file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /** * @title ClubrarePresale * @notice It distributes MPWR tokens to ILO users. */ contract ClubrarePresale is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable, PausableUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable public mpwrToken; /// @dev Prasale active / inactive bool public saleActive; /// @dev Merkle root for a whitelist users bytes32 private merkleRoot; /// @dev Price to participate in presale uint256 public tokenPrice; /// @dev How many tokens user will get in Presale uint256 public tokenPerUser; /// @dev Total ETH Raised in Presale uint256 public totalRaised; /// @dev User info who participated in Presale struct UserInfo { uint256 tokensClaimed; uint256 startTime; uint256 endTime; uint256 lastClaimedTime; uint256 tokenPerSeconds; uint256 tokenPerUser; bool isDone; } mapping(address => UserInfo) public userInfo; event Claimed(address indexed user, uint256 claimAmount); event Harvest(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event WithdrawToken(address indexed user, uint256 amount); /** * @notice Initializer * * @param _mpwrToken MPWR token address */ function initialize(address _mpwrToken) external initializer { require(_mpwrToken != address(0), "Invalid token address"); __Context_init(); __Ownable_init(); __ReentrancyGuard_init(); __Pausable_init(); mpwrToken = IERC20Upgradeable(_mpwrToken); tokenPrice = 1 ether; tokenPerUser = 100 ether; _pause(); } /** * @notice Update Merkel Root to Whitelist users * @param _merkleRoot for whitelist users */ function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } /** * @notice Update Token Price * @param _tokenPrice Eth price for Presale */ function updateTokenPrice(uint256 _tokenPrice) external onlyOwner { tokenPrice = _tokenPrice; } /** * @notice Update Token per User * @param _tokenPerUser MPWR token for per user */ function updateTokenPerUser(uint256 _tokenPerUser) external onlyOwner { tokenPerUser = _tokenPerUser; } /** * @notice Unpause presale */ function unpause() external onlyOwner { _unpause(); } /** * @notice pause presale */ function pause() external onlyOwner { _pause(); } /** * @notice on/off presale */ function toggleSale() external onlyOwner { saleActive = !saleActive; } /** * @notice get curren active merkel root */ function getMerkleRoot() external view returns (bytes32) { return merkleRoot; } /** * @notice check user whitelist or not * @param _merkleProof merkelProof generated by MerkelTree for current MerkelRoot */ function checkWhitelist(bytes32[] memory _merkleProof) external view returns (bool) { bytes32 sender = keccak256(abi.encodePacked(_msgSender())); return MerkleProof.verify(_merkleProof, merkleRoot, sender); } /** * @notice calculate token per seconds for 1 year */ function _getTokenPerSeconds() internal view returns (uint256) { return tokenPerUser.div(365).div(24).div(60).div(60); } /** * @notice internal method to calculate Claimable Amount * @param _endTime current block time * @param _user user address * @dev calculate pending rewards from last withdraw time to current time */ function _calculateTokens(uint256 _endTime, address _user) internal view returns (uint256) { UserInfo memory uInfo = userInfo[_user]; uint256 _from = uInfo.lastClaimedTime; uint256 _totalTime = _endTime.sub(_from); if (_totalTime <= 0) { return 0; } return _totalTime.mul(uInfo.tokenPerSeconds); } /** * @notice Harvest in Presale by current ETH price * @param _merkleProof merkelProof generated by MerkelTree for current MerkelRoot to verify its whitelist or not * @dev Only whitelist user can harvest and it will give MPWR token set in tokenPerUser */ function harvest(bytes32[] memory _merkleProof) external payable whenNotPaused nonReentrant { require(saleActive, "Sale is not active"); UserInfo storage uInfo = userInfo[_msgSender()]; require(!uInfo.isDone, "Already Participated"); require(msg.value == tokenPrice, "Wrong Value!"); bytes32 sender = keccak256(abi.encodePacked(_msgSender())); require(MerkleProof.verify(_merkleProof, merkleRoot, sender), "You are not whitelisted"); uInfo.startTime = block.timestamp; uInfo.endTime = block.timestamp + 365 days; uInfo.lastClaimedTime = block.timestamp; uInfo.tokenPerSeconds = _getTokenPerSeconds(); uInfo.tokenPerUser = tokenPerUser; uInfo.isDone = true; totalRaised += msg.value; emit Harvest(_msgSender(), msg.value); } /** * @notice Claim Rewards * @dev User who harvest can claim their rewards in MPWR for 1 year */ function claimReward() external whenNotPaused nonReentrant { UserInfo storage uInfo = userInfo[_msgSender()]; require(uInfo.isDone, "You are not eligible to claim this rewards!"); require(uInfo.endTime > uInfo.lastClaimedTime, "You already claimed!"); uint256 endTime = block.timestamp; if (endTime > uInfo.endTime) { endTime = uInfo.endTime; } uint256 _rewards = _calculateTokens(endTime, _msgSender()); require(_rewards > 0, "Not available to claim"); uInfo.lastClaimedTime = endTime; uInfo.tokensClaimed += _rewards; mpwrToken.safeTransfer(_msgSender(), _rewards); emit Claimed(_msgSender(), _rewards); } /** * @notice Calculate Claimable Amount * @param _user userAddress to calculate Tokens */ function calculateTokens(address _user) external view returns (uint256) { UserInfo memory uInfo = userInfo[_user]; if (!uInfo.isDone) { return 0; } if (uInfo.endTime <= uInfo.lastClaimedTime) { return 0; } uint256 _endTime = block.timestamp; if (_endTime > uInfo.endTime) { _endTime = uInfo.endTime; } return _calculateTokens(_endTime, _user); } /** * @notice Withdraw ETH balance raised in contract * @param _to address where to withdraw */ function withdraw(address _to) external onlyOwner { require(_to != address(0), "address is invalid"); payable(_to).transfer(address(this).balance); emit Withdraw(_to, address(this).balance); } /** * @notice Withdraw MPWR token from contract * @param _to address where to withdraw */ function withdrawToken(address _to) external onlyOwner { require(_to != address(0), "address is invalid"); mpwrToken.safeTransfer(_to, mpwrToken.balanceOf(address(this))); emit WithdrawToken(_to, mpwrToken.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; 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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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 onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) 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 onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // 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 IERC20Upgradeable { /** * @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 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable 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( IERC20Upgradeable 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( IERC20Upgradeable 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(IERC20Upgradeable 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.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/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 onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _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 This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library 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) { 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 (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [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 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; 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 onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
Claim Rewards User who harvest can claim their rewards in MPWR for 1 year/
function claimReward() external whenNotPaused nonReentrant { UserInfo storage uInfo = userInfo[_msgSender()]; require(uInfo.isDone, "You are not eligible to claim this rewards!"); require(uInfo.endTime > uInfo.lastClaimedTime, "You already claimed!"); uint256 endTime = block.timestamp; if (endTime > uInfo.endTime) { endTime = uInfo.endTime; } uint256 _rewards = _calculateTokens(endTime, _msgSender()); require(_rewards > 0, "Not available to claim"); uInfo.lastClaimedTime = endTime; uInfo.tokensClaimed += _rewards; mpwrToken.safeTransfer(_msgSender(), _rewards); emit Claimed(_msgSender(), _rewards); }
14,785,000
./full_match/1/0x977D360c3FbE1533eFEde3619dC74Ad0950FFc4f/sources/contracts/BondSwap/Exchange/BondsMarketplace.sol
Check whether user order nonce is executed or cancelled user address of user orderNonce nonce of the order/
function isUserOrderNonceExecutedOrCancelled(address user, uint256 orderNonce) external view returns (bool) { return _isUserOrderNonceExecutedOrCancelled[user][orderNonce]; }
16,426,676
./partial_match/1/0x5cD48e98bd39b3C3E1586687B3eA7F54D9e465a9/sources/ERC20Token.sol
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); 🐾PAW PAD - IDO Platform leverages decentralized }
3,901,955
pragma solidity ^0.4.0; /** * @title Multi Sender, support ETH and ERC20 Tokens * @dev To Use this Dapp: http://multisender.phizhub.com */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a); return c; } 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 Multi Sender, support ETH and ERC20 Tokens * @dev To Use this Dapp: http://multisender.phizhub.com */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Multi Sender, support ETH and ERC20 Tokens * @dev To Use this Dapp: http://multisender.phizhub.com */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; function transfer(address _to, uint _value) public{ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } } /** * @title Multi Sender, support ETH and ERC20 Tokens * @dev To Use this Dapp: http://multisender.phizhub.com */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) public { balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint _value) public{ require((_value == 0) || (allowed[msg.sender][_spender] == 0)) ; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Multi Sender, support ETH and ERC20 Tokens * @dev To Use this Dapp: http://multisender.phizhub.com */ contract Ownable { address public owner; function Ownable() public{ owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public{ if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Multi Sender, support ETH and ERC20 Tokens * @dev To Use this Dapp: http://multisender.phizhub.com */ contract MultiSender is Ownable{ using SafeMath for uint; event LogTokenMultiSent(address token,uint256 total); event LogGetToken(address token, address receiver, uint256 balance); address public receiverAddress; uint public txFee = 0.01 ether; uint public VIPFee = 1 ether; /* VIP List */ mapping(address => bool) public vipList; /* * get balance */ function getBalance(address _tokenAddress) onlyOwner public { address _receiverAddress = getReceiverAddress(); if(_tokenAddress == address(0)){ require(_receiverAddress.send(address(this).balance)); return; } StandardToken token = StandardToken(_tokenAddress); uint256 balance = token.balanceOf(this); token.transfer(_receiverAddress, balance); emit LogGetToken(_tokenAddress,_receiverAddress,balance); } /* * Register VIP */ function registerVIP() payable public { require(msg.value >= VIPFee); vipList[msg.sender] = true; require(receiverAddress.send(msg.value)) ; } /* * VIP list */ function addToVIPList(address[] _vipList) onlyOwner public { for (uint i =0;i<_vipList.length;i++){ vipList[_vipList[i]] = true; } } /* * Remove address from VIP List by Owner */ function removeFromVIPList(address[] _vipList) onlyOwner public { for (uint i =0;i<_vipList.length;i++){ vipList[_vipList[i]] = false; } } /* * Check isVIP */ function isVIP(address _addr) public view returns (bool) { return _addr == owner || vipList[_addr]; } /* * set receiver address */ function setReceiverAddress(address _addr) onlyOwner public { require(_addr != address(0)); receiverAddress = _addr; } /* * get receiver address */ function getReceiverAddress() public view returns (address){ if(receiverAddress == address(0)){ return owner; } return receiverAddress; } /* * set vip fee */ function setVIPFee(uint _fee) onlyOwner public { VIPFee = _fee; } /* * set tx fee */ function setTxFee(uint _fee) onlyOwner public { txFee = _fee; } function ethSendSameValue(address[] _to, uint _value) internal { uint sendAmount = _to.length.sub(1).mul(_value); uint remainingValue = msg.value; bool vip = isVIP(msg.sender); if(vip){ require(remainingValue >= sendAmount); }else{ require(remainingValue >= sendAmount.add(txFee)) ; } require(_to.length <= 255); for (uint8 i = 1; i < _to.length; i++) { remainingValue = remainingValue.sub(_value); require(_to[i].send(_value)); } emit LogTokenMultiSent(0x000000000000000000000000000000000000bEEF,sendAmount.sub(txFee)); } function ethSendDifferentValue(address[] _to, uint[] _value) internal { uint sendAmount = _value[0]; uint remainingValue = msg.value; bool vip = isVIP(msg.sender); if(vip){ require(remainingValue >= sendAmount); }else{ require(remainingValue >= sendAmount.add(txFee)) ; } require(_to.length == _value.length); require(_to.length <= 255); for (uint8 i = 1; i < _to.length; i++) { remainingValue = remainingValue.sub(_value[i]); require(_to[i].send(_value[i])); } emit LogTokenMultiSent(0x000000000000000000000000000000000000bEEF,sendAmount.sub(txFee)); } function coinSendSameValue(address _tokenAddress, address[] _to, uint _value) internal { uint sendValue = msg.value; bool vip = isVIP(msg.sender); if(!vip){ require(sendValue >= txFee); } require(_to.length <= 255); address from = msg.sender; address to = address(this); uint256 sendAmount = _to.length.sub(1).mul(_value); StandardToken token = StandardToken(_tokenAddress); token.transferFrom(from,to,sendAmount); for (uint8 i = 1; i < _to.length; i++) { token.transfer(_to[i], _value); } emit LogTokenMultiSent(_tokenAddress,sendAmount); } function coinSendDifferentValue(address _tokenAddress, address[] _to, uint[] _value) internal { uint sendValue = msg.value; bool vip = isVIP(msg.sender); if(!vip){ require(sendValue >= txFee); } require(_to.length == _value.length); require(_to.length <= 255); address from = msg.sender; address to = address(this); uint256 sendAmount = _value[0]; StandardToken token = StandardToken(_tokenAddress); token.transferFrom(from,to,sendAmount); for (uint8 i = 1; i < _to.length; i++) { token.transfer(_to[i], _value[i]); } emit LogTokenMultiSent(_tokenAddress,sendAmount); } /* Send ether with the same value by a explicit call method */ function sendEth(address[] _to, uint _value) payable public { ethSendSameValue(_to,_value); } /* Send ether with the different value by a explicit call method */ function multisend(address[] _to, uint[] _value) payable public { ethSendDifferentValue(_to,_value); } /* Send ether with the different value by a implicit call method */ function mutiSendETHWithDifferentValue(address[] _to, uint[] _value) payable public { ethSendDifferentValue(_to,_value); } /* Send ether with the same value by a implicit call method */ function mutiSendETHWithSameValue(address[] _to, uint _value) payable public { ethSendSameValue(_to,_value); } /* Send coin with the same value by a implicit call method */ function mutiSendCoinWithSameValue(address _tokenAddress, address[] _to, uint _value) payable public { coinSendSameValue(_tokenAddress, _to, _value); } /* Send coin with the different value by a implicit call method, this method can save some fee. */ function mutiSendCoinWithDifferentValue(address _tokenAddress, address[] _to, uint[] _value) payable public { coinSendDifferentValue(_tokenAddress, _to, _value); } /* Send coin with the different value by a explicit call method */ function multisendToken(address _tokenAddress, address[] _to, uint[] _value) payable public { coinSendDifferentValue(_tokenAddress, _to, _value); } /* Send coin with the same value by a explicit call method */ function drop(address _tokenAddress, address[] _to, uint _value) payable public { coinSendSameValue(_tokenAddress, _to, _value); } }
set receiver address/
function setReceiverAddress(address _addr) onlyOwner public { require(_addr != address(0)); receiverAddress = _addr; }
65,367
pragma solidity ^0.4.18; import "../ownership/Ownable.sol"; import "../math/SafeMath.sol"; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { using SafeMath for uint256; event Pause(); event Unpause(); bool public paused = false; address public crowdsale; /* * @dev Freezing certain number of tokens bought during bonus. */ mapping (address => uint256) public frozen; uint public unfreezeTimestamp; function Pausable() public { unfreezeTimestamp = now + 60 days; //default 60 days from contract deploy date as a defensive mechanism. Will be updated once the crowdsale starts. } function setUnfreezeTimestamp(uint _unfreezeTimestamp) onlyOwner public { require(now < _unfreezeTimestamp); unfreezeTimestamp = _unfreezeTimestamp; } function increaseFrozen(address _owner, uint256 _incrementalAmount) public returns (bool) { require(msg.sender == crowdsale || msg.sender == owner); require(_incrementalAmount > 0); frozen[_owner] = frozen[_owner].add(_incrementalAmount); return true; } function decreaseFrozen(address _owner, uint256 _incrementalAmount) public returns (bool) { require(msg.sender == crowdsale || msg.sender == owner); require(_incrementalAmount > 0); frozen[_owner] = frozen[_owner].sub(_incrementalAmount); return true; } function setCrowdsale(address _crowdsale) onlyOwner public { crowdsale = _crowdsale; } /** * @dev Modifier to make a function callable only when there are unfrozen tokens. */ modifier frozenTransferCheck(address _to, uint256 _value, uint256 balance) { if (now < unfreezeTimestamp) { require(_value <= balance.sub(frozen[msg.sender])); } _; } modifier frozenTransferFromCheck(address _from, address _to, uint256 _value, uint256 balance) { if (now < unfreezeTimestamp) { require(_value <= balance.sub(frozen[_from])); } _; } /** * @dev Modifier to make a function callable only when the contract is not paused. [Exception: crowdsale contract] */ modifier whenNotPaused() { require(!paused || msg.sender == crowdsale); _; } /** * @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 { require(msg.sender != address(0)); paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { require(msg.sender != address(0)); paused = false; emit Unpause(); } }
called by the owner to pause, triggers stopped state/
function pause() onlyOwner whenNotPaused public { require(msg.sender != address(0)); paused = true; emit Pause(); }
2,555,008
/** Chip */ pragma solidity ^0.8.9; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { //function _msgSender() internal view virtual returns (address payable) { 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; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } 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; } 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; } 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); } 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; } interface IAirdrop { function airdrop(address recipient, uint256 amount) external; } contract CHIPPY is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address public marketingWallet; string private _name = "Chippy"; string private _symbol = "CHIP"; uint8 private _decimals = 9; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 public marketingFeePercent = 90; uint256 public _liquidityFee = 5; uint256 private _previousLiquidityFee = _liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 100000 * 10**9; uint256 public numTokensSellToAddToLiquidity = 100000 * 10**9; uint256 public _maxWalletSize = 200000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } 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 airdrop(address recipient, uint256 amount) external onlyOwner() { removeAllFee(); _transfer(_msgSender(), recipient, amount * 10**9); restoreAllFee(); } function airdropInternal(address recipient, uint256 amount) internal { removeAllFee(); _transfer(_msgSender(), recipient, amount); restoreAllFee(); } function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){ uint256 iterator = 0; require(newholders.length == amounts.length, "must be the same length"); while(iterator < newholders.length){ airdropInternal(newholders[iterator], amounts[iterator] * 10**9); iterator += 1; } } 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(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); 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 _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 excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMarketingFeePercent(uint256 fee) public onlyOwner { marketingFeePercent = fee; } function setMarketingWallet(address walletAddress) public onlyOwner { marketingWallet = walletAddress; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require(taxFee < 10, "Tax fee cannot be more than 10%"); _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function _setMaxWalletSizePercent(uint256 maxWalletSize) external onlyOwner { _maxWalletSize = _tTotal.mul(maxWalletSize).div(10**3); } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount > 200000, "Max Tx Amount cannot be less than 69 Million"); _maxTxAmount = maxTxAmount * 10**9; } function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() { require(SwapThresholdAmount > 200000, "Swap Threshold Amount cannot be less than 69 Million"); numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9; } function claimTokens () public onlyOwner { // make sure we capture all BNB that may or may not be sent to this contract payable(marketingWallet).transfer(address(this).balance); } function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() { tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this))); } function clearStuckBalance (address payable walletaddress) external onlyOwner() { walletaddress.transfer(address(this).balance); } function addBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function allowtrading()external onlyOwner() { canTrade = true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} 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 _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"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } if (takeFee) { if (to != uniswapV2Pair) { require( amount + balanceOf(to) <= _maxWalletSize, "Recipient exceeds max wallet size." ); } } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves // add the marketing wallet uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); uint256 marketingshare = newBalance.mul(marketingFeePercent).div(100); payable(marketingWallet).transfer(marketingshare); newBalance -= marketingshare; // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } 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]) { _transferStandard(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); } }
SPDX-License-Identifier: Unlicensed
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); Chip }
10,228,169
./full_match/9001/0xb31c8f06F99Be1285Cb1998949F47E1988f38b23/sources/src/token/ERC721/facets/minting/ERC721MintableOwnable.sol
@inheritdoc IERC721MintableOwnable/
function mintByOwner(address[] calldata tos, uint256[] calldata amounts) public virtual onlyOwner { IERC721MintableExtension(address(this)).mintByFacet(tos, amounts); }
11,533,999
./full_match/42220/0x63aFE99b010208EE07673C0CF31Cc4026eD90FF7/sources/contracts/UniswapLiquiditySwapAdapter.sol
Swaps an exact `amountToSwap` of an asset to another assetToSwapFromPrice Origin asset to get price assetToSwapToPrice Destination asset to get pricce assetToSwapFrom Origin asset assetToSwapTo Destination asset amountToSwap Exact amount of `assetToSwapFrom` to be swapped minAmountOut the min amount of `assetToSwapTo` to be received from the swap return the amount received from the swap/ Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
function _swapExactTokensForTokens( address assetToSwapFromPrice, address assetToSwapToPrice, address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFromPrice); uint256 toAssetDecimals = _getDecimals(assetToSwapToPrice); uint256 fromAssetPrice = _getPrice(assetToSwapFromPrice); uint256 toAssetPrice = _getPrice(assetToSwapToPrice); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; }
16,315,829
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../interfaces/INFTComplexGemPool.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../interfaces/IERC3156FlashLender.sol"; import "../libs/AddressSet.sol"; import "./NFTComplexGemPoolData.sol"; contract NFTComplexGemPool is NFTComplexGemPoolData, INFTComplexGemPool, IERC3156FlashLender, ERC1155Holder { using AddressSet for AddressSet.Set; using ComplexPoolLib for ComplexPoolLib.ComplexPoolData; /** * @dev Add an address allowed to control this contract */ function addController(address _controllerAddress) external { require( poolData.controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); poolData.controllers[_controllerAddress] = true; } /** * @dev Check if this address is a controller */ function isController(address _controllerAddress) external view returns (bool) { return poolData.controllers[_controllerAddress]; } /** * @dev Remove the sender's address from the list of controllers */ function relinquishControl() external { require( poolData.controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); delete poolData.controllers[msg.sender]; } constructor() { poolData.controllers[msg.sender] = true; } /** * @dev initializer called when contract is deployed */ function initialize( string memory _symbol, string memory _name, uint256 _ethPrice, uint256 _minTime, uint256 _maxTime, uint256 _diffstep, uint256 _maxClaims, address _allowedToken ) external override onlyController { poolData.pool = address(this); poolData.symbol = _symbol; poolData.name = _name; poolData.ethPrice = _ethPrice; poolData.minTime = _minTime; poolData.maxTime = _maxTime; poolData.diffstep = _diffstep; poolData.maxClaims = _maxClaims; poolData.visible = true; poolData.enabled = true; if (_allowedToken != address(0)) { poolData.allowedTokens.insert(_allowedToken); } } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setGovernor(address _governorAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.governor = _governorAddress; } /** * @dev set the fee tracker. pool uses the fee tracker to issue fee tracker token issuance requests */ function setFeeTracker(address _feeTrackerAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.feeTracker = _feeTrackerAddress; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setMultiToken(address _multiTokenAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.multitoken = _multiTokenAddress; } /** * @dev set the AMM swap helper that gets token prices */ function setSwapHelper(address _swapHelperAddress) external override { require( poolData.controllers[msg.sender] = true || msg.sender == poolData.governor, "UNAUTHORIZED" ); poolData.swapHelper = _swapHelperAddress; } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems(address _creatorAddress, address _funderAddress) external override { // security checks for this method are in the library - this // method may only be called one time per new pool creation poolData.mintGenesisGems(_creatorAddress, _funderAddress); } /** * @dev create a single claim with given timeframe */ function createClaim(uint256 _timeframe) external payable override { poolData.createClaims(_timeframe, 1); } /** * @dev create multiple claims with given timeframe */ function createClaims(uint256 _timeframe, uint256 _count) external payable override { poolData.createClaims(_timeframe, _count); } /** * @dev purchase gems */ function purchaseGems(uint256 _count) external payable override { poolData.purchaseGems(msg.sender, msg.value, _count); } /** * @dev create a claim using a erc20 token */ function createERC20Claim(address _erc20TokenAddress, uint256 _tokenAmount) external override { poolData.createERC20Claims(_erc20TokenAddress, _tokenAmount, 1); } /** * @dev create a claim using a erc20 token */ function createERC20Claims( address _erc20TokenAddress, uint256 _tokenAmount, uint256 _count ) external override { poolData.createERC20Claims(_erc20TokenAddress, _tokenAmount, _count); } /** * @dev collect an open claim (take custody of the funds the claim is redeemable for and maybe a gem too) */ function collectClaim(uint256 _claimHash, bool _requireMature) external override { poolData.collectClaim(_claimHash, _requireMature); } /** * @dev The maximum flash loan amount - 90% of available funds */ function maxFlashLoan(address tokenAddress) external view override returns (uint256) { // if the token address is zero then get the FTM balance // other wise get the token balance of the given token address return tokenAddress == address(0) ? address(this).balance : IERC20(tokenAddress).balanceOf(address(this)); } /** * @dev The flash loan fee - 0.1% of borrowed funds */ function flashFee(address token, uint256 amount) public view override returns (uint256) { // get hash of flash fee key using token address uint256 flashFeeHash = uint256( keccak256(abi.encodePacked("flash_loan", address(token))) ); // get the flash fee from the storage uint256 feeDiv = INFTGemFeeManager(poolData.feeTracker).fee( flashFeeHash ); // if the flash fee is not set, get the default fee if (feeDiv == 0) { flashFeeHash = uint256(keccak256(abi.encodePacked("flash_loan"))); feeDiv = INFTGemFeeManager(poolData.feeTracker).fee(flashFeeHash); } // if no default fee, set the fee to 10000 (0.01%) if (feeDiv == 0) { feeDiv = 10000; } return amount / feeDiv; } /** * @dev Perform a flash loan (borrow tokens from the controller and return them after a certain time) */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external override returns (bool) { // get the fee of the flash loan uint256 fee = flashFee(token, amount); // get the receiver's address address receiverAddress = address(receiver); // no token address means we are sending FTM if (token == address(0)) { payable(receiverAddress).transfer(amount); } else { // else we are sending erc20 tokens IERC20(token).transfer(receiverAddress, amount); } // get the balance of the lender - base token if address is 0 // or erc20 token if address is not 0 uint256 initialBalance = token == address(0) ? address(this).balance : IERC20(token).balanceOf(address(this)); // create success callback hash bytes32 callbackSuccess = keccak256("ERC3156FlashBorrower.onFlashLoan"); // call the flash loan callback require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == callbackSuccess, "FlashMinter: Callback failed" ); // check if the flash loan is finished // first we get the balance of the lender uint256 _allowance = address(this).balance; if (token != address(0)) { // if the token is erc20 we need // to get the allowance of the token _allowance = IERC20(token).allowance( address(receiver), address(this) ); } else { // if the token is FTM we check if the // initia balance is greater than the // allowance. If it is we set _allowance // to zero to dissallow the loan. Other if (initialBalance > _allowance) _allowance = 0; else _allowance = _allowance - initialBalance; } // if the allowance is greater than the loan amount plus // the fee then we can finish the flash loan require( _allowance >= (amount + fee), "FlashMinter: Repay not approved" ); return true; } }
The maximum flash loan amount - 90% of available funds/ if the token address is zero then get the FTM balance other wise get the token balance of the given token address
function maxFlashLoan(address tokenAddress) external view override returns (uint256) { return tokenAddress == address(0) ? address(this).balance : IERC20(tokenAddress).balanceOf(address(this)); }
888,468
pragma solidity ^0.4.24; 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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Withdrawable is Ownable { event ReceiveEther(address _from, uint256 _value); event WithdrawEther(address _to, uint256 _value); event WithdrawToken(address _token, address _to, uint256 _value); /** * @dev recording receiving ether from msn.sender */ function () payable public { emit ReceiveEther(msg.sender, msg.value); } /** * @dev withdraw,send ether to target * @param _to is where the ether will be sent to * _amount is the number of the ether */ function withdraw(address _to, uint _amount) public onlyOwner returns (bool) { require(_to != address(0)); _to.transfer(_amount); emit WithdrawEther(_to, _amount); return true; } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _to is where the tokens will be sent to * _value is the number of the token */ function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_token != address(0)); ERC20 tk = ERC20(_token); tk.transfer(_to, _value); emit WithdrawToken(_token, _to, _value); return true; } /** * @dev receive approval from an ERC20 token contract, and then gain the tokens, * then take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ // function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public { // require(_token != address(0)); // require(_from != address(0)); // ERC20 tk = ERC20(_token); // require(tk.transferFrom(_from, this, _value)); // emit ReceiveDeposit(_from, _value, _token, _extraData); // } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract DRCWalletStorage is Withdrawable, Claimable { using SafeMath for uint256; /** * withdraw wallet description */ struct WithdrawWallet { bytes32 name; address walletAddr; } /** * Deposit data storage */ struct DepositRepository { int256 balance; // can be negative uint256 frozen; WithdrawWallet[] withdrawWallets; // mapping (bytes32 => address) withdrawWallets; } mapping (address => DepositRepository) depositRepos; mapping (address => address) public walletDeposits; mapping (address => bool) public frozenDeposits; address[] depositAddresses; uint256 public size; /** * @dev add deposit contract address for the default withdraw wallet * * @param _wallet the default withdraw wallet address * @param _depositAddr the corresponding deposit address to the default wallet */ function addDeposit(address _wallet, address _depositAddr) onlyOwner public returns (bool) { require(_wallet != address(0)); require(_depositAddr != address(0)); walletDeposits[_wallet] = _depositAddr; WithdrawWallet[] storage withdrawWalletList = depositRepos[_depositAddr].withdrawWallets; withdrawWalletList.push(WithdrawWallet("default wallet", _wallet)); depositRepos[_depositAddr].balance = 0; depositRepos[_depositAddr].frozen = 0; depositAddresses.push(_depositAddr); size = size.add(1); return true; } /** * @dev remove an address from the deposit address list * * @param _deposit the deposit address in the list */ function removeDepositAddress(address _deposit) internal returns (bool) { uint i = 0; for (;i < depositAddresses.length; i = i.add(1)) { if (depositAddresses[i] == _deposit) { break; } } if (i >= depositAddresses.length) { return false; } while (i < depositAddresses.length.sub(1)) { depositAddresses[i] = depositAddresses[i.add(1)]; i = i.add(1); } delete depositAddresses[depositAddresses.length.sub(1)]; depositAddresses.length = depositAddresses.length.sub(1); return true; } /** * @dev remove deposit contract address from storage * * @param _depositAddr the corresponding deposit address */ function removeDeposit(address _depositAddr) onlyOwner public returns (bool) { require(isExisted(_depositAddr)); WithdrawWallet memory withdraw = depositRepos[_depositAddr].withdrawWallets[0]; delete walletDeposits[withdraw.walletAddr]; delete depositRepos[_depositAddr]; delete frozenDeposits[_depositAddr]; removeDepositAddress(_depositAddr); size = size.sub(1); return true; } /** * @dev add withdraw address for one deposit addresss * * @param _deposit the corresponding deposit address * @param _name the new withdraw wallet name * @param _withdraw the new withdraw wallet address */ function addWithdraw(address _deposit, bytes32 _name, address _withdraw) onlyOwner public returns (bool) { require(_deposit != address(0)); WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; withdrawWalletList.push(WithdrawWallet(_name, _withdraw)); return true; } /** * @dev increase balance of this deposit address * * @param _deposit the corresponding deposit address * @param _value the amount that the balance will be increased */ function increaseBalance(address _deposit, uint256 _value) onlyOwner public returns (bool) { // require(_deposit != address(0)); require (walletsNumber(_deposit) > 0); int256 _balance = depositRepos[_deposit].balance; depositRepos[_deposit].balance = _balance + int256(_value); return true; } /** * @dev decrease balance of this deposit address * * @param _deposit the corresponding deposit address * @param _value the amount that the balance will be decreased */ function decreaseBalance(address _deposit, uint256 _value) onlyOwner public returns (bool) { // require(_deposit != address(0)); require (walletsNumber(_deposit) > 0); int256 _balance = depositRepos[_deposit].balance; depositRepos[_deposit].balance = _balance - int256(_value); return true; } /** * @dev change the default withdraw wallet address binding to the deposit contract address * * @param _oldWallet the old default withdraw wallet * @param _newWallet the new default withdraw wallet */ function changeDefaultWallet(address _oldWallet, address _newWallet) onlyOwner public returns (bool) { require(_oldWallet != address(0)); require(_newWallet != address(0)); address _deposit = walletDeposits[_oldWallet]; WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; withdrawWalletList[0].walletAddr = _newWallet; // emit ChangeDefaultWallet(_oldWallet, _newWallet); walletDeposits[_newWallet] = _deposit; delete walletDeposits[_oldWallet]; return true; } /** * @dev change the name of the withdraw wallet address of the deposit contract address * * @param _deposit the deposit address * @param _newName the wallet name * @param _wallet the withdraw wallet */ function changeWalletName(address _deposit, bytes32 _newName, address _wallet) onlyOwner public returns (bool) { require(_deposit != address(0)); require(_wallet != address(0)); uint len = walletsNumber(_deposit); // default wallet name do not change for (uint i = 1; i < len; i = i.add(1)) { WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[i]; if (_wallet == wallet.walletAddr) { wallet.name = _newName; return true; } } return false; } /** * @dev freeze the tokens in the deposit address * * @param _deposit the deposit address * @param _freeze to freeze or release * @param _value the amount of tokens need to be frozen */ function freezeTokens(address _deposit, bool _freeze, uint256 _value) onlyOwner public returns (bool) { require(_deposit != address(0)); // require(_value <= balanceOf(_deposit)); frozenDeposits[_deposit] = _freeze; uint256 _frozen = depositRepos[_deposit].frozen; int256 _balance = depositRepos[_deposit].balance; int256 freezeAble = _balance - int256(_frozen); freezeAble = freezeAble < 0 ? 0 : freezeAble; if (_freeze) { if (_value > uint256(freezeAble)) { _value = uint256(freezeAble); } depositRepos[_deposit].frozen = _frozen.add(_value); } else { if (_value > _frozen) { _value = _frozen; } depositRepos[_deposit].frozen = _frozen.sub(_value); } return true; } /** * @dev get the wallet address for the deposit address * * @param _deposit the deposit address * @param _ind the wallet index in the list */ function wallet(address _deposit, uint256 _ind) public view returns (address) { require(_deposit != address(0)); WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; return withdrawWalletList[_ind].walletAddr; } /** * @dev get the wallet name for the deposit address * * @param _deposit the deposit address * @param _ind the wallet index in the list */ function walletName(address _deposit, uint256 _ind) public view returns (bytes32) { require(_deposit != address(0)); WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; return withdrawWalletList[_ind].name; } /** * @dev get the wallet name for the deposit address * * @param _deposit the deposit address */ function walletsNumber(address _deposit) public view returns (uint256) { require(_deposit != address(0)); WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; return withdrawWalletList.length; } /** * @dev get the balance of the deposit account * * @param _deposit the wallet address */ function isExisted(address _deposit) public view returns (bool) { return (walletsNumber(_deposit) > 0); } /** * @dev get the balance of the deposit account * * @param _deposit the deposit address */ function balanceOf(address _deposit) public view returns (int256) { require(_deposit != address(0)); return depositRepos[_deposit].balance; } /** * @dev get the frozen amount of the deposit address * * @param _deposit the deposit address */ function frozenAmount(address _deposit) public view returns (uint256) { require(_deposit != address(0)); return depositRepos[_deposit].frozen; } /** * @dev get the deposit address by index * * @param _ind the deposit address index */ function depositAddressByIndex(uint256 _ind) public view returns (address) { return depositAddresses[_ind]; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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 ); }
get the wallet address for the deposit address _deposit the deposit address _ind the wallet index in the list/
function wallet(address _deposit, uint256 _ind) public view returns (address) { require(_deposit != address(0)); WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; return withdrawWalletList[_ind].walletAddr; }
13,077,061
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; //Track Token Supply //This might be an overkill... //TODO: Get rid of this! import "@openzeppelin/contracts/utils/Counters.sol"; /** * This is a simple Offer Contract * Used to manage the sale lifecycle * Version 0.2.0 */ // contract Offers is ERC1155 { contract Offers is ERC1155Supply { using Counters for Counters.Counter; Counters.Counter private _tokenIds; //Track Last Token ID mapping(uint256 => string) private _tokenURIs; // Mapping for token URIs mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _used; // Mapping from token ID to account's Negative balances (Offers Redeemed) string[] public status_name = ['cancelled','requested','delivered','closed']; //Status Names [0 - as cancelled] struct Order { uint8 status; //Request Stage address account; // string request_uri; //Delivery Stage // string delivery_uri; //Approval Stage // uint8 score; //Review as an Event // string review_uri; } // mapping(uint256 => Order) _orders; //? How to Save Offer IDs...? [tokenId+] // token_id => Orders mapping(uint256 => mapping(uint256 => Order)) private _orders; // Track Individual Orders // token_id => Order_id => Order // mapping(uint256 => uint256) public _orderCount; //Track Last Order ID // token_id => last_order_id // mapping(uint256 => Counters.Counter) private _orderCount; //Track Last Order ID // token_id => last_order_id mapping(uint256 => uint256) private _orderCount; mapping(uint256 => uint256) private _prices; // Token Prices mapping(uint256 => uint256) private _deposits; // Pending Payments (Escrow) mapping(uint256 => address) public _creators; mapping(uint256 => uint256) public _maxSupply; // mapping(uint256 => uint256) private _totalSupply; //Inherit From ERC1155Supply // Contract name string public name = 'Offers'; // Contract symbol string public symbol = 'OFFER'; // Deployer address private _owner; constructor() ERC1155('') { //Remember Deployer _owner = msg.sender; // _mint(msg.sender, 0, 10**18, ""); } //-- Modifiers /** UNNECESSARY * @dev Require msg.sender to be the creator of the token id modifier creatorOnly(uint256 _id) { require(_creators[_id] == msg.sender, "CREATOR_ONLY"); _; } */ /** UNUSED * @dev Require msg.sender to own more than 0 of the token id modifier ownersOnly(uint256 _id) { require(balances[msg.sender][_id] > 0, "OWNER_ONLY"); // require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED"); _; } */ //-- Events /** * New Offer Made */ event _offer(uint256 indexed token_id, address account, string uri); // File an Order /** * Offer Sold */ event _sold(uint256 indexed token_id, address account); // File an Order /** * Offer Request - New Order * uint256 tokenId //Token ID * string URI //Details URI * address account //Requesting Account */ event _order(uint256 indexed token_id, uint256 order_id, address account, string uri); /** * Refund Issued */ event _delivery(uint256 indexed token_id, uint256 order_id, string uri); // Refund Event /** * Refund Issued */ // event _refund(uint256 indexed token_id, address account); // Refund Event /** * Review Posted */ event _review(address provider, address customer, uint256 rating, string uri); // Review Provider (rating + details URI) // mapping(uint256 => string) private _tokenURIs; // Mapping for token URIs (Taken From ERC721) /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. */ 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) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 credit = creditOf(from, id); //Check for Sufficient Credit require(credit >= amount, "INSUFFICIENT_CREDIT"); } } } //-- Getters /** * Expose Contract Owner */ function owner() public view returns (address) { return _owner; } /** * Get Available (Unused) Balance (Credit) */ function creditOf(address account, uint256 token_id) public view returns (uint256) { require (account != address(0), "INVALID_ADDRESS"); require (exists(token_id), "NONEXISTENT_TOKEN"); // return ( balanceOf(account, token_id) - _used[token_id][account] ); return ( balanceOf(account, token_id) - usedBalanceOf(account, token_id) ); } // function credit(uint256 token_id) public view returns (uint256) { // return creditOf(_msgSender(), token_id); // } /** * Balance Used */ function usedBalanceOf(address account, uint256 token_id) public view returns (uint256) { require(account != address(0), "INVALID_ADDRESS"); return _used[token_id][account]; } /** * Get Token URI */ // function tokenURI(uint256 token_id) public view returns (string memory) { // require(exists(token_id), "NONEXISTENT_TOKEN"); // return _tokenURIs[token_id]; // } function uri(uint256 token_id) public view override returns (string memory) { require(exists(token_id), "NONEXISTENT_TOKEN"); return _tokenURIs[token_id]; } /** * Get Token Price */ function price(uint256 token_id) public view returns (uint256) { return _prices[token_id]; } /** * Get Pending Deposits */ function tokenDeposits(uint256 token_id) public view returns (uint256) { require(exists(token_id), "NONEXISTENT_TOKEN"); // require(_creators[token_id] == _msgSender(), "CREATOR_ONLY"); //Maybe? return _deposits[token_id]; } /** * @dev Get Pending Deposits */ function tokenSupplyAvailable(uint256 token_id) public view returns (uint256) { require(exists(token_id), "NONEXISTENT_TOKEN"); return (_maxSupply[token_id] + 1 - totalSupply(token_id)); //+1 Because First Mint Doesn't Count (Offer) } /** * @dev Get Current Order Status */ function status(uint256 token_id, uint256 order_id) public view returns (uint8) { //Validate require(existsOrder(token_id, order_id), "NONEXISTENT_ORDER"); return _orders[token_id][order_id].status; } /** * Check if Order Exists by Checking Requesting Account's Address */ function existsOrder(uint256 token_id, uint256 order_id) public view returns (bool) { return(exists(token_id) && _orders[token_id][order_id].account != address(0)); } //-- Actions /** * @dev Make a New Offer */ function sell(uint256 token_price, uint256 max_supply, string memory token_uri) public returns (uint256) { address maker = msg.sender; //? Should I Support Contracts as Makers? // address maker = _msgSender(); //Increment Token ID _tokenIds.increment(); //First is 1 uint256 token_id = _tokenIds.current(); //Validat New ID // require(exists(token_id), "NONEXISTENT_TOKEN"); //Seems Unecessary... //Mint _mint(maker, token_id, 1, ''); //Update Current Supply //TODO: 'Make' Probably Shouldn't Count... // tokenSupply[token_id] = 1; //Should Be Automatic //Set Token Max-Supply _maxSupply[token_id] = max_supply; //Set Token URI _tokenURIs[token_id] = token_uri; //Set Token Price _prices[token_id] = token_price; //Set Creator (Hook?) _creators[token_id] = maker; //Event: Token URI if (bytes(token_uri).length > 0) { emit URI(token_uri, token_id); } return token_id; } /** * @dev Take an Existing Offer (Buy Units of an existing Offering token) */ function buy(uint256 quantity, uint256 token_id) public payable { //Validat that Token Exists require(exists(token_id), "NONEXISTENT_TOKEN"); //Validate Stock require((_maxSupply[token_id] - totalSupply(token_id)) > 0, "REQ_QTY_UNAVAILABLE"); //Validate Deposit Amount require(msg.value == (_prices[token_id] * quantity), "PAYMENT_MISMATCH"); //Record Deposit _deposits[token_id] += msg.value; //Mint Units of Existing Token _mint(msg.sender, token_id, quantity, ''); // tokenSupply[token_id] = tokenSupply[token_id].add(quantity); //Done Automatically //Event: New Sale emit _sold(token_id, msg.sender); } /** * @dev Make a Request for Service -- Order (Single) */ function order(uint256 token_id, string memory request_uri) public { //Validate Credit (Spendable Balance) require(creditOf(msg.sender, token_id) > 0, "INSUFFICIENT_CREDIT"); //Mark Used _used[token_id][msg.sender] += 1; //Increment Order ID _orderCount[token_id] += 1; //New Order ID uint256 order_id = _orderCount[token_id]; //[DEV] Double Check that Order Doesn't Exist require(!existsOrder(token_id, order_id), "EXISTING_ORDER"); //Init New Order _orders[token_id][order_id] = Order({ status: 1, //requested account: msg.sender // request_uri: request_uri, // delivery_uri: '', // review_uri: '' }); //Event W/URI emit _order(token_id, order_id, msg.sender, request_uri); } /** * Deliver Order */ function deliver(uint256 token_id, uint256 order_id, string memory delivery_uri) public { //Validate Order require(existsOrder(token_id, order_id), "NONEXISTENT_ORDER"); //Validate Caller is Provider require(_msgSender() == _creators[token_id], "SELLER_ONLY"); //Validate Status 'requested' require(_orders[token_id][order_id].status == 1, "WRONG_STAGE"); //Set Status _orders[token_id][order_id].status = 2; //delivered //Event: Delivery emit _delivery(token_id, order_id, delivery_uri); } /** * Approve Delivery & Review * @param rating [ scale of 1-10 0 to skip ] */ function approve(uint256 token_id, uint256 order_id, uint256 rating, string memory review_uri) public payable { //Validate Order require(existsOrder(token_id, order_id), "NONEXISTENT_ORDER"); //Validate Status 'delivered' require(_orders[token_id][order_id].status == 2, "WRONG_STAGE"); //Validate Caller is Buyer require(_msgSender() == _orders[token_id][order_id].account, "BUYER_ONLY"); //Set Status _orders[token_id][order_id].status = 2; //delivered //Transfer Funds (+ Tip) to Creator uint256 amount = _prices[token_id] + msg.value; payable(_creators[token_id]).transfer(amount); if(_msgSender() != _creators[token_id]){ //Can't Rate Oneself //Validate Rating if(rating < 1 || rating > 10){ rating = 0; } //Event: Rate (if Not Creator) emit _review(_creators[token_id], _msgSender(), rating, review_uri); } } /** [TBD] * Request a Revision function revision(){ } */ /** [TBD] * Return unused Tokend function return(){ } */ /** [TBD] * Issue a Refund (Cancel Request) function refund( // address account, uint256 token_id ) public { //TODO: Validate Offer Owner //Mark Unused // _used[token_id][_msgSender()] = _used[token_id][_msgSender()] - 1; _used[token_id][_msgSender()] -= 1; // ! CAVEAT: Which Offer is going to be cancelled ?? Need to track offers... } */ //-- TESTS /* 0-255 uint8 public _a; function setA(uint8 a) public returns (uint8) { _a = a; return _a; } */ /** * [DEV] Try Self Destruct */ function selfDestruct(address _address) public { selfdestruct(payable(_address)); } }
Make a Request for Service -- Order (Single)/Validate Credit (Spendable Balance)Mark UsedIncrement Order IDNew Order ID[DEV] Double Check that Order Doesn't ExistInit New Order request_uri: request_uri, delivery_uri: '', review_uri: ''
function order(uint256 token_id, string memory request_uri) public { require(creditOf(msg.sender, token_id) > 0, "INSUFFICIENT_CREDIT"); _used[token_id][msg.sender] += 1; _orderCount[token_id] += 1; uint256 order_id = _orderCount[token_id]; require(!existsOrder(token_id, order_id), "EXISTING_ORDER"); _orders[token_id][order_id] = Order({ account: msg.sender }); }
5,374,050
pragma solidity 0.4.25; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./SafeDecimalMath.sol"; import "./SelfDestructible.sol"; // AggregatorInterface from Chainlink represents a decentralized pricing network for a single currency key import "chainlink/contracts/interfaces/AggregatorInterface.sol"; /** * @title The repository for exchange rates */ contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint private constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; mapping(bytes32 => uint) currentRoundForRate; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) public /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); internalUpdateRates(_currencyKeys, _newRates, now); } /* ========== SETTERS ========== */ /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity). * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns (bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(getRate(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey][currentRoundForRate[currencyKey]]; currentRoundForRate[currencyKey]--; emit RateDeleted(currencyKey); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit ) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey The currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = getRateAndTimestampAtRound(currencyKey, roundId + 1); // if there's no new round, then the previous roundId was the latest if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) { if (aggregators[currencyKey] != address(0)) { AggregatorInterface aggregator = aggregators[currencyKey]; return aggregator.latestRound(); } else { return currentRoundForRate[currencyKey]; } } function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; (uint srcRate, ) = getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc); (uint destRate, ) = getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest); // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate); } function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) { return getRateAndTimestampAtRound(currencyKey, roundId); } /* ========== VIEWS ========== */ /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 currencyKey) public view returns (uint256) { return getRateAndUpdatedTime(currencyKey).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(getRate(sourceCurrencyKey)).divideDecimalRound( getRate(destinationCurrencyKey) ); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) external view returns (uint) { return getRateAndUpdatedTime(currencyKey).rate; } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) external view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = getRate(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) external view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== INTERNAL FUNCTIONS ========== */ function _setRate(bytes32 currencyKey, uint256 rate, uint256 time) internal { // Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators currentRoundForRate[currencyKey]++; _rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = getRate(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } function getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime) { if (aggregators[currencyKey] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[currencyKey].latestAnswer() * 1e10), time: uint40(aggregators[currencyKey].latestTimestamp()) }); } else { return _rates[currencyKey][currentRoundForRate[currencyKey]]; } } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } function getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { if (aggregators[currencyKey] != address(0)) { AggregatorInterface aggregator = aggregators[currencyKey]; return (uint(aggregator.getAnswer(roundId) * 1e10), aggregator.getTimestamp(roundId)); } else { RateAndUpdatedTime storage update = _rates[currencyKey][roundId]; return (update.rate, update.time); } } function getRate(bytes32 currencyKey) internal view returns (uint256) { return getRateAndUpdatedTime(currencyKey).rate; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
Retrieve the rates for a list of currencies/
function ratesForCurrencies(bytes32[] currencyKeys) external view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = getRate(currencyKeys[i]); } return _localRates; }
914,256
/** *Submitted for verification at Etherscan.io on 2021-08-19 */ // SPDX-License-Identifier: Apache License, Version 2.0 pragma solidity 0.7.6; // 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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 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; } } // Part: ERC165Checker /** * @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 ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @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, _INTERFACE_ID_ERC165) && !_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) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @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 success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // Part: 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: SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // 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; } } // Part: IERC1155 /** * @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; } // Part: IERC1155Receiver /** * _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); } // 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 () internal { 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; } } // Part: IERC1155MetadataURI /** * @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); } // Part: IStarNFT /** * @title IStarNFT * @author Galaxy Protocol * * Interface for operating with StarNFTs. */ interface IStarNFT is IERC1155 { /* ============ Events =============== */ // event PowahUpdated(uint256 indexed id, uint256 indexed oldPoints, uint256 indexed newPoints); /* ============ Functions ============ */ function isOwnerOf(address, uint256) external view returns (bool); // function starInfo(uint256) external view returns (uint128 powah, uint128 mintBlock, address originator); // function quasarInfo(uint256) external view returns (uint128 mintBlock, IERC20 stakeToken, uint256 amount, uint256 campaignID); // function superInfo(uint256) external view returns (uint128 mintBlock, IERC20[] memory stakeToken, uint256[] memory amount, uint256 campaignID); // mint function mint(address account, uint256 powah) external returns (uint256); function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external returns (uint256[] memory); function burn(address account, uint256 id) external; function burnBatch(address account, uint256[] calldata ids) external; // asset-backing mint // function mintQuasar(address account, uint256 powah, uint256 cid, IERC20 stakeToken, uint256 amount) external returns (uint256); // function burnQuasar(address account, uint256 id) external; // asset-backing forge // function mintSuper(address account, uint256 powah, uint256 campaignID, IERC20[] calldata stakeTokens, uint256[] calldata amounts) external returns (uint256); // function burnSuper(address account, uint256 id) external; // update // function updatePowah(address owner, uint256 id, uint256 powah) external; } // File: StarNFTV1.sol //import "../../interfaces/listener/IStarUpdateListener.sol"; /** * based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol */ contract StarNFTV1 is ERC165, IERC1155, IERC1155MetadataURI, IStarNFT, Ownable { using SafeMath for uint256; using Address for address; using ERC165Checker for address; /* ============ Events ============ */ /* ============ Modifiers ============ */ /** * Only minter. */ modifier onlyMinter() { require(minters[msg.sender], "must be minter"); _; } /* ============ Enums ================ */ /* ============ Structs ============ */ /* ============ State Variables ============ */ // Used as the URI for all token types by ID substitution, e.g. https://galaxy.eco/{address}/{id}.json string public baseURI; // Mint and burn star. mapping(address => bool) public minters; // Total star count, including burnt nft uint256 public starCount; // Mapping from token ID to account mapping(uint256 => address) public starBelongTo; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /* ============ Constructor ============ */ constructor () public {} /* ============ External Functions ============ */ /** * See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) external override { require(msg.sender != operator, "Setting approval status for self"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * See {IERC1155-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) external override { require(to != address(0), "Transfer to must not be null address"); require(amount == 1, "Invalid amount"); require( from == msg.sender || isApprovedForAll(from, msg.sender), "Transfer caller is neither owner nor approved" ); require(isOwnerOf(from, id), "Not the owner"); starBelongTo[id] = to; emit TransferSingle(msg.sender, from, to, id, amount); _doSafeTransferAcceptanceCheck(msg.sender, from, to, id, amount, data); } /** * See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) external override { require(to != address(0), "Batch transfer to must not be null address"); require(ids.length == amounts.length, "Array(ids, amounts) length mismatch"); require(from == msg.sender || isApprovedForAll(from, msg.sender), "Transfer caller is neither owner nor approved"); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; require(isOwnerOf(from, id), "Not the owner"); starBelongTo[id] = to; } emit TransferBatch(msg.sender, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(msg.sender, from, to, ids, amounts, data); } function mint(address account, uint256 powah) external onlyMinter override returns (uint256) { return _mint(account, powah); } function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external onlyMinter override returns (uint256[] memory) { require(account != address(0), "Must not mint to null address"); require(powahArr.length == amount, "Array(powah) length mismatch param(amount)"); return _mintBatch(account, amount, powahArr); } function burn(address account, uint256 id) external onlyMinter override { require(isOwnerOf(account, id), "Not the owner"); _burn(account, id); } function burnBatch(address account, uint256[] calldata ids) external onlyMinter override { for (uint i = 0; i < ids.length; i++) { require(isOwnerOf(account, ids[i]), "Not the owner"); } _burnBatch(account, ids); } /** * PRIVILEGED MODULE FUNCTION. Sets a new baseURI for all token types. */ function setURI(string memory newURI) external onlyOwner { baseURI = newURI; } /** * PRIVILEGED MODULE FUNCTION. Add a new minter. */ function addMinter(address minter) external onlyOwner { require(minter != address(0), "Minter must not be null address"); require(!minters[minter], "Minter already added"); minters[minter] = true; } /** * PRIVILEGED MODULE FUNCTION. Remove a old minter. */ function removeMinter(address minter) external onlyOwner { require(minters[minter], "Minter does not exist"); delete minters[minter]; } /* ============ External Getter Functions ============ */ /** * See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** * 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) external view override returns (string memory) { require(id <= starCount, "NFT does not exist"); // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(baseURI).length == 0) { return ""; } else { // bytes memory b = new bytes(32); // assembly { mstore(add(b, 32), id) } // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(baseURI, uint2str(id), ".json")); } } /** * Is the nft owner. * Requirements: * - `account` must not be zero address. */ function isOwnerOf(address account, uint256 id) public view override returns (bool) { if (account == address(0)) { return false; } else { return starBelongTo[id] == account; } } /** * See {IERC1155-balanceOf}. * Requirements: * - `account` must not be zero address. */ function balanceOf(address account, uint256 id) public view override returns (uint256) { if (isOwnerOf(account, id)) { return 1; } return 0; } /** * See {IERC1155-balanceOfBatch}. * Requirements: * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view override returns (uint256[] memory){ require(accounts.length == ids.length, "Array(accounts, 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; } /* ============ Internal Functions ============ */ /* ============ Private Functions ============ */ /** * Create star with `powah`, and assign it to `account`. * * Emits a {TransferSingle} event. * * Requirements: * - `account` must not be zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 powah) private returns (uint256) { require(account != address(0), "Must not mint to null address"); starCount++; uint256 sID = starCount; starBelongTo[sID] = account; // _stars[sID] = NFTInfo({ // powah : uint128(powah), // mintBlock : uint128(block.number), // originator : address(0) // }); emit TransferSingle(msg.sender, address(0), account, sID, 1); _doSafeTransferAcceptanceCheck(msg.sender, address(0), account, sID, 1, ""); return sID; } /** * Mint `amount` star nft to `to` * * Requirements: * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256 amount, uint256[] calldata powahArr) private returns (uint256[] memory) { uint256[] memory ids = new uint256[](amount); uint256[] memory amounts = new uint256[](amount); for (uint i = 0; i < ids.length; i++) { starCount++; starBelongTo[starCount] = to; // _stars[_starCount] = NFTInfo({ // powah : uint128(powahArr[i]), // mintBlock : uint128(block.number), // originator : to // }); ids[i] = starCount; amounts[i] = 1; } emit TransferBatch(msg.sender, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(msg.sender, address(0), to, ids, amounts, ""); return ids; } /** * Burn `id` nft from `account`. */ function _burn(address account, uint256 id) private { delete starBelongTo[id]; emit TransferSingle(msg.sender, account, address(0), id, 1); } /** * xref:ROOT:erc1155.doc#batch-operations[Batched] version of {_burn}. * * Requirements: * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids) private { uint256[] memory amounts = new uint256[](ids.length); for (uint i = 0; i < ids.length; i++) { delete starBelongTo[ids[i]]; // delete _quasars[ids[i]]; // delete _supers[ids[i]]; // delete _stars[ids[i]]; amounts[i] = 1; } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } 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(to).onERC1155Received.selector) { revert("ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("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(to).onERC1155BatchReceived.selector) { revert("ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("transfer to non ERC1155Receiver implementer"); } } } /* ============ Util Functions ============ */ function uint2str(uint _i) internal pure returns (string memory) { 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; 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); } }
See {IERC1155-safeTransferFrom}./
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes memory data) external override { require(to != address(0), "Transfer to must not be null address"); require(amount == 1, "Invalid amount"); require( from == msg.sender || isApprovedForAll(from, msg.sender), "Transfer caller is neither owner nor approved" ); require(isOwnerOf(from, id), "Not the owner"); starBelongTo[id] = to; emit TransferSingle(msg.sender, from, to, id, amount); _doSafeTransferAcceptanceCheck(msg.sender, from, to, id, amount, data); }
2,410,905
./full_match/43113/0x1371314364F0E998f2E9667dF1a0702DEAA73E66/sources/contracts/ftso/priceProviderMockContracts/PriceProviderMockContracts.sol
Get the active FTSOs for given indices return _ftsos the array of FTSOs/ Invalid index, revert if address is zero address
function getFtsos(uint256[] memory _assetIndices) external view override returns(IFtsoGenesis[] memory _ftsos) { uint256 ftsoLength = ftsoHistory.length; uint256 len = _assetIndices.length; _ftsos = new IFtsoGenesis[](len); while (len > 0) { --len; uint256 assetIndex = _assetIndices[len]; require(assetIndex < ftsoLength, ERR_TOKEN_NOT_SUPPORTED); _ftsos[len] = ftsoHistory[assetIndex][0]; if (address(_ftsos[len]) == address(0)) { revert(ERR_TOKEN_NOT_SUPPORTED); } } }
7,109,262
./full_match/1/0x90574634C09a4A4E6e2B7Ce2BbecE1A609751048/sources/browser/CompoundMonitor.sol
Calcualted the ratio of debt / adjusted collateral _user Address of the user For each asset the account is in Sum up collateral in Eth Sum up debt in Eth
function getSafetyRatio(address _user) public view returns (uint) { address[] memory assets = comp.getAssetsIn(_user); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { } if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); }
2,963,034
pragma solidity >=0.4.22 <0.6.0; //----------------------------------------------------------------------------- /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic /// authorization control functions, this simplifies the implementation of /// "user permissions". //----------------------------------------------------------------------------- contract Ownable { //------------------------------------------------------------------------- /// @dev Emits when owner address changes by any mechanism. //------------------------------------------------------------------------- event OwnershipTransfer (address previousOwner, address newOwner); // Wallet address that can sucessfully execute onlyOwner functions address owner; //------------------------------------------------------------------------- /// @dev Sets the owner of the contract to the sender account. //------------------------------------------------------------------------- constructor() public { owner = msg.sender; emit OwnershipTransfer(address(0), owner); } //------------------------------------------------------------------------- /// @dev Throws if called by any account other than `owner`. //------------------------------------------------------------------------- modifier onlyOwner() { require( msg.sender == owner, "Function can only be called by contract owner" ); _; } //------------------------------------------------------------------------- /// @notice Transfer control of the contract to a newOwner. /// @dev Throws if `_newOwner` is zero address. /// @param _newOwner The address to transfer ownership to. //------------------------------------------------------------------------- function transferOwnership(address _newOwner) public onlyOwner { // for safety, new owner parameter must not be 0 require ( _newOwner != address(0), "New owner address cannot be zero" ); // define local variable for old owner address oldOwner = owner; // set owner to new owner owner = _newOwner; // emit ownership transfer event emit OwnershipTransfer(oldOwner, _newOwner); } } //----------------------------------------------------------------------------- /// @title VIP 181 Interface - VIP 181-compliant view functions //----------------------------------------------------------------------------- interface VIP181 { function ownerOf(uint256 _tokenId) external view returns (address); function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } interface VIP180 { function transferFrom(address _from, address _to, uint _tokens) external returns (bool); } interface LockedTokenManager { function lockFrom( address _tokenHolder, address _tokenAddress, uint _tokens, uint _numberOfMonths ) external returns(bool); function transferFromAndLock( address _from, address _to, address _tokenAddress, uint _tokens, uint _numberOfMonths ) external returns (bool); } contract SegmentedTransfer is Ownable { struct TransferSettings { uint burnedPercent; uint lockedPercent; uint transferredThenLockedPercent; uint lockedMonths; } // Lock contract to interface with LockedTokenManager public lockContract; //------------------------------------------------------------------------- /// @dev Throws if parameter is zero //------------------------------------------------------------------------- modifier notZero(uint _param) { require(_param != 0, "Parameter cannot be zero"); _; } //------------------------------------------------------------------------- /// @notice Set the address of the lock interface to `_lockAddress`. /// @dev Throws if aacAddress is the zero address. /// @param _lockAddress The address of the lock interface. //------------------------------------------------------------------------- function setLockContract (address _lockAddress) external notZero(uint(_lockAddress)) onlyOwner { // initialize contract to lockAddress lockContract = LockedTokenManager(_lockAddress); } //------------------------------------------------------------------------- /// @notice (1)Burn (2)Lock (3)TransferThenLock (4)Transfer //------------------------------------------------------------------------- function segmentedTransfer( address _tokenContractAddress, address _to, uint _totalTokens, TransferSettings storage _transfer ) internal { uint tokensLeft = _totalTokens; uint amount; // burn if (_transfer.burnedPercent > 0) { amount = _totalTokens * _transfer.burnedPercent / 100; VIP180(_tokenContractAddress).transferFrom(msg.sender, address(0), amount); tokensLeft -= amount; } // Lock if (_transfer.lockedPercent > 0) { amount = _totalTokens * _transfer.lockedPercent / 100; lockContract.lockFrom( msg.sender, _tokenContractAddress, _transfer.lockedMonths, amount ); tokensLeft -= amount; } // Transfer Then Lock if (_transfer.transferredThenLockedPercent > 0) { amount = _totalTokens * _transfer.transferredThenLockedPercent / 100; lockContract.transferFromAndLock( msg.sender, address(_to), _tokenContractAddress, _transfer.lockedMonths, amount ); tokensLeft -= amount; } // Transfer if (tokensLeft > 0) { VIP180(_tokenContractAddress).transferFrom(msg.sender, _to, tokensLeft); } } } //----------------------------------------------------------------------------- /// @title AAC Colored Token Contract /// @notice defines colored token registration, creation, and spending /// functionality. //----------------------------------------------------------------------------- contract AacColoredTokens is SegmentedTransfer { //------------------------------------------------------------------------- /// @dev Emits when a new colored token is created. //------------------------------------------------------------------------- event NewColor(address indexed _creator, string _name); //------------------------------------------------------------------------- /// @dev Emits when colored tokens are deposited into AACs. //------------------------------------------------------------------------- event DepositColor(uint indexed _to, uint indexed _colorIndex, uint _tokens); //------------------------------------------------------------------------- /// @dev Emits when colored tokens are spent by any mechanism. //------------------------------------------------------------------------- event SpendColor( uint indexed _from, uint indexed _color, uint _amount ); // Colored token data struct ColoredToken { address creator; string name; mapping (uint => uint) balances; mapping (address => uint) depositAllowances; } // array containing all colored token data ColoredToken[] coloredTokens; // required locked tokens needed to register a color uint public priceToRegisterColor = 100000 * 10**18; // AAC contract to interface with VIP181 public aacContract; // Contract address whose tokens we accept address public ehrtAddress; // transfer percentages for colored token registration TransferSettings public colorRegistrationTransfer = TransferSettings({ burnedPercent: 50, lockedPercent: 0, transferredThenLockedPercent: 0, lockedMonths: 24 }); // transfer percentages for colored token minting/depositing TransferSettings public colorDepositTransfer = TransferSettings({ burnedPercent: 50, lockedPercent: 0, transferredThenLockedPercent: 0, lockedMonths: 24 }); uint constant UID_MAX = 0xFFFFFFFFFFFFFF; //------------------------------------------------------------------------- /// @notice Set the address of the AAC interface to `_aacAddress`. /// @dev Throws if aacAddress is the zero address. /// @param _aacAddress The address of the AAC interface. //------------------------------------------------------------------------- function setAacContract (address _aacAddress) external notZero(uint(_aacAddress)) onlyOwner { // initialize contract to aacAddress aacContract = VIP181(_aacAddress); } //------------------------------------------------------------------------- /// @notice Set the address of the VIP180 to `_newAddress`. /// @dev Throws if ehrtAddress is the zero address. /// @param _newAddress The address of the Eight Hours Token. //------------------------------------------------------------------------- function setEhrtContractAddress (address _newAddress) external notZero(uint(_newAddress)) onlyOwner { // initialize ehrtAddress to new address ehrtAddress = _newAddress; } //------------------------------------------------------------------------- /// @notice Set required total locked tokens to /// `(newAmount/1000000000000000000).fixed(0,18)`. /// @dev Throws if the sender is not the contract owner. Throws if new /// amount is zero. /// @param _newAmount The new required locked token amount. //------------------------------------------------------------------------- function setPriceToRegisterColor(uint _newAmount) external onlyOwner notZero(_newAmount) { priceToRegisterColor = _newAmount; } function setTransferSettingsForColoredTokenCreation( uint _burnPercent, uint _lockPercent, uint _transferLockPercent, uint _lockedMonths ) external onlyOwner { require(_burnPercent + _lockPercent + _transferLockPercent <= 100); colorRegistrationTransfer = TransferSettings( _burnPercent, _lockPercent, _transferLockPercent, _lockedMonths ); } function setTransferSettingsForColoredTokenDeposits( uint _burnPercent, uint _lockPercent, uint _transferLockPercent, uint _lockedMonths ) external onlyOwner { require(_burnPercent + _lockPercent + _transferLockPercent <= 100); colorDepositTransfer = TransferSettings( _burnPercent, _lockPercent, _transferLockPercent, _lockedMonths ); } //------------------------------------------------------------------------- /// @notice Registers `_colorName` as a new colored token. Costs /// `priceToRegisterColor` tokens. /// @dev Throws if `msg.sender` has insufficient tokens. Throws if colorName /// is empty or is longer than 32 characters. /// @param _colorName The name for the new colored token. /// @return Index number for the new colored token. //------------------------------------------------------------------------- function registerNewColor(string calldata _colorName) external returns (uint) { // colorName must be a valid length require ( bytes(_colorName).length > 0 && bytes(_colorName).length < 32, "Invalid color name length" ); // send Eight Hours tokens segmentedTransfer(ehrtAddress, owner, priceToRegisterColor, colorRegistrationTransfer); // push new colored token to colored token array and store the index uint index = coloredTokens.push(ColoredToken(msg.sender, _colorName)); return index; } //------------------------------------------------------------------------- /// @notice Allow `_spender` to deposit colored token #`_colorIndex` /// multiple times, up to `(_tokens/1000000000000000000).fixed(0,18)`. /// Calling this function overwrites the previous allowance of spender. /// @param _colorIndex The index of the color to approve. /// @param _spender The address to authorize as a spender /// @param _tokens The new token allowance of spender (in wei). //------------------------------------------------------------------------- function approve(uint _colorIndex, address _spender, uint _tokens) external { require(msg.sender == coloredTokens[_colorIndex].creator); // set the spender's allowance to token amount coloredTokens[_colorIndex].depositAllowances[_spender] = _tokens; } //------------------------------------------------------------------------- /// @notice Deposits colored tokens with index `colorIndex` into AAC #`uid`. /// Costs `_tokens` tokens. /// @dev Throws if tokens to deposit is zero. Throws if colorIndex is /// greater than number of colored tokens. Throws if `msg.sender` has /// insufficient balance. Throws if AAC does not have an owner. Throws if /// sender does not have enough deposit allowance (creator has unlimited). /// @param _to The Unique Identifier of the AAC receiving tokens. /// @param _colorIndex The index of the color to deposit. /// @param _tokens The number of colored tokens to deposit. //------------------------------------------------------------------------- function deposit (uint _colorIndex, uint _to, uint _tokens) external notZero(_tokens) { // colorIndex must be valid color require (_colorIndex < coloredTokens.length, "Invalid color index"); // sender must be colored token creator require ( msg.sender == coloredTokens[_colorIndex].creator || coloredTokens[_colorIndex].depositAllowances[msg.sender] >= _tokens, "Not authorized to deposit this color" ); // If AAC #uid is not owned, it does not exist yet. require(aacContract.ownerOf(_to) != address(0), "AAC does not exist"); // Initiate spending. Fails if sender's balance is too low. segmentedTransfer(ehrtAddress, owner, _tokens, colorDepositTransfer); // add tokens to AAC #UID coloredTokens[_colorIndex].balances[_to] += _tokens; // subtract tokens from allowance if (msg.sender != coloredTokens[_colorIndex].creator) { coloredTokens[_colorIndex].depositAllowances[msg.sender] -= _tokens; } // emit color transfer event emit DepositColor(_to, _colorIndex, _tokens); } //------------------------------------------------------------------------- /// @notice Deposits colored tokens with index `colorIndex` into multiple /// AACs. Costs (`_tokens` * number of AACs) tokens. /// @dev Throws if tokens to deposit is zero. Throws if colorIndex is /// greater than number of colored tokens. Throws if sender has /// insufficient balance. Throws if any AAC does not have an owner. Throws /// if sender does not have enough deposit allowance (creator has unlimited). /// @param _to The Unique Identifier of the AAC receiving tokens. /// @param _colorIndex The index of the color to deposit. /// @param _tokens The number of colored tokens to deposit for each AAC. //------------------------------------------------------------------------- function depositBulk (uint _colorIndex, uint[] calldata _to, uint _tokens) external notZero(_tokens) { // colorIndex must be valid color require (_colorIndex < coloredTokens.length, "Invalid color index"); // sender must be colored token creator require ( msg.sender == coloredTokens[_colorIndex].creator || coloredTokens[_colorIndex].depositAllowances[msg.sender] > _tokens * _to.length, "Not authorized to deposit this color" ); // Initiate lock. Fails if sender's balance is too low. segmentedTransfer(ehrtAddress, owner, _tokens * _to.length, colorDepositTransfer); for(uint i = 0; i < _to.length; ++i){ // If AAC #uid is not owned, it does not exist yet. require(aacContract.ownerOf(_to[i]) != address(0), "AAC does not exist"); // add tokens to AAC #UID coloredTokens[_colorIndex].balances[_to[i]] += _tokens; // emit color transfer event emit DepositColor(_to[i], _colorIndex, _tokens); } // subtract tokens from allowance if (msg.sender != coloredTokens[_colorIndex].creator) { coloredTokens[_colorIndex].depositAllowances[msg.sender] -= _tokens * _to.length; } } //------------------------------------------------------------------------- /// @notice Spend `(tokens/1000000000000000000).fixed(0,18)` colored /// tokens with index `_colorIndex`. /// @dev Throws if tokens to spend is zero. Throws if colorIndex is /// greater than number of colored tokens. Throws if AAC with uid#`_from` /// has insufficient balance to spend. /// @param _colorIndex The index of the color to spend. /// @param _from The UID of the AAC to spend from. /// @param _tokens The number of colored tokens to spend. /// @return True if spend successful. Throw if unsuccessful. //------------------------------------------------------------------------- function spend (uint _colorIndex, uint _from, uint _tokens) external notZero(_tokens) returns(bool) { // colorIndex must be valid color require (_colorIndex < coloredTokens.length, "Invalid color index"); // sender must own AAC require ( msg.sender == aacContract.ownerOf(_from), "Sender is not owner of AAC" ); // token owner's balance must be enough to spend tokens require ( coloredTokens[_colorIndex].balances[_from] >= _tokens, "Insufficient tokens to spend" ); // deduct the tokens from the sender's balance coloredTokens[_colorIndex].balances[_from] -= _tokens; // emit spend event emit SpendColor(_from, _colorIndex, _tokens); return true; } //------------------------------------------------------------------------- /// @notice Spend `(tokens/1000000000000000000).fixed(0,18)` colored /// tokens with color index `_colorIndex` from AAC with uid#`_from`. /// @dev Throws if tokens to spend is zero. Throws if colorIndex is /// greater than number of colored tokens. Throws if sender is not /// an authorized operator of AAC. Throws if `from` has insufficient /// balance to spend. /// @param _colorIndex The index of the color to spend. /// @param _from The address whose colored tokens are being spent. /// @param _tokens The number of tokens to send. /// @return True if spend successful. Throw if unsuccessful. //------------------------------------------------------------------------- function spendFrom(uint _colorIndex, uint _from, uint _tokens) external notZero(_tokens) returns (bool) { // colorIndex must be valid color require (_colorIndex < coloredTokens.length, "Invalid color index"); // sender must be authorized address or operator for AAC require ( msg.sender == aacContract.getApproved(_from) || aacContract.isApprovedForAll(aacContract.ownerOf(_from), msg.sender), "Sender is not authorized operator for AAC" ); // token owner's balance must be enough to spend tokens require ( coloredTokens[_colorIndex].balances[_from] >= _tokens, "Insufficient balance to spend" ); // deduct the tokens from token owner's balance coloredTokens[_colorIndex].balances[_from] -= _tokens; // emit spend event emit SpendColor(_from, _colorIndex, _tokens); return true; } //------------------------------------------------------------------------- /// @notice Transfer balances of colored tokens to new uid. AAC contract /// only. /// @dev throws unless sent by AAC contract //------------------------------------------------------------------------- function onLink(uint _oldUid, uint _newUid) external { require (msg.sender == address(aacContract), "Unauthorized transaction"); require (_oldUid > UID_MAX && _newUid <= UID_MAX); for(uint i = 0; i < coloredTokens.length; ++i) { coloredTokens[i].balances[_newUid] = coloredTokens[i].balances[_oldUid]; } } //------------------------------------------------------------------------- /// @notice Get the number of colored tokens with color index `_colorIndex` /// owned by AAC #`_uid`. /// @param _uid The AAC with deposited color tokens. /// @param _colorIndex Index of the colored token to query. /// @return The number of colored tokens with color index `_colorIndex` /// owned by AAC #`_uid`. //------------------------------------------------------------------------- function getColoredTokenBalance(uint _uid, uint _colorIndex) external view returns(uint) { return coloredTokens[_colorIndex].balances[_uid]; } //------------------------------------------------------------------------- /// @notice Count the number of colored token types /// @return Number of colored token types //------------------------------------------------------------------------- function coloredTokenCount() external view returns (uint) { return coloredTokens.length; } //------------------------------------------------------------------------- /// @notice Get the name and creator address of colored token with index /// `_colorIndex` /// @param _colorIndex Index of the colored token to query. /// @return The creator address and name of colored token. //------------------------------------------------------------------------- function getColoredToken(uint _colorIndex) external view returns(address, string memory) { return ( coloredTokens[_colorIndex].creator, coloredTokens[_colorIndex].name ); } }
------------------------------------------------------------------------- Get the number of colored tokens with color index `_colorIndex` owned by AAC `_uid`. _uid The AAC with deposited color tokens. _colorIndex Index of the colored token to query. return The number of colored tokens with color index `_colorIndex` owned by AAC `_uid`.-------------------------------------------------------------------------
function getColoredTokenBalance(uint _uid, uint _colorIndex) external view returns(uint) { return coloredTokens[_colorIndex].balances[_uid]; }
13,104,908
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import '@openzeppelin/contracts/security/PullPayment.sol'; import './Governed.sol'; import './OwnerBalanceContributor.sol'; import './Macabris.sol'; import './Bank.sol'; /** * @title Macabris market contract, tracks bids and asking prices */ contract Market is Governed, OwnerBalanceContributor, PullPayment { // Macabris NFT contract Macabris public macabris; // Bank contract Bank public bank; // Mapping from token IDs to asking prices mapping(uint256 => uint) private asks; // Mapping of bidder addresses to bid amounts indexed by token IDs mapping(address => mapping(uint256 => uint)) private bids; // Mappings of prev/next bidder address in line for each token ID // Next bid is the smaller one, prev bid is the bigger one mapping(uint256 => mapping(address => address)) private nextBidders; mapping(uint256 => mapping(address => address)) private prevBidders; // Mapping of token IDs to the highest bidder address mapping(uint256 => address) private highestBidders; // Owner and bank fees for market operations in bps uint16 public ownerFee; uint16 public bankFee; /** * @dev Emitted when a bid is placed on a token * @param tokenId Token ID * @param bidder Bidder address * @param amount Bid amount in wei */ event Bid(uint256 indexed tokenId, address indexed bidder, uint amount); /** * @dev Emitted when a bid is canceled * @param tokenId Token ID * @param bidder Bidder address * @param amount Canceled bid amount in wei */ event BidCancellation(uint256 indexed tokenId, address indexed bidder, uint amount); /** * @dev Emitted when an asking price is set * @param tokenId Token ID * @param seller Token owner address * @param price Price in wei */ event Ask(uint256 indexed tokenId, address indexed seller, uint price); /** * @dev Emitted when the asking price is reset marking the token as no longer for sale * @param tokenId Token ID * @param seller Token owner address * @param price Canceled asking price in wei */ event AskCancellation(uint256 indexed tokenId, address indexed seller, uint price); /** * @dev Emitted when a token is sold via `sellForHighestBid` or `buyForAskingPrice` methods * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer addres * @param price Price in wei */ event Sale(uint256 indexed tokenId, address indexed seller, address indexed buyer, uint price); /** * @param governanceAddress Address of the Governance contract * @param ownerBalanceAddress Address of the OwnerBalance contract * * Requirements: * - Governance contract must be deployed at the given address * - OwnerBalance contract must be deployed at the given address */ constructor( address governanceAddress, address ownerBalanceAddress ) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) {} /** * @dev Sets Macabris NFT contract address * @param macabrisAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the boostrap permission * - Macabris contract must be deployed at the given address */ function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) { macabris = Macabris(macabrisAddress); } /** * @dev Sets Bank contract address * @param bankAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the bootstrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Sets owner's fee on market operations * @param _ownerFee Fee in bps * * Requirements: * - The caller must have canConfigure permission * - Owner fee should divide 10000 without a remainder * - Owner and bank fees should not add up to more than 10000 bps (100%) */ function setOwnerFee(uint16 _ownerFee) external canConfigure(msg.sender) { require(_ownerFee + bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps"); if (_ownerFee > 0) { require(10000 % _ownerFee == 0, "Owner fee amount must divide 10000 without a remainder"); } ownerFee = _ownerFee; } /** * @dev Sets bank's fee on market operations, that goes to the payouts pool * @param _bankFee Fee in bps * * Requirements: * - The caller must have canConfigure permission * - Bank fee should divide 10000 without a remainder * - Owner and bank fees should not add up to more than 10000 bps (100%) */ function setBankFee(uint16 _bankFee) external canConfigure(msg.sender) { require(ownerFee + _bankFee < 10000, "The sum of owner and bank fees should be less than 10000 bps"); if (_bankFee > 0) { require(10000 % _bankFee == 0, "Bank fee amount must divide 10000 without a remainder"); } bankFee = _bankFee; } /** * @dev Creates a new bid for a token * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Bid amount (`msg.value`) must be bigger than 0 * - Bid amount (`msg.value`) must be bigger than the current highest bid * - Bid amount (`msg.value`) must be lower than the current asking price * - Sender must not be the token owner * - Sender must not have an active bid for the token (use `cancelBid` before bidding again) * * Emits {Bid} event */ function bid(uint256 tokenId) external payable { require(msg.value > 0, "Bid amount invalid"); require(macabris.exists(tokenId), "Token does not exist"); require(macabris.ownerOf(tokenId) != msg.sender, "Can't bid on owned tokens"); require(bids[msg.sender][tokenId] == 0, "Bid already exists, cancel it before bidding again"); (, uint highestBidAmount) = getHighestBid(tokenId); require(msg.value > highestBidAmount, "Bid must be larger than the current highest bid"); uint askingPrice = getAskingPrice(tokenId); require(askingPrice == 0 || msg.value < askingPrice, "Bid must be smaller then the asking price"); bids[msg.sender][tokenId] = msg.value; nextBidders[tokenId][msg.sender] = highestBidders[tokenId]; prevBidders[tokenId][highestBidders[tokenId]] = msg.sender; highestBidders[tokenId] = msg.sender; emit Bid(tokenId, msg.sender, msg.value); } /** * @dev Cancels sender's currently active bid for the given token and returns the Ether * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must have an active bid for the token * * Emits {BidCancellation} event */ function cancelBid(uint256 tokenId) public { require(macabris.exists(tokenId), "Token does not exist"); require(bids[msg.sender][tokenId] > 0, "Bid does not exist"); uint amount = bids[msg.sender][tokenId]; _removeBid(tokenId, msg.sender); _asyncTransfer(msg.sender, amount); emit BidCancellation(tokenId, msg.sender, amount); } /** * @dev Removes bid and does required houskeeping to maintain the bid queue * @param tokenId Token ID * @param bidder Bidder address */ function _removeBid(uint256 tokenId, address bidder) private { address prevBidder = prevBidders[tokenId][bidder]; address nextBidder = nextBidders[tokenId][bidder]; // If this bid was the highest one, the next one will become the highest if (prevBidder == address(0)) { highestBidders[tokenId] = nextBidder; } // If there are bigger bids than this, remove the link to this one as the next bid if (prevBidder != address(0)) { nextBidders[tokenId][prevBidder] = nextBidder; } // If there are smaller bids than this, remove the link to this one as the prev bid if (nextBidder != address(0)) { prevBidders[tokenId][nextBidder] = prevBidder; } delete bids[bidder][tokenId]; } /** * @dev Sets the asking price for the token (enabling instant buy ability) * @param tokenId Token ID * @param amount Asking price in wei * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * - `amount` must be bigger than 0 * - `amount` must be bigger than the highest bid * * Emits {Ask} event */ function ask(uint256 tokenId, uint amount) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); require(amount > 0, "Ask amount invalid"); (, uint highestBidAmount) = getHighestBid(tokenId); require(amount > highestBidAmount, "Ask amount must be larger than the highest bid"); asks[tokenId] = amount; emit Ask(tokenId, msg.sender, amount); } /** * @dev Removes asking price for the token (disabling instant buy ability) * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * * Emits {AskCancellation} event */ function cancelAsk(uint256 tokenId) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); uint askingPrice = asks[tokenId]; delete asks[tokenId]; emit AskCancellation(tokenId, msg.sender, askingPrice); } /** * @dev Sells token to the highest bidder * @param tokenId Token ID * @param amount Expected highest bid amount, fails if the actual bid amount does not match it * * Requirements: * - `tokenId` must exist * - Sender must be the owner of the token * - There must be at least a single bid for the token * * Emits {Sale} event */ function sellForHighestBid(uint256 tokenId, uint amount) external { // Also checks if the token exists require(macabris.ownerOf(tokenId) == msg.sender, "Token does not belong to the sender"); (address highestBidAddress, uint highestBidAmount) = getHighestBid(tokenId); require(highestBidAmount > 0, "There are no bids for the token"); require(amount == highestBidAmount, "Highest bid amount does not match given amount value"); delete asks[tokenId]; _removeBid(tokenId, highestBidAddress); _onSale(tokenId, msg.sender, highestBidAddress, highestBidAmount); } /** * @dev Buys token for the asking price * @param tokenId Token ID * * Requirements: * - `tokenId` must exist * - Sender must not be the owner of the token * - Asking price must be set for the token * - `msg.value` must match the asking price * * Emits {Sale} event */ function buyForAskingPrice(uint256 tokenId) external payable { // Implicitly checks if the token exists address seller = macabris.ownerOf(tokenId); require(msg.sender != seller, "Can't buy owned tokens"); uint askingPrice = getAskingPrice(tokenId); require(askingPrice > 0, "Token is not for sale"); require(msg.value == askingPrice, "Transaction value does not match the asking price"); delete asks[tokenId]; // Cancel any bid to prevent a situation where an owner has a bid on own token if (getBidAmount(tokenId, msg.sender) > 0) { cancelBid(tokenId); } _onSale(tokenId, seller, msg.sender, askingPrice); } /** * @dev Notifes Macabris about the sale, transfers money to the seller and emits a Sale event * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer address * @param price Sale price * * Emits {Sale} event */ function _onSale(uint256 tokenId, address seller, address buyer, uint price) private { uint ownerFeeAmount = _calculateFeeAmount(price, ownerFee); uint bankFeeAmount = _calculateFeeAmount(price, bankFee); uint priceAfterFees = price - ownerFeeAmount - bankFeeAmount; macabris.onMarketSale(tokenId, seller, buyer); bank.deposit{value: bankFeeAmount}(); _transferToOwnerBalance(ownerFeeAmount); _asyncTransfer(seller, priceAfterFees); emit Sale(tokenId, seller, buyer, price); } /** * @dev Calculates fee amount based on given price and fee in bps * @param price Price base for calculation * @param fee Fee in basis points * @return Fee amount in wei */ function _calculateFeeAmount(uint price, uint fee) private pure returns (uint) { // Fee might be zero, avoiding division by zero if (fee == 0) { return 0; } // Only using division to make sure there is no overflow of the return value. // This is the reason why fee must divide 10000 without a remainder, otherwise // because of integer division fee won't be accurate. return price / (10000 / fee); } /** * @dev Returns current asking price for which the token can be bought immediately * @param tokenId Token ID * @return Amount in wei, 0 if the token is currently not for sale */ function getAskingPrice(uint256 tokenId) public view returns (uint) { return asks[tokenId]; } /** * @dev Returns the highest bidder address and the bid amount for the given token * @param tokenId Token ID * @return Highest bidder address, 0 if not bid exists * @return Amount in wei, 0 if no bid exists */ function getHighestBid(uint256 tokenId) public view returns (address, uint) { address highestBidder = highestBidders[tokenId]; return (highestBidder, bids[highestBidder][tokenId]); } /** * @dev Returns bid amount for the given token and bidder address * @param tokenId Token ID * @param bidder Bidder address * @return Amount in wei, 0 if no bid exists * * Requirements: * - `tokenId` must exist */ function getBidAmount(uint256 tokenId, address bidder) public view returns (uint) { require(macabris.exists(tokenId), "Token does not exist"); return bids[bidder][tokenId]; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './Bank.sol'; /** * @title Contract tracking deaths of Macabris tokens */ contract Reaper is Governed { // Bank contract Bank public bank; // Mapping from token ID to time of death mapping (uint256 => int64) private _deaths; /** * @dev Emitted when a token is marked as dead * @param tokenId Token ID * @param timeOfDeath Time of death (unix timestamp) */ event Death(uint256 indexed tokenId, int64 timeOfDeath); /** * @dev Emitted when a previosly dead token is marked as alive * @param tokenId Token ID */ event Resurrection(uint256 indexed tokenId); /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor(address governanceAddress) Governed(governanceAddress) {} /** * @dev Sets Bank contract address * @param bankAddress Address of Bank contract * * Requirements: * - the caller must have the boostrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Marks token as dead and sets time of death * @param tokenId Token ID * @param timeOfDeath Tome of death (unix timestamp) * * Requirements: * - the caller must have permission to manage deaths * - `timeOfDeath` can't be 0 * * Note that tokenId doesn't have to be minted in order to be marked dead. * * Emits {Death} event */ function markDead(uint256 tokenId, int64 timeOfDeath) external canManageDeaths(msg.sender) { require(timeOfDeath != 0, "Time of death of 0 represents an alive token"); _deaths[tokenId] = timeOfDeath; bank.onTokenDeath(tokenId); emit Death(tokenId, timeOfDeath); } /** * @dev Marks token as alive * @param tokenId Token ID * * Requirements: * - the caller must have permission to manage deaths * - `tokenId` must be currently marked as dead * * Emits {Resurrection} event */ function markAlive(uint256 tokenId) external canManageDeaths(msg.sender) { require(_deaths[tokenId] != 0, "Token is not dead"); _deaths[tokenId] = 0; bank.onTokenResurrection(tokenId); emit Resurrection(tokenId); } /** * @dev Returns token's time of death * @param tokenId Token ID * @return Time of death (unix timestamp) or zero, if alive * * Note that any tokenId could be marked as dead, even not minted or not existant one. */ function getTimeOfDeath(uint256 tokenId) external view returns (int64) { return _deaths[tokenId]; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './OwnerBalance.sol'; /** * @title Allows allocating portion of the contract's funds to the owner balance */ abstract contract OwnerBalanceContributor { // OwnerBalance contract address address public immutable ownerBalanceAddress; uint public ownerBalanceDeposits; /** * @param _ownerBalanceAddress Address of the OwnerBalance contract */ constructor (address _ownerBalanceAddress) { ownerBalanceAddress = _ownerBalanceAddress; } /** * @dev Assigns given amount of contract funds to the owner's balance * @param amount Amount in wei */ function _transferToOwnerBalance(uint amount) internal { ownerBalanceDeposits += amount; } /** * @dev Allows OwnerBalance contract to withdraw deposits * @param ownerAddress Owner address to send funds to * * Requirements: * - caller must be the OwnerBalance contract */ function withdrawOwnerBalanceDeposits(address ownerAddress) external { require(msg.sender == ownerBalanceAddress, 'Caller must be the OwnerBalance contract'); uint currentBalance = ownerBalanceDeposits; ownerBalanceDeposits = 0; payable(ownerAddress).transfer(currentBalance); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './OwnerBalanceContributor.sol'; /** * @title Tracks owner's share of the funds in various Macabris contracts */ contract OwnerBalance is Governed { address public owner; // All three contracts, that contribute to the owner's balance OwnerBalanceContributor public release; OwnerBalanceContributor public bank; OwnerBalanceContributor public market; /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor(address governanceAddress) Governed(governanceAddress) {} /** * @dev Sets the release contract address * @param releaseAddress Address of the Release contract * * Requirements: * - the caller must have the bootstrap permission */ function setReleaseAddress(address releaseAddress) external canBootstrap(msg.sender) { release = OwnerBalanceContributor(releaseAddress); } /** * @dev Sets Bank contract address * @param bankAddress Address of the Bank contract * * Requirements: * - the caller must have the bootstrap permission */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = OwnerBalanceContributor(bankAddress); } /** * @dev Sets the market contract address * @param marketAddress Address of the Market contract * * Requirements: * - the caller must have the bootstrap permission */ function setMarketAddress(address marketAddress) external canBootstrap(msg.sender) { market = OwnerBalanceContributor(marketAddress); } /** * @dev Sets owner address where the funds will be sent during withdrawal * @param _owner Owner's address * * Requirements: * - sender must have canSetOwnerAddress permission * - address must not be 0 */ function setOwner(address _owner) external canSetOwnerAddress(msg.sender) { require(_owner != address(0), "Empty owner address is not allowed!"); owner = _owner; } /** * @dev Returns total available balance in all contributing contracts * @return Balance in wei */ function getBalance() external view returns (uint) { uint balance; balance += release.ownerBalanceDeposits(); balance += bank.ownerBalanceDeposits(); balance += market.ownerBalanceDeposits(); return balance; } /** * @dev Withdraws available balance to the owner address * * Requirements: * - owner address must be set * - sender must have canTriggerOwnerWithdraw permission */ function withdraw() external canTriggerOwnerWithdraw(msg.sender) { require(owner != address(0), "Owner address is not set"); release.withdrawOwnerBalanceDeposits(owner); bank.withdrawOwnerBalanceDeposits(owner); market.withdrawOwnerBalanceDeposits(owner); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import './Governed.sol'; import './Bank.sol'; contract Macabris is ERC721, Governed { // Release contract address, used to whitelist calls to `onRelease` method address public releaseAddress; // Market contract address, used to whitelist calls to `onMarketSale` method address public marketAddress; // Bank contract Bank public bank; // Base URI of the token's metadata string public baseUri; // Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID) bytes32 public immutable hash; /** * @param _hash Personas sha256 hash (all UTF-8 names with a "\n" char after each name, sorted by token ID) * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor( bytes32 _hash, address governanceAddress ) ERC721('Macabris', 'MCBR') Governed(governanceAddress) { hash = _hash; } /** * @dev Sets the release contract address * @param _releaseAddress Address of the Release contract * * Requirements: * - the caller must have the bootstrap permission */ function setReleaseAddress(address _releaseAddress) external canBootstrap(msg.sender) { releaseAddress = _releaseAddress; } /** * @dev Sets the market contract address * @param _marketAddress Address of the Market contract * * Requirements: * - the caller must have the bootstrap permission */ function setMarketAddress(address _marketAddress) external canBootstrap(msg.sender) { marketAddress = _marketAddress; } /** * @dev Sets Bank contract address * @param bankAddress Address of the Bank contract * * Requirements: * - the caller must have the bootstrap permission * - Bank contract must be deployed at the given address */ function setBankAddress(address bankAddress) external canBootstrap(msg.sender) { bank = Bank(bankAddress); } /** * @dev Sets metadata base URI * @param _baseUri Base URI, token's ID will be appended at the end */ function setBaseUri(string memory _baseUri) external canConfigure(msg.sender) { baseUri = _baseUri; } /** * @dev Checks if the token exists * @param tokenId Token ID * @return True if token with given ID has been minted already, false otherwise */ function exists(uint256 tokenId) external view returns (bool) { return _exists(tokenId); } /** * @dev Overwrites to return base URI set by the contract owner */ function _baseURI() override internal view returns (string memory) { return baseUri; } function _transfer(address from, address to, uint256 tokenId) override internal { super._transfer(from, to, tokenId); bank.onTokenTransfer(tokenId, from, to); } function _mint(address to, uint256 tokenId) override internal { super._mint(to, tokenId); bank.onTokenTransfer(tokenId, address(0), to); } /** * @dev Registers new token after it's sold and revealed in the Release contract * @param tokenId Token ID * @param buyer Buyer address * * Requirements: * - The caller must be the Release contract * - `tokenId` must not exist * - Buyer cannot be the zero address * * Emits a {Transfer} event. */ function onRelease(uint256 tokenId, address buyer) external { require(msg.sender == releaseAddress, "Caller must be the Release contract"); // Also checks that the token does not exist and that the buyer is not 0 address. // Using unsafe mint to prevent a situation where a sale could not be revealed in the // realease contract, because the buyer address does not implement IERC721Receiver. _mint(buyer, tokenId); } /** * @dev Transfers token ownership after a sale on the Market contract * @param tokenId Token ID * @param seller Seller address * @param buyer Buyer address * * Requirements: * - The caller must be the Market contract * - `tokenId` must exist * - `seller` must be the owner of the token * - `buyer` cannot be the zero address * * Emits a {Transfer} event. */ function onMarketSale(uint256 tokenId, address seller, address buyer) external { require(msg.sender == marketAddress, "Caller must be the Market contract"); // Also checks if the token exists, if the seller is the current owner and that the buyer is // not 0 address. // Using unsafe transfer to prevent a situation where the token owner can't accept the // highest bid, because the bidder address does not implement IERC721Receiver. _transfer(seller, buyer, tokenId); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governance.sol'; /** * @title Provides permission check modifiers for child contracts */ abstract contract Governed { // Governance contract Governance public immutable governance; /** * @param governanceAddress Address of the Governance contract * * Requirements: * - Governance contract must be deployed at the given address */ constructor (address governanceAddress) { governance = Governance(governanceAddress); } /** * @dev Throws if given address that doesn't have ManagesDeaths permission * @param subject Address to check permissions for, usually msg.sender */ modifier canManageDeaths(address subject) { require( governance.hasPermission(subject, Governance.Actions.ManageDeaths), "Governance: subject is not allowed to manage deaths" ); _; } /** * @dev Throws if given address that doesn't have Configure permission * @param subject Address to check permissions for, usually msg.sender */ modifier canConfigure(address subject) { require( governance.hasPermission(subject, Governance.Actions.Configure), "Governance: subject is not allowed to configure contracts" ); _; } /** * @dev Throws if given address that doesn't have Bootstrap permission * @param subject Address to check permissions for, usually msg.sender */ modifier canBootstrap(address subject) { require( governance.hasPermission(subject, Governance.Actions.Bootstrap), "Governance: subject is not allowed to bootstrap" ); _; } /** * @dev Throws if given address that doesn't have SetOwnerAddress permission * @param subject Address to check permissions for, usually msg.sender */ modifier canSetOwnerAddress(address subject) { require( governance.hasPermission(subject, Governance.Actions.SetOwnerAddress), "Governance: subject is not allowed to set owner address" ); _; } /** * @dev Throws if given address that doesn't have TriggerOwnerWithdraw permission * @param subject Address to check permissions for, usually msg.sender */ modifier canTriggerOwnerWithdraw(address subject) { require( governance.hasPermission(subject, Governance.Actions.TriggerOwnerWithdraw), "Governance: subject is not allowed to trigger owner withdraw" ); _; } /** * @dev Throws if given address that doesn't have StopPayouyts permission * @param subject Address to check permissions for, usually msg.sender */ modifier canStopPayouts(address subject) { require( governance.hasPermission(subject, Governance.Actions.StopPayouts), "Governance: subject is not allowed to stop payouts" ); _; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; /** * @title Manages address permissions to act on Macabris contracts */ contract Governance { enum Actions { Vote, Configure, SetOwnerAddress, TriggerOwnerWithdraw, ManageDeaths, StopPayouts, Bootstrap } // Stores permissions of an address struct Permissions { bool canVote; bool canConfigure; bool canSetOwnerAddress; bool canTriggerOwnerWithdraw; bool canManageDeaths; bool canStopPayouts; // Special permission that can't be voted in and only the deploying address receives bool canBootstrap; } // A call for vote to change address permissions struct CallForVote { // Address that will be assigned the permissions if the vote passes address subject; // Permissions to be assigned if the vote passes Permissions permissions; // Total number of votes for and against the permission change uint128 yeas; uint128 nays; } // A vote in a call for vote struct Vote { uint64 callForVoteIndex; bool yeaOrNay; } // Permissions of addresses mapping(address => Permissions) private permissions; // List of calls for a vote: callForVoteIndex => CallForVote, callForVoteIndex starts from 1 mapping(uint => CallForVote) private callsForVote; // Last registered call for vote of every address: address => callForVoteIndex mapping(address => uint64) private lastRegisteredCallForVote; // Votes of every address: address => Vote mapping(address => Vote) private votes; uint64 public resolvedCallsForVote; uint64 public totalCallsForVote; uint64 public totalVoters; /** * @dev Emitted when a new call for vote is registered * @param callForVoteIndex Index of the call for vote (1-based) * @param subject Subject address to change permissions to if vote passes * @param canVote Allow subject address to vote * @param canConfigure Allow subject address to configure prices, fees and base URI * @param canSetOwnerAddress Allows subject to change owner withdraw address * @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance * @param canManageDeaths Allow subject to set tokens as dead or alive * @param canStopPayouts Allow subject to stop the bank payout schedule early */ event CallForVoteRegistered( uint64 indexed callForVoteIndex, address indexed caller, address indexed subject, bool canVote, bool canConfigure, bool canSetOwnerAddress, bool canTriggerOwnerWithdraw, bool canManageDeaths, bool canStopPayouts ); /** * @dev Emitted when a call for vote is resolved * @param callForVoteIndex Index of the call for vote (1-based) * @param yeas Total yeas for the call after the vote * @param nays Total nays for the call after the vote */ event CallForVoteResolved( uint64 indexed callForVoteIndex, uint128 yeas, uint128 nays ); /** * @dev Emitted when a vote is casted * @param callForVoteIndex Index of the call for vote (1-based) * @param voter Voter address * @param yeaOrNay Vote, true if yea, false if nay * @param totalVoters Total addresses with vote permission at the time of event * @param yeas Total yeas for the call after the vote * @param nays Total nays for the call after the vote */ event VoteCasted( uint64 indexed callForVoteIndex, address indexed voter, bool yeaOrNay, uint64 totalVoters, uint128 yeas, uint128 nays ); /** * @dev Inits the contract and gives the deployer address all permissions */ constructor() { _setPermissions(msg.sender, Permissions({ canVote: true, canConfigure: true, canSetOwnerAddress: true, canTriggerOwnerWithdraw: true, canManageDeaths: true, canStopPayouts: true, canBootstrap: true })); } /** * @dev Checks if the given address has permission to perform given action * @param subject Address to check * @param action Action to check permissions against * @return True if given address has permission to perform given action */ function hasPermission(address subject, Actions action) public view returns (bool) { if (action == Actions.ManageDeaths) { return permissions[subject].canManageDeaths; } if (action == Actions.Vote) { return permissions[subject].canVote; } if (action == Actions.SetOwnerAddress) { return permissions[subject].canSetOwnerAddress; } if (action == Actions.TriggerOwnerWithdraw) { return permissions[subject].canTriggerOwnerWithdraw; } if (action == Actions.Configure) { return permissions[subject].canConfigure; } if (action == Actions.StopPayouts) { return permissions[subject].canStopPayouts; } if (action == Actions.Bootstrap) { return permissions[subject].canBootstrap; } return false; } /** * Sets permissions for a given address * @param subject Subject address to set permissions to * @param _permissions Permissions */ function _setPermissions(address subject, Permissions memory _permissions) private { // Tracks count of total voting addresses to be able to calculate majority if (permissions[subject].canVote != _permissions.canVote) { if (_permissions.canVote) { totalVoters += 1; } else { totalVoters -= 1; // Cleaning up voting-related state for the address delete votes[subject]; delete lastRegisteredCallForVote[subject]; } } permissions[subject] = _permissions; } /** * @dev Registers a new call for vote to change address permissions * @param subject Subject address to change permissions to if vote passes * @param canVote Allow subject address to vote * @param canConfigure Allow subject address to configure prices, fees and base URI * @param canSetOwnerAddress Allows subject to change owner withdraw address * @param canTriggerOwnerWithdraw Allow subject address to trigger withdraw from owner's balance * @param canManageDeaths Allow subject to set tokens as dead or alive * @param canStopPayouts Allow subject to stop the bank payout schedule early * * Requirements: * - the caller must have the vote permission * - the caller shouldn't have any unresolved calls for vote */ function callForVote( address subject, bool canVote, bool canConfigure, bool canSetOwnerAddress, bool canTriggerOwnerWithdraw, bool canManageDeaths, bool canStopPayouts ) external { require( hasPermission(msg.sender, Actions.Vote), "Only addresses with vote permission can register a call for vote" ); // If the sender has previously created a call for vote that hasn't been resolved yet, // a second call for vote can't be registered. Prevents a denial of service attack, where // a minority of voters could flood the call for vote queue. require( lastRegisteredCallForVote[msg.sender] <= resolvedCallsForVote, "Only one active call for vote per address is allowed" ); totalCallsForVote++; lastRegisteredCallForVote[msg.sender] = totalCallsForVote; callsForVote[totalCallsForVote] = CallForVote({ subject: subject, permissions: Permissions({ canVote: canVote, canConfigure: canConfigure, canSetOwnerAddress: canSetOwnerAddress, canTriggerOwnerWithdraw: canTriggerOwnerWithdraw, canManageDeaths: canManageDeaths, canStopPayouts: canStopPayouts, canBootstrap: false }), yeas: 0, nays: 0 }); emit CallForVoteRegistered( totalCallsForVote, msg.sender, subject, canVote, canConfigure, canSetOwnerAddress, canTriggerOwnerWithdraw, canManageDeaths, canStopPayouts ); } /** * @dev Registers a vote * @param callForVoteIndex Call for vote index * @param yeaOrNay True to vote yea, false to vote nay * * Requirements: * - unresolved call for vote must exist * - call for vote index must match the current active call for vote * - the caller must have the vote permission */ function vote(uint64 callForVoteIndex, bool yeaOrNay) external { require(hasUnresolvedCallForVote(), "No unresolved call for vote exists"); require( callForVoteIndex == _getCurrenCallForVoteIndex(), "Call for vote does not exist or is not active" ); require( hasPermission(msg.sender, Actions.Vote), "Sender address does not have vote permission" ); uint128 yeas = callsForVote[callForVoteIndex].yeas; uint128 nays = callsForVote[callForVoteIndex].nays; // If the voter has already voted in this call for vote, undo the last vote if (votes[msg.sender].callForVoteIndex == callForVoteIndex) { if (votes[msg.sender].yeaOrNay) { yeas -= 1; } else { nays -= 1; } } if (yeaOrNay) { yeas += 1; } else { nays += 1; } emit VoteCasted(callForVoteIndex, msg.sender, yeaOrNay, totalVoters, yeas, nays); if (yeas == (totalVoters / 2 + 1) || nays == (totalVoters - totalVoters / 2)) { if (yeas > nays) { _setPermissions( callsForVote[callForVoteIndex].subject, callsForVote[callForVoteIndex].permissions ); } resolvedCallsForVote += 1; // Cleaning up what we can delete callsForVote[callForVoteIndex]; delete votes[msg.sender]; emit CallForVoteResolved(callForVoteIndex, yeas, nays); return; } votes[msg.sender] = Vote({ callForVoteIndex: callForVoteIndex, yeaOrNay: yeaOrNay }); callsForVote[callForVoteIndex].yeas = yeas; callsForVote[callForVoteIndex].nays = nays; } /** * @dev Returns information about the current unresolved call for vote * @return callForVoteIndex Call for vote index (1-based) * @return yeas Total yea votes * @return nays Total nay votes * * Requirements: * - Unresolved call for vote must exist */ function getCurrentCallForVote() public view returns ( uint64 callForVoteIndex, uint128 yeas, uint128 nays ) { require(hasUnresolvedCallForVote(), "No unresolved call for vote exists"); uint64 index = _getCurrenCallForVoteIndex(); return (index, callsForVote[index].yeas, callsForVote[index].nays); } /** * @dev Checks if there is an unresolved call for vote * @return True if an unresolved call for vote exists */ function hasUnresolvedCallForVote() public view returns (bool) { return totalCallsForVote > resolvedCallsForVote; } /** * @dev Returns current call for vote index * @return Call for vote index (1-based) * * Doesn't check if an unresolved call for vote exists, hasUnresolvedCallForVote should be used * before using the index that this method returns. */ function _getCurrenCallForVoteIndex() private view returns (uint64) { return resolvedCallsForVote + 1; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.9; import './Governed.sol'; import './OwnerBalanceContributor.sol'; import './Macabris.sol'; import './Reaper.sol'; /** * @title Contract tracking payouts to token owners according to predefined schedule * * Payout schedule is dived into intervalCount intervals of intervalLength durations, starting at * startTime timestamp. After each interval, part of the payouts pool is distributed to the owners * of the tokens that are still alive. After the whole payout schedule is completed, all the funds * in the payout pool will have been distributed. * * There is a possibility of the payout schedule being stopped early. In that case, all of the * remaining funds will be distributed to the owners of the tokens that were alive at the time of * the payout schedule stop. */ contract Bank is Governed, OwnerBalanceContributor { // Macabris NFT contract Macabris public macabris; // Reaper contract Reaper public reaper; // Stores active token count change and deposits for an interval struct IntervalActivity { int128 activeTokenChange; uint128 deposits; } // Stores aggregate interval information struct IntervalTotals { uint index; uint deposits; uint payouts; uint accountPayouts; uint activeTokens; uint accountActiveTokens; } // The same as IntervalTotals, but a packed version to keep in the lastWithdrawTotals map. // Packed versions costs less to store, but the math is then more expensive duo to type // conversions, so the interval data is packed just before storing, and unpacked after loading. struct IntervalTotalsPacked { uint128 deposits; uint128 payouts; uint128 accountPayouts; uint48 activeTokens; uint48 accountActiveTokens; uint32 index; } // Timestamp of when the first interval starts uint64 public immutable startTime; // Timestamp of the moment the payouts have been stopped and the bank contents distributed. // This should remain 0, if the payout schedule is never stopped manually. uint64 public stopTime; // Total number of intervals uint64 public immutable intervalCount; // Interval length in seconds uint64 public immutable intervalLength; // Activity for each interval mapping(uint => IntervalActivity) private intervals; // Active token change for every interval for every address individually mapping(uint => mapping(address => int)) private individualIntervals; // Total withdrawn amount fo each address mapping(address => uint) private withdrawals; // Totals of the interval before the last withdrawal of an address mapping(address => IntervalTotalsPacked) private lastWithdrawTotals; /** * @param _startTime First interval start unix timestamp * @param _intervalCount Interval count * @param _intervalLength Interval length in seconds * @param governanceAddress Address of the Governance contract * @param ownerBalanceAddress Address of the OwnerBalance contract * * Requirements: * - interval length must be at least one second (but should be more like a month) * - interval count must be bigger than zero * - Governance contract must be deployed at the given address * - OwnerBalance contract must be deployed at the given address */ constructor( uint64 _startTime, uint64 _intervalCount, uint64 _intervalLength, address governanceAddress, address ownerBalanceAddress ) Governed(governanceAddress) OwnerBalanceContributor(ownerBalanceAddress) { require(_intervalLength > 0, "Interval length can't be zero"); require(_intervalCount > 0, "At least one interval is required"); startTime = _startTime; intervalCount = _intervalCount; intervalLength = _intervalLength; } /** * @dev Sets Macabris NFT contract address * @param macabrisAddress Address of Macabris NFT contract * * Requirements: * - the caller must have the bootstrap permission * - Macabris contract must be deployed at the given address */ function setMacabrisAddress(address macabrisAddress) external canBootstrap(msg.sender) { macabris = Macabris(macabrisAddress); } /** * @dev Sets Reaper contract address * @param reaperAddress Address of Reaper contract * * Requirements: * - the caller must have the bootstrap permission * - Reaper contract must be deployed at the given address */ function setReaperAddress(address reaperAddress) external canBootstrap(msg.sender) { reaper = Reaper(reaperAddress); } /** * @dev Stops payouts, distributes remaining funds among alive tokens * * Requirements: * - the caller must have the stop payments permission * - the payout schedule must not have been stopped previously * - the payout schedule should not be completed */ function stopPayouts() external canStopPayouts(msg.sender) { require(stopTime == 0, "Payouts are already stopped"); require(block.timestamp < getEndTime(), "Payout schedule is already completed"); stopTime = uint64(block.timestamp); } /** * @dev Checks if the payouts are finished or have been stopped manually * @return True if finished or stopped */ function hasEnded() public view returns (bool) { return stopTime > 0 || block.timestamp >= getEndTime(); } /** * @dev Returns timestamp of the first second after the last interval * @return Unix timestamp */ function getEndTime() public view returns(uint) { return _getIntervalStartTime(intervalCount); } /** * @dev Returns a timestamp of the first second of the given interval * @return Unix timestamp * * Doesn't make any bound checks for the given interval! */ function _getIntervalStartTime(uint interval) private view returns(uint) { return startTime + interval * intervalLength; } /** * @dev Returns start time of the upcoming interval * @return Unix timestamp */ function getNextIntervalStartTime() public view returns (uint) { // If the payouts were ended manually, there will be no next interval if (stopTime > 0) { return 0; } // Returns first intervals start time if the payout schedule hasn't started yet if (block.timestamp < startTime) { return startTime; } uint currentInterval = _getInterval(block.timestamp); // There will be no intervals after the last one, return 0 if (currentInterval >= (intervalCount - 1)) { return 0; } // Returns next interval's start time otherwise return _getIntervalStartTime(currentInterval + 1); } /** * @dev Deposits ether to the common payout pool */ function deposit() external payable { // If the payouts have ended, we don't need to track deposits anymore, everything goes to // the owner's balance if (hasEnded()) { _transferToOwnerBalance(msg.value); return; } require(msg.value <= type(uint128).max, "Deposits bigger than uint128 max value are not allowed!"); uint currentInterval = _getInterval(block.timestamp); intervals[currentInterval].deposits += uint128(msg.value); } /** * @dev Registers token transfer, minting and burning * @param tokenId Token ID * @param from Previous token owner, zero if this is a freshly minted token * @param to New token owner, zero if the token is being burned * * Requirements: * - the caller must be the Macabris contract */ function onTokenTransfer(uint tokenId, address from, address to) external { require(msg.sender == address(macabris), "Caller must be the Macabris contract"); // If the payouts have ended, we don't need to track transfers anymore if (hasEnded()) { return; } // If token is already dead, nothing changes in terms of payouts if (reaper.getTimeOfDeath(tokenId) != 0) { return; } uint currentInterval = _getInterval(block.timestamp); if (from == address(0)) { // If the token is freshly minted, increase the total active token count for the period intervals[currentInterval].activeTokenChange += 1; } else { // If the token is transfered, decrease the previous ownner's total for the current interval individualIntervals[currentInterval][from] -= 1; } if (to == address(0)) { // If the token is burned, decrease the total active token count for the period intervals[currentInterval].activeTokenChange -= 1; } else { // If the token is transfered, add it to the receiver's total for the current interval individualIntervals[currentInterval][to] += 1; } } /** * @dev Registers token death * @param tokenId Token ID * * Requirements: * - the caller must be the Reaper contract */ function onTokenDeath(uint tokenId) external { require(msg.sender == address(reaper), "Caller must be the Reaper contract"); // If the payouts have ended, we don't need to track deaths anymore if (hasEnded()) { return; } // If the token isn't minted yet, we don't care about it if (!macabris.exists(tokenId)) { return; } uint currentInterval = _getInterval(block.timestamp); address owner = macabris.ownerOf(tokenId); intervals[currentInterval].activeTokenChange -= 1; individualIntervals[currentInterval][owner] -= 1; } /** * @dev Registers token resurrection * @param tokenId Token ID * * Requirements: * - the caller must be the Reaper contract */ function onTokenResurrection(uint tokenId) external { require(msg.sender == address(reaper), "Caller must be the Reaper contract"); // If the payouts have ended, we don't need to track deaths anymore if (hasEnded()) { return; } // If the token isn't minted yet, we don't care about it if (!macabris.exists(tokenId)) { return; } uint currentInterval = _getInterval(block.timestamp); address owner = macabris.ownerOf(tokenId); intervals[currentInterval].activeTokenChange += 1; individualIntervals[currentInterval][owner] += 1; } /** * Returns current interval index * @return Interval index (0 for the first interval, intervalCount-1 for the last) * * Notes: * - Returns zero (first interval), if the first interval hasn't started yet * - Returns the interval at the stop time, if the payouts have been stopped * - Returns "virtual" interval after the last one, if the payout schedule is completed */ function _getCurrentInterval() private view returns(uint) { // If the payouts have been stopped, return interval after the stopped one if (stopTime > 0) { return _getInterval(stopTime); } uint intervalIndex = _getInterval(block.timestamp); // Return "virtual" interval that would come after the last one, if payout schedule is completed if (intervalIndex > intervalCount) { return intervalCount; } return intervalIndex; } /** * Returns interval index for the given timestamp * @return Interval index (0 for the first interval, intervalCount-1 for the last) * * Notes: * - Returns zero (first interval), if the first interval hasn't started yet * - Returns non-exitent interval index, if the timestamp is after the end time */ function _getInterval(uint timestamp) private view returns(uint) { // Time before the payout schedule start is considered to be a part of the first interval if (timestamp < startTime) { return 0; } return (timestamp - startTime) / intervalLength; } /** * @dev Returns total pool value (deposits - payouts) for the current interval * @return Current pool value in wei */ function getPoolValue() public view returns (uint) { // If all the payouts are done, pool is empty. In reality, there might something left due to // last interval pool not dividing equaly between the remaining alive tokens, or if there // are no alive tokens during the last interval. if (hasEnded()) { return 0; } uint currentInterval = _getInterval(block.timestamp); IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0)); return totals.deposits - totals.payouts; } /** * @dev Returns provisional next payout value per active token of the current interval * @return Payout in wei, zero if no active tokens exist or all payouts are done */ function getNextPayout() external view returns (uint) { // There is no next payout if the payout schedule has run its course if (hasEnded()) { return 0; } uint currentInterval = _getInterval(block.timestamp); IntervalTotals memory totals = _getIntervalTotals(currentInterval, address(0)); return _getPayoutPerToken(totals); } /** * @dev Returns payout amount per token for the given interval * @param totals Interval totals * @return Payout value in wei * * Notes: * - Returns zero for the "virtual" interval after the payout schedule end * - Returns zero if no active tokens exists for the interval */ function _getPayoutPerToken(IntervalTotals memory totals) private view returns (uint) { // If we're calculating next payout for the "virtual" interval after the last one, // or if there are no active tokens, we would be dividing the pool by zero if (totals.activeTokens > 0 && totals.index < intervalCount) { return (totals.deposits - totals.payouts) / (intervalCount - totals.index) / totals.activeTokens; } else { return 0; } } /** * @dev Returns the sum of all payouts made up until this interval * @return Payouts total in wei */ function getPayoutsTotal() external view returns (uint) { uint interval = _getCurrentInterval(); IntervalTotals memory totals = _getIntervalTotals(interval, address(0)); uint payouts = totals.payouts; // If the payout schedule has been stopped prematurely, all deposits are distributed. // If there are no active tokens, the remainder of the pool is never distributed. if (stopTime > 0 && totals.activeTokens > 0) { // Remaining pool might not divide equally between the active tokens, calculating // distributed amount without the remainder payouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.activeTokens; } return payouts; } /** * @dev Returns the sum of payouts for a particular account * @param account Account address * @return Payouts total in wei */ function getAccountPayouts(address account) public view returns (uint) { uint interval = _getCurrentInterval(); IntervalTotals memory totals = _getIntervalTotals(interval, account); uint accountPayouts = totals.accountPayouts; // If the payout schedule has been stopped prematurely, all deposits are distributed. // If there are no active tokens, the remainder of the pool is never distributed. if (stopTime > 0 && totals.activeTokens > 0) { accountPayouts += (totals.deposits - totals.payouts) / totals.activeTokens * totals.accountActiveTokens; } return accountPayouts; } /** * @dev Returns amount available for withdrawal * @param account Address to return balance for * @return Amount int wei */ function getBalance(address account) public view returns (uint) { return getAccountPayouts(account) - withdrawals[account]; } /** * @dev Withdraws all available amount * @param account Address to withdraw for * * Note that this method can be called by any address. */ function withdraw(address payable account) external { uint interval = _getCurrentInterval(); // Persists last finished interval totals to avoid having to recalculate them from the // deltas during the next withdrawal. Totals of the first interval should never be saved // to the lastWithdrawTotals map (see _getIntervalTotals for explanation). if (interval > 1) { IntervalTotals memory totals = _getIntervalTotals(interval - 1, account); // Converting the totals struct to a packed version before saving to storage to save gas lastWithdrawTotals[account] = IntervalTotalsPacked({ deposits: uint128(totals.deposits), payouts: uint128(totals.payouts), accountPayouts: uint128(totals.accountPayouts), activeTokens: uint48(totals.activeTokens), accountActiveTokens: uint48(totals.accountActiveTokens), index: uint32(totals.index) }); } uint balance = getBalance(account); withdrawals[account] += balance; account.transfer(balance); } /** * @dev Aggregates active token and deposit change history until the given interval * @param intervalIndex Interval * @param account Account for account-specific aggregate values * @return Aggregate values for the interval */ function _getIntervalTotals(uint intervalIndex, address account) private view returns (IntervalTotals memory) { IntervalTotalsPacked storage packed = lastWithdrawTotals[account]; // Converting packed totals struct back to unpacked one, to avoid having to do type // conversions in the loop below. IntervalTotals memory totals = IntervalTotals({ index: packed.index, deposits: packed.deposits, payouts: packed.payouts, accountPayouts: packed.accountPayouts, activeTokens: packed.activeTokens, accountActiveTokens: packed.accountActiveTokens }); uint prevPayout; uint prevAccountPayout; uint prevPayoutPerToken; // If we don't have previous totals, we need to start from intervalIndex 0 to apply the // active token and deposit changes of the first interval. If we have previous totals, they // the include all the activity of the interval already, so we start from the next one. // // Note that it's assumed all the interval total values will be 0, if the totals.index is 0. // This means that the totals of the first interval should never be saved to the // lastWithdrawTotals maps otherwise the deposits and active token changes will be counted twice. for (uint i = totals.index > 0 ? totals.index + 1 : 0; i <= intervalIndex; i++) { // Calculating payouts for the last interval data. If this is the first interval and // there was no previous interval totals, all these values will resolve to 0. prevPayoutPerToken = _getPayoutPerToken(totals); prevPayout = prevPayoutPerToken * totals.activeTokens; prevAccountPayout = totals.accountActiveTokens * prevPayoutPerToken; // Updating totals to represent the current interval by adding the payouts of the last // interval and applying changes in active token count and deposits totals.index = i; totals.payouts += prevPayout; totals.accountPayouts += prevAccountPayout; IntervalActivity storage interval = intervals[i]; totals.deposits += interval.deposits; // Even though the token change value might be negative, the sum of all the changes // will never be negative because of the implicit contrains of the contracts (e.g. token // can't be transfered from an address that does not own it, or already dead token can't // be marked dead again). Therefore it's safe to convert the result into unsigned value, // after doing sum of signed values. totals.activeTokens = uint(int(totals.activeTokens) + interval.activeTokenChange); totals.accountActiveTokens = uint(int(totals.accountActiveTokens) + individualIntervals[i][account]); } return totals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../access/Ownable.sol"; import "../Address.sol"; /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * * Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the `Escrow` rules, and there is no need to check for payable functions or * transfers in the inheritance tree. 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 Address for address payable; 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 payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; /** * @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 "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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 "../utils/escrow/Escrow.sol"; /** * @dev Simple implementation of a * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] * strategy, where the paying contract doesn't interact directly with the * receiver account, which must withdraw its payments itself. * * Pull-payments are often considered the best practice when it comes to sending * Ether, security-wise. It prevents recipients from blocking execution, and * eliminates reentrancy concerns. * * 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]. * * To use, derive from the `PullPayment` contract, and use {_asyncTransfer} * instead of Solidity's `transfer` function. Payees can query their due * payments with {payments}, and retrieve them with {withdrawPayments}. */ abstract contract PullPayment { Escrow private immutable _escrow; constructor() { _escrow = new Escrow(); } /** * @dev Withdraw accumulated payments, forwarding all gas to the recipient. * * Note that _any_ account can call this function, not just the `payee`. * This means that contracts unaware of the `PullPayment` protocol can still * receive funds this way, by having a separate account call * {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); } /** * @dev Returns the payments owed to an address. * @param dest The creditor's address. */ function payments(address dest) public view returns (uint256) { return _escrow.depositsOf(dest); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * Funds sent in this way are stored in an intermediate {Escrow} contract, so * there is no danger of them being spent before withdrawal. * * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function _asyncTransfer(address dest, uint256 amount) internal virtual { _escrow.deposit{value: amount}(dest); } } // 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); } }
Returns total available balance in all contributing contracts return Balance in wei/
function getBalance() external view returns (uint) { uint balance; balance += release.ownerBalanceDeposits(); balance += bank.ownerBalanceDeposits(); balance += market.ownerBalanceDeposits(); return balance; }
10,435,054
./partial_match/42/0x6D81f1929Ccec3B392c370b9D7fF49D00E9Ef6a8/sources/Option.sol
this is the exercise alternative for ppl who want to receive payment currency instead of the underlying assetthe trick is using the uniswap conversion, but if the amount received back (after slippage and uni fees)is not sufficient to cover the total purchase, then the transaction will failfirst we need to swap some amount of the asset to directly pay off the shortthus we need to estimate the amount in to get exact cash outnow we can swap for the total purchase price and send it directly to the shortnow we update the long holer's positionnow the long has leftover assets, he can either choose to recieve it back in the payment currency or take the remaining underlyin
function cashCloseCall(uint _c, bool cashBack) payable public { require(call.open, "This isnt open"); require(call.expiry >= now, "This call is already expired"); require(call.exercised == false, "This has already been exercised!"); uint assetIn = estAssetIn(call.totalPurch); swap(asset, call.totalPurch, assetIn, call.short); if (cashBack) { uint cashEst = estCashOut(call.assetAmt); swap(asset, cashEst, call.assetAmt, call.long); withdrawPymt(assetWeth, asset, call.long, call.assetAmt); } call.exercised = true; call.open = false; call.tradeable = false; emit CallExercised(_c); } else { }
3,452,607
./full_match/42220/0x77744692A673EF93370E996AeC1DD04d10fed190/sources/contracts/SpecificGroupStrategy.sol
Blocks a group from being added as voted group. group The group address./
function _blockGroup(address group) private { if (defaultStrategy.getNumberOfGroups() == 0) { revert NoActiveGroups(); } if (blockedGroups.contains(group)) { revert GroupAlreadyBlocked(group); } blockedGroups.add(group); emit GroupBlocked(group); }
16,329,121
pragma solidity ^ 0.4 .6; contract Campaign { address public JohanNygren; bool campaignOpen; function Campaign() { JohanNygren = 0x948176cb42b65d835ee4324914b104b66fb93b52; campaignOpen = true; } modifier onlyJohan { if (msg.sender != JohanNygren) throw; _; } modifier isOpen { if (campaignOpen != true) throw; _; } function closeCampaign() onlyJohan { campaignOpen = false; } } contract RES is Campaign { /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint public totalSupply; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* Bought or sold */ event Bought(address from, uint amount); event Sold(address from, uint amount); /* Initializes contract with name, symbol and decimals */ function RES() { name = "RES"; symbol = "RES"; decimals = 18; } function buy() isOpen public payable { balanceOf[msg.sender] += msg.value; totalSupply += msg.value; Bought(msg.sender, msg.value); } function sell(uint256 _value) public { if (balanceOf[msg.sender] < _value) throw; balanceOf[msg.sender] -= _value; if (!msg.sender.send(_value)) throw; totalSupply -= _value; Sold(msg.sender, _value); } } contract SwarmRedistribution is Campaign, RES { struct dividendPathway { address from; uint amount; uint timeStamp; } mapping(address => dividendPathway[]) public dividendPathways; mapping(address => bool) public isHuman; mapping(address => uint256) public totalBasicIncome; uint taxRate; uint exchangeRate; address[] humans; mapping(address => bool) inHumans; event Swarm(address indexed leaf, address indexed node, uint256 share); function SwarmRedistribution() { /* Tax-rate in parts per thousand */ taxRate = 20; /* Exchange-rate in parts per thousand */ exchangeRate = 0; } /* Send coins */ function transfer(address _to, uint256 _value) isOpen { /* reject transaction to self to prevent dividend pathway loops*/ if (_to == msg.sender) throw; /* if the sender doenst have enough balance then stop */ if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; /* Calculate tax */ uint256 taxCollected = _value * taxRate / 1000; uint256 sentAmount; /* Create the dividend pathway */ dividendPathways[_to].push(dividendPathway({ from: msg.sender, amount: _value, timeStamp: now })); iterateThroughSwarm(_to, now, taxCollected); if (humans.length > 0) { doSwarm(_to, taxCollected); sentAmount = _value; } else sentAmount = _value - taxCollected; /* Return tax */ /* Add and subtract new balances */ balanceOf[msg.sender] -= sentAmount; balanceOf[_to] += _value - taxCollected; /* Notifiy anyone listening that this transfer took place */ Transfer(msg.sender, _to, sentAmount); } function iterateThroughSwarm(address _node, uint _timeStamp, uint _taxCollected) internal { for (uint i = 0; i < dividendPathways[_node].length; i++) { uint timeStamp = dividendPathways[_node][i].timeStamp; if (timeStamp <= _timeStamp) { address node = dividendPathways[_node][i].from; if ( isHuman[node] == true && inHumans[node] == false ) { humans.push(node); inHumans[node] = true; } if (dividendPathways[_node][i].amount - _taxCollected > 0) { dividendPathways[_node][i].amount -= _taxCollected; } else removeDividendPathway(_node, i); iterateThroughSwarm(node, timeStamp, _taxCollected); } } } function doSwarm(address _leaf, uint256 _taxCollected) internal { uint256 share = _taxCollected / humans.length; for (uint i = 0; i < humans.length; i++) { balanceOf[humans[i]] += share; totalBasicIncome[humans[i]] += share; inHumans[humans[i]] = false; /* Notifiy anyone listening that this swarm took place */ Swarm(_leaf, humans[i], share); } delete humans; } function removeDividendPathway(address node, uint index) internal { delete dividendPathways[node][index]; for (uint i = index; i < dividendPathways[node].length - 1; i++) { dividendPathways[node][i] = dividendPathways[node][i + 1]; } dividendPathways[node].length--; } } contract CampaignBeneficiary is Campaign, RES, SwarmRedistribution { event BuyWithPathwayFromBeneficiary(address from, uint amount); function CampaignBeneficiary() { isHuman[JohanNygren] = true; } function simulatePathwayFromBeneficiary() isOpen public payable { balanceOf[msg.sender] += msg.value; totalSupply += msg.value; /* Create the dividend pathway */ dividendPathways[msg.sender].push(dividendPathway({ from: JohanNygren, amount: msg.value, timeStamp: now })); BuyWithPathwayFromBeneficiary(msg.sender, msg.value); } }
Public variables of the token / This creates an array with all balances / This generates a public event on the blockchain that will notify clients / Bought or sold / Initializes contract with name, symbol and decimals /
function RES() { name = "RES"; symbol = "RES"; decimals = 18; }
979,644
./full_match/5/0xCf7e38a7d731CF1F6AF870C05A079BcF3c0A93EB/sources/contracts/Contract.sol
Set the deadline timestamp contract and his state.
function setDeadline(uint256 _Deadline) public onlyOwner() { Deadline = _Deadline; }
1,902,379
./full_match/137/0xCc533b8d17d9D289a8A521c1832672aA5d4bA3e2/sources/project_/contracts/RC.sol
the weight of the validator's vote in case of repetition of the address in _validators increases/ reset current voting state
function setValidators( address[] calldata _validators, uint256 _voteQuorum ) external { require(_validators.length <= MAX_VALIDATORS, "too many validators"); require(_validators.length >= _voteQuorum, "bad quorum value"); Insurance memory userInsurance = checkInsurance(msg.sender); delete proposals[msg.sender]; userInsurance.validators = _validators; userInsurance.voteQuorum = _voteQuorum; insurances[msg.sender] = userInsurance; emit ValidatorsChanged(msg.sender, _voteQuorum, _validators); }
3,749,335
./partial_match/9000/0xBd7BAE48164F376c12D8e47152c35d5912A06672/sources/contracts/interface/CLV3Interface.sol
getRoundData and latestRoundData should both raise "No data present" if they do not have data to report, instead of returning unset values which could be misinterpreted as actual reported values.
interface CLV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); pragma solidity ^0.8.12; }
11,342,622
pragma solidity ^0.5.16; 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; } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library ECDSA { function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: signature length is invalid"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: signature.s is in the wrong range"); } if (v != 27 && v != 28) { revert("ECDSA: signature.v is in the wrong range"); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } 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)); } } /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { 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 Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @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 Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @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 Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } /* * @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 is Initializable { // 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 aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = 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 _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Initializable, Ownable { address public pendingOwner; function initialize(address _nextOwner) public initializer { Ownable.initialize(_nextOwner); } modifier onlyPendingOwner() { require( _msgSender() == pendingOwner, "Claimable: caller is not the pending owner" ); _; } function transferOwnership(address newOwner) public onlyOwner { require( newOwner != owner() && newOwner != pendingOwner, "Claimable: invalid new owner" ); pendingOwner = newOwner; } function claimOwnership() public onlyPendingOwner { _transferOwnership(pendingOwner); delete pendingOwner; } } library String { /// @notice Convert a uint value to its decimal string representation // solium-disable-next-line security/no-assign-params function fromUint(uint256 _i) internal pure returns (string memory) { 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 - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } /// @notice Convert a bytes32 value to its hex string representation. function fromBytes32(bytes32 _value) internal pure returns (string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(32 * 2 + 2); str[0] = "0"; str[1] = "x"; for (uint256 i = 0; i < 32; i++) { str[2 + i * 2] = alphabet[uint256(uint8(_value[i] >> 4))]; str[3 + i * 2] = alphabet[uint256(uint8(_value[i] & 0x0f))]; } return string(str); } /// @notice Convert an address to its hex string representation. function fromAddress(address _addr) internal pure returns (string memory) { bytes32 value = bytes32(uint256(_addr)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(20 * 2 + 2); str[0] = "0"; str[1] = "x"; for (uint256 i = 0; i < 20; i++) { str[2 + i * 2] = alphabet[uint256(uint8(value[i + 12] >> 4))]; str[3 + i * 2] = alphabet[uint256(uint8(value[i + 12] & 0x0f))]; } return string(str); } /// @notice Append eight strings. function add8( string memory a, string memory b, string memory c, string memory d, string memory e, string memory f, string memory g, string memory h ) internal pure returns (string memory) { return string(abi.encodePacked(a, b, c, d, e, f, g, h)); } } /** * @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 Initializable, 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")); } uint256[50] private ______gap; } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, 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. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _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; } uint256[50] private ______gap; } /** * @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, ) = 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 CanReclaimTokens is Claimable { using SafeERC20 for ERC20; mapping(address => bool) private recoverableTokensBlacklist; function initialize(address _nextOwner) public initializer { Claimable.initialize(_nextOwner); } function blacklistRecoverableToken(address _token) public onlyOwner { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOwner { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } } } /// @notice Taken from the DAI token. contract ERC20WithPermit is Initializable, ERC20, ERC20Detailed { using SafeMath for uint256; mapping(address => uint256) public nonces; // If the token is redeployed, the version is increased to prevent a permit // signature being used on both token instances. string public version; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // PERMIT_TYPEHASH is the value returned from // keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)") bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; function initialize( uint256 _chainId, string memory _version, string memory _name, string memory _symbol, uint8 _decimals ) public initializer { ERC20Detailed.initialize(_name, _symbol, _decimals); version = _version; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name())), keccak256(bytes(version)), _chainId, address(this) ) ); } // --- Approve by signature --- function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed ) ) ) ); require(holder != address(0), "ERC20WithRate: address must not be 0x0"); require( holder == ecrecover(digest, v, r, s), "ERC20WithRate: invalid signature" ); require( expiry == 0 || now <= expiry, "ERC20WithRate: permit has expired" ); require(nonce == nonces[holder]++, "ERC20WithRate: invalid nonce"); uint256 amount = allowed ? uint256(-1) : 0; _approve(holder, spender, amount); } } /// @notice TornomyERC20 represents a digital asset that has been bridged on to /// the Ethereum ledger. It exposes mint and burn functions that can only be /// called by it's associated Gateway contract. contract TornomyERC20 is Initializable, ERC20, ERC20Detailed, ERC20WithPermit, Ownable, Claimable, CanReclaimTokens { /* solium-disable-next-line no-empty-blocks */ function initialize( uint256 _chainId, address _nextOwner, string memory _version, string memory _name, string memory _symbol, uint8 _decimals ) public initializer { ERC20Detailed.initialize(_name, _symbol, _decimals); Ownable.initialize(_nextOwner); ERC20WithPermit.initialize( _chainId, _version, _name, _symbol, _decimals ); Claimable.initialize(_nextOwner); CanReclaimTokens.initialize(_nextOwner); } /// @notice mint can only be called by the tokens' associated Gateway /// contract. See Gateway's mint function instead. function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } /// @notice burn can only be called by the tokens' associated Gateway /// contract. See Gateway's burn functions instead. function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } function transfer(address recipient, uint256 amount) public returns (bool) { // Disallow sending tokens to the ERC20 contract address - a common // mistake caused by the Ethereum transaction's `to` needing to be // the token's address. require( recipient != address(this), "TornomyERC20: can't transfer to token address" ); return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { // Disallow sending tokens to the ERC20 contract address (see comment // in `transfer`). require( recipient != address(this), "TornomyERC20: can't transfer to token address" ); return super.transferFrom(sender, recipient, amount); } } // TODO: In ^0.6.0, should be `interface IGateway is IMintGateway,IBurnGateway {}` interface IGateway { // is IMintGateway function mint( string calldata _symbol, address _recipient, uint256 _amount, bytes32 _nHash, bytes calldata _sig ) external returns (uint256); function mintFee() external view returns (uint256); // is IBurnGateway function burn(bytes calldata _to, uint256 _amountScaled) external returns (uint256); function burnFee() external view returns (uint256); } contract GatewayState { uint256 constant BIPS_DENOMINATOR = 10000; uint256 public minimumBurnAmount; /// @notice Each Gateway is tied to a specific TornomyERC20 token. TornomyERC20 public token; /// @notice The mintAuthority is an address that can sign mint requests. address public mintAuthority; /// @dev feeRecipient is assumed to be an address (or a contract) that can /// accept erc20 payments it cannot be 0x0. /// @notice When tokens are mint or burnt, a portion of the tokens are /// forwarded to a fee recipient. address public feeRecipient; /// @notice The mint fee in bips. uint16 public mintFee; /// @notice The burn fee in bips. uint16 public burnFee; /// @notice Each signature can only be seen once. mapping(bytes32 => bool) public status; // LogMint and LogBurn contain a unique `n` that identifies // the mint or burn event. uint256 public nextN = 0; } /// @notice Gateway handles verifying mint and burn requests. A mintAuthority /// approves new assets to be minted by providing a digital signature. An ownernpm /// of an asset can request for it to be burnt. contract TornomyTokenGateway is Initializable, Claimable, CanReclaimTokens, GatewayState { using SafeMath for uint256; event LogMintAuthorityUpdated(address indexed _newMintAuthority); event LogMint( address indexed _to, uint256 _amount, uint256 indexed _n, bytes32 indexed _signedMessageHash ); event LogBurn( bytes _to, uint256 _amount, uint256 indexed _n, bytes indexed _indexedTo ); /// @notice Only allow the Darknode Payment contract. modifier onlyOwnerOrMintAuthority() { require( msg.sender == mintAuthority || msg.sender == owner(), "Gateway: caller is not the owner or mint authority" ); _; } /// @param _token The TornomyERC20 this Gateway is responsible for. /// @param _feeRecipient The recipient of burning and minting fees. /// @param _mintAuthority The address of the key that can sign mint /// requests. /// @param _mintFee The amount subtracted each mint request and /// forwarded to the feeRecipient. In BIPS. /// @param _burnFee The amount subtracted each burn request and /// forwarded to the feeRecipient. In BIPS. function initialize( TornomyERC20 _token, address _feeRecipient, address _mintAuthority, uint16 _mintFee, uint16 _burnFee, uint256 _minimumBurnAmount ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); minimumBurnAmount = _minimumBurnAmount; token = _token; mintFee = _mintFee; burnFee = _burnFee; updateMintAuthority(_mintAuthority); updateFeeRecipient(_feeRecipient); } // Public functions //////////////////////////////////////////////////////// /// @notice Claims ownership of the token passed in to the constructor. /// `transferStoreOwnership` must have previously been called. /// Anyone can call this function. function claimTokenOwnership() public { token.claimOwnership(); } /// @notice Allow the owner to update the owner of the TornomyERC20 token. function transferTokenOwnership(TornomyTokenGateway _nextTokenOwner) public onlyOwner { token.transferOwnership(address(_nextTokenOwner)); _nextTokenOwner.claimTokenOwnership(); } /// @notice Allow the owner to update the fee recipient. /// /// @param _nextMintAuthority The address to start paying fees to. function updateMintAuthority(address _nextMintAuthority) public onlyOwnerOrMintAuthority { // The mint authority should not be set to 0, which is the result // returned by ecrecover for an invalid signature. require( _nextMintAuthority != address(0), "Gateway: mintAuthority cannot be set to address zero" ); mintAuthority = _nextMintAuthority; emit LogMintAuthorityUpdated(mintAuthority); } /// @notice Allow the owner to update the minimum burn amount. /// /// @param _minimumBurnAmount The new min burn amount. function updateMinimumBurnAmount(uint256 _minimumBurnAmount) public onlyOwner { minimumBurnAmount = _minimumBurnAmount; } /// @notice Allow the owner to update the fee recipient. /// /// @param _nextFeeRecipient The address to start paying fees to. function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner { // 'mint' and 'burn' will fail if the feeRecipient is 0x0 require( _nextFeeRecipient != address(0x0), "Gateway: fee recipient cannot be 0x0" ); feeRecipient = _nextFeeRecipient; } /// @notice Allow the owner to update the 'mint' fee. /// /// @param _nextMintFee The new fee for minting and burning. function updateMintFee(uint16 _nextMintFee) public onlyOwner { mintFee = _nextMintFee; } /// @notice Allow the owner to update the burn fee. /// /// @param _nextBurnFee The new fee for minting and burning. function updateBurnFee(uint16 _nextBurnFee) public onlyOwner { burnFee = _nextBurnFee; } function mint( string calldata _symbol, address _recipient, uint256 _amount, bytes32 _nHash, bytes calldata _sig ) external { bytes32 payloadHash = keccak256(abi.encode(_symbol, _recipient)); // Verify signature bytes32 signedMessageHash = hashForSignature( _symbol, _recipient, _amount, msg.sender, _nHash ); require( status[signedMessageHash] == false, "Gateway: nonce hash already spent" ); if (!verifySignature(signedMessageHash, _sig)) { // Return a detailed string containing the hash and recovered // signer. This is somewhat costly but is only run in the revert // branch. revert( String.add8( "Gateway: invalid signature. pHash: ", String.fromBytes32(payloadHash), ", amount: ", String.fromUint(_amount), ", msg.sender: ", String.fromAddress(msg.sender), ", _nHash: ", String.fromBytes32(_nHash) ) ); } status[signedMessageHash] = true; // Mint `amount - fee` for the recipient and mint `fee` for the minter uint256 absoluteFee = _amount.mul(mintFee).div( BIPS_DENOMINATOR ); uint256 receivedAmount = _amount.sub( absoluteFee, "Gateway: fee exceeds amount" ); // Mint amount minus the fee token.mint(_recipient, receivedAmount); // Mint the fee token.mint(feeRecipient, absoluteFee); emit LogMint( _recipient, receivedAmount, nextN, signedMessageHash ); nextN += 1; } /// @notice burn destroys tokens after taking a fee for the `_feeRecipient`, /// allowing the associated assets to be released on their native /// chain. /// /// @param _to The address to receive the un-bridged asset. The format of /// this address should be of the destination chain. /// For example, when burning to Bitcoin, _to should be a /// Bitcoin address. /// @param _amount The amount of the token being burnt, in its /// smallest value. (e.g. satoshis for BTC) function burn(bytes calldata _to, uint256 _amount) external { // function burn(bytes memory _to, uint256 _amount) public returns (uint256) { require( token.transferFrom(_msgSender(), address(this), _amount), "token transfer failed" ); // The recipient must not be empty. Better validation is possible, // but would need to be customized for each destination ledger. require(_to.length != 0, "Gateway: to address is empty"); // Calculate fee, subtract it from amount being burnt. uint256 fee = _amount.mul(burnFee).div(BIPS_DENOMINATOR); uint256 amountAfterFee = _amount.sub( fee, "Gateway: fee exceeds amount" ); // Burn the whole amount, and then re-mint the fee. token.burn(address(this), _amount); token.mint(feeRecipient, fee); require( // Must be strictly greater, to that the release transaction is of // at least one unit. amountAfterFee > minimumBurnAmount, "Gateway: amount is less than the minimum burn amount" ); emit LogBurn(_to, amountAfterFee, nextN, _to); nextN += 1; } /// @notice verifySignature checks the the provided signature matches the provided /// parameters. function verifySignature(bytes32 _signedMessageHash, bytes memory _sig) public view returns (bool) { bytes32 ethSignedMessageHash = ECDSA.toEthSignedMessageHash(_signedMessageHash); address signer = ECDSA.recover(ethSignedMessageHash, _sig); return mintAuthority == signer; } /// @notice hashForSignature hashes the parameters so that they can be signed. function hashForSignature( string memory _symbol, address _recipient, uint256 _amount, address _caller, bytes32 _nHash ) public view returns (bytes32) { bytes32 payloadHash = keccak256(abi.encode(_symbol, _recipient)); return keccak256(abi.encode(payloadHash, _amount, address(token), _caller, _nHash)); } }
Contract initializer. _logic Address of the initial implementation. _data Data to send as msg.data to the implementation to initialize the proxied contract. It should include the signature and the parameters of the function to be called, as described in This parameter is optional, if no data is given the initialization call to proxied contract will be skipped./
function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } }
1,984,700
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @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); } // File @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.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); } // File @openzeppelin/contracts/utils/Context.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/token/ERC20/ERC20.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 {} } // File @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) /** * @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 { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // File @openzeppelin/contracts/security/Pausable.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (security/Pausable.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()); } } // File @openzeppelin/contracts/access/IAccessControl.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/utils/Strings.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @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/introspection/IERC165.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @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@v4.5.0 // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/access/AccessControl.sol@v4.5.0 // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { 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 virtual 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 revoked `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}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/ERC20/ERC20PermissionedMint.sol contract ERC20PermissionedMint is ERC20, ERC20Burnable, Owned { // Core address public timelock_address; // Minters address[] public minters_array; // Allowed to mint mapping(address => bool) public minters; // Mapping is also used for faster verification /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _timelock_address, string memory _name, string memory _symbol ) ERC20(_name, _symbol) Owned(_creator_address) { timelock_address = _timelock_address; } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyMinters() { require(minters[msg.sender] == true, "Only minters"); _; } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by minters when user redeems function minter_burn_from(address b_address, uint256 b_amount) public onlyMinters { super.burnFrom(b_address, b_amount); emit TokenMinterBurned(b_address, msg.sender, b_amount); } // This function is what other minters will call to mint new tokens function minter_mint(address m_address, uint256 m_amount) public onlyMinters { super._mint(m_address, m_amount); emit TokenMinterMinted(msg.sender, m_address, m_amount); } // Adds whitelisted minters function addMinter(address minter_address) public onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == false, "Address already exists"); minters[minter_address] = true; minters_array.push(minter_address); emit MinterAdded(minter_address); } // Remove a minter function removeMinter(address minter_address) public onlyByOwnGov { require(minter_address != address(0), "Zero address detected"); require(minters[minter_address] == true, "Address nonexistant"); // Delete from the mapping delete minters[minter_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < minters_array.length; i++){ if (minters_array[i] == minter_address) { minters_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit MinterRemoved(minter_address); } /* ========== EVENTS ========== */ event TokenMinterBurned(address indexed from, address indexed to, uint256 amount); event TokenMinterMinted(address indexed from, address indexed to, uint256 amount); event MinterAdded(address minter_address); event MinterRemoved(address minter_address); } // File contracts/FPI/FPI.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ================================ FPI =============================== // ==================================================================== // Frax Price Index // Initial peg target is the US CPI-U (Consumer Price Index, All Urban Consumers) // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jack Corddry: https://github.com/corddry // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett contract FPI is ERC20PermissionedMint { /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _timelock_address ) ERC20PermissionedMint(_creator_address, _timelock_address, "Frax Price Index", "FPI") { _mint(_creator_address, 100000000e18); // Genesis mint } } // File contracts/Frax/IFrax.sol interface IFrax { function COLLATERAL_RATIO_PAUSER() external view returns (bytes32); function DEFAULT_ADMIN_ADDRESS() external view returns (address); function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function addPool(address pool_address ) external; function allowance(address owner, address spender ) external view returns (uint256); function approve(address spender, uint256 amount ) external returns (bool); function balanceOf(address account ) external view returns (uint256); function burn(uint256 amount ) external; function burnFrom(address account, uint256 amount ) external; function collateral_ratio_paused() external view returns (bool); function controller_address() external view returns (address); function creator_address() external view returns (address); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool); function eth_usd_consumer_address() external view returns (address); function eth_usd_price() external view returns (uint256); function frax_eth_oracle_address() external view returns (address); function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256); function frax_pools(address ) external view returns (bool); function frax_pools_array(uint256 ) external view returns (address); function frax_price() external view returns (uint256); function frax_step() external view returns (uint256); function fxs_address() external view returns (address); function fxs_eth_oracle_address() external view returns (address); function fxs_price() external view returns (uint256); function genesis_supply() external view returns (uint256); function getRoleAdmin(bytes32 role ) external view returns (bytes32); function getRoleMember(bytes32 role, uint256 index ) external view returns (address); function getRoleMemberCount(bytes32 role ) external view returns (uint256); function globalCollateralValue() external view returns (uint256); function global_collateral_ratio() external view returns (uint256); function grantRole(bytes32 role, address account ) external; function hasRole(bytes32 role, address account ) external view returns (bool); function increaseAllowance(address spender, uint256 addedValue ) external returns (bool); function last_call_time() external view returns (uint256); function minting_fee() external view returns (uint256); function name() external view returns (string memory); function owner_address() external view returns (address); function pool_burn_from(address b_address, uint256 b_amount ) external; function pool_mint(address m_address, uint256 m_amount ) external; function price_band() external view returns (uint256); function price_target() external view returns (uint256); function redemption_fee() external view returns (uint256); function refreshCollateralRatio() external; function refresh_cooldown() external view returns (uint256); function removePool(address pool_address ) external; function renounceRole(bytes32 role, address account ) external; function revokeRole(bytes32 role, address account ) external; function setController(address _controller_address ) external; function setETHUSDOracle(address _eth_usd_consumer_address ) external; function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external; function setFXSAddress(address _fxs_address ) external; function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external; function setFraxStep(uint256 _new_step ) external; function setMintingFee(uint256 min_fee ) external; function setOwner(address _owner_address ) external; function setPriceBand(uint256 _price_band ) external; function setPriceTarget(uint256 _new_price_target ) external; function setRedemptionFee(uint256 red_fee ) external; function setRefreshCooldown(uint256 _new_cooldown ) external; function setTimelock(address new_timelock ) external; function symbol() external view returns (string memory); function timelock_address() external view returns (address); function toggleCollateralRatio() external; function totalSupply() external view returns (uint256); function transfer(address recipient, uint256 amount ) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool); function weth_address() external view returns (address); } // File contracts/Frax/IFraxAMOMinter.sol // MAY need to be updated interface IFraxAMOMinter { function FRAX() external view returns(address); function FXS() external view returns(address); function acceptOwnership() external; function addAMO(address amo_address, bool sync_too) external; function allAMOAddresses() external view returns(address[] memory); function allAMOsLength() external view returns(uint256); function amos(address) external view returns(bool); function amos_array(uint256) external view returns(address); function burnFraxFromAMO(uint256 frax_amount) external; function burnFxsFromAMO(uint256 fxs_amount) external; function col_idx() external view returns(uint256); function collatDollarBalance() external view returns(uint256); function collatDollarBalanceStored() external view returns(uint256); function collat_borrow_cap() external view returns(int256); function collat_borrowed_balances(address) external view returns(int256); function collat_borrowed_sum() external view returns(int256); function collateral_address() external view returns(address); function collateral_token() external view returns(address); function correction_offsets_amos(address, uint256) external view returns(int256); function custodian_address() external view returns(address); function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18); // function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes); function fraxDollarBalanceStored() external view returns(uint256); function fraxTrackedAMO(address amo_address) external view returns(int256); function fraxTrackedGlobal() external view returns(int256); function frax_mint_balances(address) external view returns(int256); function frax_mint_cap() external view returns(int256); function frax_mint_sum() external view returns(int256); function fxs_mint_balances(address) external view returns(int256); function fxs_mint_cap() external view returns(int256); function fxs_mint_sum() external view returns(int256); function giveCollatToAMO(address destination_amo, uint256 collat_amount) external; function min_cr() external view returns(uint256); function mintFraxForAMO(address destination_amo, uint256 frax_amount) external; function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external; function missing_decimals() external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function oldPoolCollectAndGive(address destination_amo) external; function oldPoolRedeem(uint256 frax_amount) external; function old_pool() external view returns(address); function owner() external view returns(address); function pool() external view returns(address); function receiveCollatFromAMO(uint256 usdc_amount) external; function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function removeAMO(address amo_address, bool sync_too) external; function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external; function setCollatBorrowCap(uint256 _collat_borrow_cap) external; function setCustodian(address _custodian_address) external; function setFraxMintCap(uint256 _frax_mint_cap) external; function setFraxPool(address _pool_address) external; function setFxsMintCap(uint256 _fxs_mint_cap) external; function setMinimumCollateralRatio(uint256 _min_cr) external; function setTimelock(address new_timelock) external; function syncDollarBalances() external; function timelock_address() external view returns(address); } // File contracts/Oracle/AggregatorV3Interface.sol interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File @chainlink/contracts/src/v0.8/vendor/BufferChainlink.sol@v0.4.0 /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library BufferChainlink { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint256 capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint256 capacity) internal pure returns (buffer memory) { 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(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns (buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint256 capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint256 a, uint256 b) private pure returns (uint256) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write( buffer memory buf, uint256 off, bytes memory data, uint256 len ) internal pure returns (buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint256 dest; uint256 src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } 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 unchecked { uint256 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 string to a 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. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append( buffer memory buf, bytes memory data, uint256 len ) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a 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, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8( buffer memory buf, uint256 off, uint8 data ) internal pure returns (buffer memory) { if (off >= 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 + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to 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, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns (buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write( buffer memory buf, uint256 off, bytes32 data, uint256 len ) private pure returns (buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } unchecked { uint256 mask = (256**len) - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20( buffer memory buf, uint256 off, bytes20 data ) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to 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, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to 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, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt( buffer memory buf, uint256 off, uint256 data, uint256 len ) private pure returns (buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint256 mask = (256**len) - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } 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 appendInt( buffer memory buf, uint256 data, uint256 len ) internal pure returns (buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } // File @chainlink/contracts/src/v0.8/vendor/CBORChainlink.sol@v0.4.0 library CBORChainlink { using BufferChainlink for BufferChainlink.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_TAG = 6; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; uint8 private constant TAG_TYPE_BIGNUM = 2; uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3; function encodeFixedNumeric(BufferChainlink.buffer memory buf, uint8 major, uint64 value) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if (value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if (value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if (value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure { if(value > 0xFFFFFFFFFFFFFFFF) { encodeBigNum(buf, value); } else { encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(value)); } } function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure { if(value < -0x10000000000000000) { encodeSignedBigNum(buf, value); } else if(value > 0xFFFFFFFFFFFFFFFF) { encodeBigNum(buf, uint(value)); } else if(value >= 0) { encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(uint256(value))); } else { encodeFixedNumeric(buf, MAJOR_TYPE_NEGATIVE_INT, uint64(uint256(-1 - value))); } } function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure { encodeFixedNumeric(buf, MAJOR_TYPE_BYTES, uint64(value.length)); buf.append(value); } function encodeBigNum(BufferChainlink.buffer memory buf, uint value) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM)); encodeBytes(buf, abi.encode(value)); } function encodeSignedBigNum(BufferChainlink.buffer memory buf, int input) internal pure { buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM)); encodeBytes(buf, abi.encode(uint256(-1 - input))); } function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure { encodeFixedNumeric(buf, MAJOR_TYPE_STRING, uint64(bytes(value).length)); buf.append(bytes(value)); } function startArray(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(BufferChainlink.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } // File @chainlink/contracts/src/v0.8/Chainlink.sol@v0.4.0 /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBORChainlink for BufferChainlink.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; BufferChainlink.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param jobId The Job Specification ID * @param callbackAddr The callback address * @param callbackFunc The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 jobId, address callbackAddr, bytes4 callbackFunc ) internal pure returns (Chainlink.Request memory) { BufferChainlink.init(self.buf, defaultBufferSize); self.id = jobId; self.callbackAddress = callbackAddr; self.callbackFunctionId = callbackFunc; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param data The CBOR data */ function setBuffer(Request memory self, bytes memory data) internal pure { BufferChainlink.init(self.buf, data.length); BufferChainlink.append(self.buf, data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The string value to add */ function add( Request memory self, string memory key, string memory value ) internal pure { self.buf.encodeString(key); self.buf.encodeString(value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The bytes value to add */ function addBytes( Request memory self, string memory key, bytes memory value ) internal pure { self.buf.encodeString(key); self.buf.encodeBytes(value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The int256 value to add */ function addInt( Request memory self, string memory key, int256 value ) internal pure { self.buf.encodeString(key); self.buf.encodeInt(value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param key The name of the key * @param value The uint256 value to add */ function addUint( Request memory self, string memory key, uint256 value ) internal pure { self.buf.encodeString(key); self.buf.encodeUInt(value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param key The name of the key * @param values The array of string values to add */ function addStringArray( Request memory self, string memory key, string[] memory values ) internal pure { self.buf.encodeString(key); self.buf.startArray(); for (uint256 i = 0; i < values.length; i++) { self.buf.encodeString(values[i]); } self.buf.endSequence(); } } // File @chainlink/contracts/src/v0.8/interfaces/ENSInterface.sol@v0.4.0 interface ENSInterface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner( bytes32 node, bytes32 label, address owner ) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } // File @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol@v0.4.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); } // File @chainlink/contracts/src/v0.8/interfaces/ChainlinkRequestInterface.sol@v0.4.0 interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } // File @chainlink/contracts/src/v0.8/interfaces/OracleInterface.sol@v0.4.0 interface OracleInterface { function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external returns (bool); function isAuthorizedSender(address node) external view returns (bool); function withdraw(address recipient, uint256 amount) external; function withdrawable() external view returns (uint256); } // File @chainlink/contracts/src/v0.8/interfaces/OperatorInterface.sol@v0.4.0 interface OperatorInterface is OracleInterface, ChainlinkRequestInterface { function operatorRequest( address sender, uint256 payment, bytes32 specId, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, bytes calldata data ) external; function fulfillOracleRequest2( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes calldata data ) external returns (bool); function ownerTransferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function distributeFunds(address payable[] calldata receivers, uint256[] calldata amounts) external payable; function getAuthorizedSenders() external returns (address[] memory); function setAuthorizedSenders(address[] calldata senders) external; function getForwarder() external returns (address); } // File @chainlink/contracts/src/v0.8/interfaces/PointerInterface.sol@v0.4.0 interface PointerInterface { function getAddress() external view returns (address); } // File @chainlink/contracts/src/v0.8/vendor/ENSResolver.sol@v0.4.0 abstract contract ENSResolver_Chainlink { function addr(bytes32 node) public view virtual returns (address); } // File @chainlink/contracts/src/v0.8/ChainlinkClient.sol@v0.4.0 /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ abstract contract ChainlinkClient { using Chainlink for Chainlink.Request; uint256 internal constant LINK_DIVISIBILITY = 10**18; uint256 private constant AMOUNT_OVERRIDE = 0; address private constant SENDER_OVERRIDE = address(0); uint256 private constant ORACLE_ARGS_VERSION = 1; uint256 private constant OPERATOR_ARGS_VERSION = 2; bytes32 private constant ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 private constant ENS_ORACLE_SUBNAME = keccak256("oracle"); address private constant LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private s_ens; bytes32 private s_ensNode; LinkTokenInterface private s_link; OperatorInterface private s_oracle; uint256 private s_requestCount = 1; mapping(bytes32 => address) private s_pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param specId The Job Specification ID that the request will be created for * @param callbackAddr address to operate the callback on * @param callbackFunctionSignature function signature to use for the callback * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 specId, address callbackAddr, bytes4 callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(specId, callbackAddr, callbackFunctionSignature); } /** * @notice Creates a request that can hold additional parameters * @param specId The Job Specification ID that the request will be created for * @param callbackFunctionSignature function signature to use for the callback * @return A Chainlink Request struct in memory */ function buildOperatorRequest(bytes32 specId, bytes4 callbackFunctionSignature) internal view returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(specId, address(this), callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(s_oracle), req, payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param oracleAddress The address of the oracle for the request * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendChainlinkRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns (bytes32 requestId) { uint256 nonce = s_requestCount; s_requestCount = nonce + 1; bytes memory encodedRequest = abi.encodeWithSelector( ChainlinkRequestInterface.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent req.id, address(this), req.callbackFunctionId, nonce, ORACLE_ARGS_VERSION, req.buf.buf ); return _rawRequest(oracleAddress, nonce, payment, encodedRequest); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev This function supports multi-word response * @dev Calls `sendOperatorRequestTo` with the stored oracle address * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendOperatorRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) { return sendOperatorRequestTo(address(s_oracle), req, payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev This function supports multi-word response * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param oracleAddress The address of the oracle for the request * @param req The initialized Chainlink Request * @param payment The amount of LINK to send for the request * @return requestId The request ID */ function sendOperatorRequestTo( address oracleAddress, Chainlink.Request memory req, uint256 payment ) internal returns (bytes32 requestId) { uint256 nonce = s_requestCount; s_requestCount = nonce + 1; bytes memory encodedRequest = abi.encodeWithSelector( OperatorInterface.operatorRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent req.id, req.callbackFunctionId, nonce, OPERATOR_ARGS_VERSION, req.buf.buf ); return _rawRequest(oracleAddress, nonce, payment, encodedRequest); } /** * @notice Make a request to an oracle * @param oracleAddress The address of the oracle for the request * @param nonce used to generate the request ID * @param payment The amount of LINK to send for the request * @param encodedRequest data encoded for request type specific format * @return requestId The request ID */ function _rawRequest( address oracleAddress, uint256 nonce, uint256 payment, bytes memory encodedRequest ) private returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, nonce)); s_pendingRequests[requestId] = oracleAddress; emit ChainlinkRequested(requestId); require(s_link.transferAndCall(oracleAddress, payment, encodedRequest), "unable to transferAndCall to oracle"); } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param requestId The request ID * @param payment The amount of LINK sent for the request * @param callbackFunc The callback function specified for the request * @param expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunc, uint256 expiration ) internal { OperatorInterface requested = OperatorInterface(s_pendingRequests[requestId]); delete s_pendingRequests[requestId]; emit ChainlinkCancelled(requestId); requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration); } /** * @notice the next request count to be used in generating a nonce * @dev starts at 1 in order to ensure consistent gas cost * @return returns the next request count to be used in a nonce */ function getNextRequestCount() internal view returns (uint256) { return s_requestCount; } /** * @notice Sets the stored oracle address * @param oracleAddress The address of the oracle contract */ function setChainlinkOracle(address oracleAddress) internal { s_oracle = OperatorInterface(oracleAddress); } /** * @notice Sets the LINK token address * @param linkAddress The address of the LINK token contract */ function setChainlinkToken(address linkAddress) internal { s_link = LinkTokenInterface(linkAddress); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(s_link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(s_oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param oracleAddress The address of the oracle contract that will fulfill the request * @param requestId The request ID used for the response */ function addChainlinkExternalRequest(address oracleAddress, bytes32 requestId) internal notPendingRequest(requestId) { s_pendingRequests[requestId] = oracleAddress; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param ensAddress The address of the ENS contract * @param node The ENS node hash */ function useChainlinkWithENS(address ensAddress, bytes32 node) internal { s_ens = ENSInterface(ensAddress); s_ensNode = node; bytes32 linkSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_TOKEN_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_ORACLE_SUBNAME)); ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 requestId) internal recordChainlinkFulfillment(requestId) // solhint-disable-next-line no-empty-blocks { } /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 requestId) { require(msg.sender == s_pendingRequests[requestId], "Source must be the oracle of the request"); delete s_pendingRequests[requestId]; emit ChainlinkFulfilled(requestId); _; } /** * @dev Reverts if the request is already pending * @param requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 requestId) { require(s_pendingRequests[requestId] == address(0), "Request is already pending"); _; } } // File contracts/Math/BokkyPooBahsDateTimeLibrary.sol // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // File contracts/Math/BokkyPooBahsDateTimeContract.sol // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.00 - Contract Instance // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- contract BokkyPooBahsDateTimeContract { uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant SECONDS_PER_HOUR = 60 * 60; uint public constant SECONDS_PER_MINUTE = 60; int public constant OFFSET19700101 = 2440588; uint public constant DOW_MON = 1; uint public constant DOW_TUE = 2; uint public constant DOW_WED = 3; uint public constant DOW_THU = 4; uint public constant DOW_FRI = 5; uint public constant DOW_SAT = 6; uint public constant DOW_SUN = 7; function _now() public view returns (uint timestamp) { timestamp = block.timestamp; } function _nowDateTime() public view returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp); } function _daysFromDate(uint year, uint month, uint day) public pure returns (uint _days) { return BokkyPooBahsDateTimeLibrary._daysFromDate(year, month, day); } function _daysToDate(uint _days) public pure returns (uint year, uint month, uint day) { return BokkyPooBahsDateTimeLibrary._daysToDate(_days); } function timestampFromDate(uint year, uint month, uint day) public pure returns (uint timestamp) { return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day); } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (uint timestamp) { return BokkyPooBahsDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second); } function timestampToDate(uint timestamp) public pure returns (uint year, uint month, uint day) { (year, month, day) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); } function timestampToDateTime(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(timestamp); } function isValidDate(uint year, uint month, uint day) public pure returns (bool valid) { valid = BokkyPooBahsDateTimeLibrary.isValidDate(year, month, day); } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (bool valid) { valid = BokkyPooBahsDateTimeLibrary.isValidDateTime(year, month, day, hour, minute, second); } function isLeapYear(uint timestamp) public pure returns (bool leapYear) { leapYear = BokkyPooBahsDateTimeLibrary.isLeapYear(timestamp); } function _isLeapYear(uint year) public pure returns (bool leapYear) { leapYear = BokkyPooBahsDateTimeLibrary._isLeapYear(year); } function isWeekDay(uint timestamp) public pure returns (bool weekDay) { weekDay = BokkyPooBahsDateTimeLibrary.isWeekDay(timestamp); } function isWeekEnd(uint timestamp) public pure returns (bool weekEnd) { weekEnd = BokkyPooBahsDateTimeLibrary.isWeekEnd(timestamp); } function getDaysInMonth(uint timestamp) public pure returns (uint daysInMonth) { daysInMonth = BokkyPooBahsDateTimeLibrary.getDaysInMonth(timestamp); } function _getDaysInMonth(uint year, uint month) public pure returns (uint daysInMonth) { daysInMonth = BokkyPooBahsDateTimeLibrary._getDaysInMonth(year, month); } function getDayOfWeek(uint timestamp) public pure returns (uint dayOfWeek) { dayOfWeek = BokkyPooBahsDateTimeLibrary.getDayOfWeek(timestamp); } function getYear(uint timestamp) public pure returns (uint year) { year = BokkyPooBahsDateTimeLibrary.getYear(timestamp); } function getMonth(uint timestamp) public pure returns (uint month) { month = BokkyPooBahsDateTimeLibrary.getMonth(timestamp); } function getDay(uint timestamp) public pure returns (uint day) { day = BokkyPooBahsDateTimeLibrary.getDay(timestamp); } function getHour(uint timestamp) public pure returns (uint hour) { hour = BokkyPooBahsDateTimeLibrary.getHour(timestamp); } function getMinute(uint timestamp) public pure returns (uint minute) { minute = BokkyPooBahsDateTimeLibrary.getMinute(timestamp); } function getSecond(uint timestamp) public pure returns (uint second) { second = BokkyPooBahsDateTimeLibrary.getSecond(timestamp); } function addYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addYears(timestamp, _years); } function addMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addMonths(timestamp, _months); } function addDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addDays(timestamp, _days); } function addHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addHours(timestamp, _hours); } function addMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addMinutes(timestamp, _minutes); } function addSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.addSeconds(timestamp, _seconds); } function subYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subYears(timestamp, _years); } function subMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subMonths(timestamp, _months); } function subDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subDays(timestamp, _days); } function subHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subHours(timestamp, _hours); } function subMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subMinutes(timestamp, _minutes); } function subSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) { newTimestamp = BokkyPooBahsDateTimeLibrary.subSeconds(timestamp, _seconds); } function diffYears(uint fromTimestamp, uint toTimestamp) public pure returns (uint _years) { _years = BokkyPooBahsDateTimeLibrary.diffYears(fromTimestamp, toTimestamp); } function diffMonths(uint fromTimestamp, uint toTimestamp) public pure returns (uint _months) { _months = BokkyPooBahsDateTimeLibrary.diffMonths(fromTimestamp, toTimestamp); } function diffDays(uint fromTimestamp, uint toTimestamp) public pure returns (uint _days) { _days = BokkyPooBahsDateTimeLibrary.diffDays(fromTimestamp, toTimestamp); } function diffHours(uint fromTimestamp, uint toTimestamp) public pure returns (uint _hours) { _hours = BokkyPooBahsDateTimeLibrary.diffHours(fromTimestamp, toTimestamp); } function diffMinutes(uint fromTimestamp, uint toTimestamp) public pure returns (uint _minutes) { _minutes = BokkyPooBahsDateTimeLibrary.diffMinutes(fromTimestamp, toTimestamp); } function diffSeconds(uint fromTimestamp, uint toTimestamp) public pure returns (uint _seconds) { _seconds = BokkyPooBahsDateTimeLibrary.diffSeconds(fromTimestamp, toTimestamp); } } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/Oracle/CPITrackerOracle.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= CPITrackerOracle ========================= // ==================================================================== // Pull in CPI data and track it in Dec 2021 dollars // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett // References // https://docs.chain.link/docs/make-a-http-get-request/#api-consumer-example contract CPITrackerOracle is Owned, ChainlinkClient { using Chainlink for Chainlink.Request; // Core BokkyPooBahsDateTimeContract public time_contract; address public timelock_address; address public bot_address; // Data uint256 public cpi_last = 28012600000; // Dec 2021 CPI-U, 280.126 * 100000000 uint256 public cpi_target = 28193300000; // Jan 2022 CPI-U, 281.933 * 100000000 uint256 public peg_price_last = 1e18; // Use currPegPrice(). Will always be in Dec 2021 dollars uint256 public peg_price_target = 1006450668627688968; // Will always be in Dec 2021 dollars // Chainlink address public oracle; // Chainlink CPI oracle address bytes32 public jobId; // Job ID for the CPI-U date uint256 public fee; // LINK token fee // Tracking uint256 public stored_year = 2022; // Last time (year) the stored CPI data was updated uint256 public stored_month = 1; // Last time (month) the stored CPI data was updated uint256 public lastUpdateTime = 1644886800; // Last time the stored CPI data was updated. uint256 public ramp_period = 28 * 86400; // Apply the CPI delta to the peg price over a set period uint256 public future_ramp_period = 28 * 86400; CPIObservation[] public cpi_observations; // Historical tracking of CPI data // Safety uint256 public max_delta_frac = 25000; // 2.5%. Max month-to-month CPI delta. // Misc string[13] public month_names; // English names of the 12 months uint256 public fulfill_ready_day = 15; // Date of the month that CPI data is expected to by ready by /* ========== STRUCTS ========== */ struct CPIObservation { uint256 result_year; uint256 result_month; uint256 cpi_target; uint256 peg_price_target; uint256 timestamp; } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier onlyByOwnGovBot() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == bot_address, "Not owner, tlck, or bot"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _creator_address, address _timelock_address ) Owned(_creator_address) { timelock_address = _timelock_address; // Initialize the array. Cannot be done in the declaration month_names = [ '', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; // CPI [Ethereum] // ================================= // setPublicChainlinkToken(); // time_contract = BokkyPooBahsDateTimeContract(0x90503D86E120B3B309CEBf00C2CA013aB3624736); // oracle = 0x049Bd8C3adC3fE7d3Fc2a44541d955A537c2A484; // jobId = "1c309d42c7084b34b1acf1a89e7b51fc"; // fee = 50e18; // 50 LINK // CPI [Polygon Mainnet] // ================================= // setChainlinkToken(0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39); // time_contract = BokkyPooBahsDateTimeContract(0x998da4fCB229Db1AA84395ef6f0c6be6Ef3dbE58); // oracle = 0x9B44870bcc35734c08e40F847cC068c0bA618194; // jobId = "8107f18343a24980b2fe7d3c8f32630f"; // fee = 1e17; // 0.1 LINK // CPI [Polygon Mumbai] // ================================= setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB); time_contract = BokkyPooBahsDateTimeContract(0x2Dd1B4D4548aCCeA497050619965f91f78b3b532); oracle = 0x3c30c5c415B2410326297F0f65f5Cbb32f3aefCc; jobId = "32c3e7b12fe44665a4e2bb87aa9779af"; fee = 1e17; // 0.1 LINK // Add the first observation cpi_observations.push(CPIObservation( 2021, 12, cpi_last, peg_price_last, 1642208400 // Dec data observed on Jan 15 2021 )); // Add the second observation cpi_observations.push(CPIObservation( 2022, 1, cpi_target, peg_price_target, 1644886800 // Jan data observed on Feb 15 2022 )); } /* ========== VIEWS ========== */ function upcomingCPIParams() public view returns ( uint256 upcoming_year, uint256 upcoming_month, uint256 upcoming_timestamp ) { if (stored_month == 12) { upcoming_year = stored_year + 1; upcoming_month = 1; } else { upcoming_year = stored_year; upcoming_month = stored_month + 1; } // Data is usually released by the 15th day of the next month (fulfill_ready_day) // https://www.usinflationcalculator.com/inflation/consumer-price-index-release-schedule/ upcoming_timestamp = time_contract.timestampFromDate(upcoming_year, upcoming_month, fulfill_ready_day); } // Display the upcoming CPI month function upcomingSerie() external view returns (string memory serie_name) { // Get the upcoming CPI params (uint256 upcoming_year, uint256 upcoming_month, ) = upcomingCPIParams(); // Convert to a string return string(abi.encodePacked("CUSR0000SA0", " ", month_names[upcoming_month], " ", Strings.toString(upcoming_year))); } // Delta between the current and previous peg prices function currDeltaFracE6() public view returns (int256) { return int256(((peg_price_target - peg_price_last) * 1e6) / peg_price_last); } // Absolute value of the delta between the current and previous peg prices function currDeltaFracAbsE6() public view returns (uint256) { int256 curr_delta_frac = currDeltaFracE6(); if (curr_delta_frac > 0) return uint256(curr_delta_frac); else return uint256(-curr_delta_frac); } // Current peg price in E18, accounting for the ramping function currPegPrice() external view returns (uint256) { uint256 elapsed_time = block.timestamp - lastUpdateTime; if (elapsed_time >= ramp_period) { return peg_price_target; } else { // Calculate the fraction of the delta to use, based on the elapsed time // Can be negative in case of deflation (that never happens right :]) int256 fractional_price_delta = (int256(peg_price_target - peg_price_last) * int256(elapsed_time)) / int256(ramp_period); return uint256(int256(peg_price_last) + int256(fractional_price_delta)); } } /* ========== MUTATIVE ========== */ // Fetch the CPI data from the Chainlink oracle function requestCPIData() external onlyByOwnGovBot returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); // Get the upcoming CPI params (uint256 upcoming_year, uint256 upcoming_month, uint256 upcoming_timestamp) = upcomingCPIParams(); // Don't update too fast require(block.timestamp >= upcoming_timestamp, "Too early"); request.add("serie", "CUSR0000SA0"); // CPI-U: https://data.bls.gov/timeseries/CUSR0000SA0 request.add("month", month_names[upcoming_month]); request.add("year", Strings.toString(upcoming_year)); return sendChainlinkRequestTo(oracle, request, fee); } /** * Callback function */ // Called by the Chainlink oracle function fulfill(bytes32 _requestId, uint256 result) public recordChainlinkFulfillment(_requestId) { // Set the stored CPI and price to the old targets cpi_last = cpi_target; peg_price_last = peg_price_target; // Set the target CPI and price based on the results cpi_target = result; peg_price_target = (peg_price_last * cpi_target) / cpi_last; // Make sure the delta isn't too large require(currDeltaFracAbsE6() <= max_delta_frac, "Delta too high"); // Update the timestamp lastUpdateTime = block.timestamp; // Update the year and month (uint256 result_year, uint256 result_month, ) = upcomingCPIParams(); stored_year = result_year; stored_month = result_month; // Update the future ramp period, if applicable // A ramp cannot be updated mid-month as it will mess up the last_price math; ramp_period = future_ramp_period; // Add the observation cpi_observations.push(CPIObservation( result_year, result_month, cpi_target, peg_price_target, block.timestamp )); emit CPIUpdated(result_year, result_month, result, peg_price_target, ramp_period); } function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) external onlyByOwnGovBot { cancelChainlinkRequest(_requestId, _payment, _callbackFunc, _expiration); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTimelock(address _new_timelock_address) external onlyByOwnGov { timelock_address = _new_timelock_address; } function setBot(address _new_bot_address) external onlyByOwnGov { bot_address = _new_bot_address; } function setOracleInfo(address _oracle, bytes32 _jobId, uint256 _fee) external onlyByOwnGov { oracle = _oracle; jobId = _jobId; fee = _fee; } function setMaxDeltaFrac(uint256 _max_delta_frac) external onlyByOwnGov { max_delta_frac = _max_delta_frac; } function setFulfillReadyDay(uint256 _fulfill_ready_day) external onlyByOwnGov { fulfill_ready_day = _fulfill_ready_day; } function setFutureRampPeriod(uint256 _future_ramp_period) external onlyByOwnGov { future_ramp_period = _future_ramp_period; // In sec } // Mainly for recovering LINK function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); } /* ========== EVENTS ========== */ event CPIUpdated(uint256 year, uint256 month, uint256 result, uint256 peg_price_target, uint256 ramp_period); } // File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2PairV5.sol interface IUniswapV2PairV5 { 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; } // File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniV2TWAMMPair.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= IUniV2TWAMMPair ========================== // ==================================================================== // TWAMM LP Pair Interface // Inspired by https://www.paradigm.xyz/2021/07/twamm // https://github.com/para-dave/twamm // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett // Reviewer(s) / Contributor(s) // Travis Moore: https://github.com/FortisFortuna // Sam Kazemian: https://github.com/samkazemian interface IUniV2TWAMMPair is IUniswapV2PairV5 { // TWAMM event LongTermSwap0To1(address indexed addr, uint256 orderId, uint256 amount0In, uint256 numberOfTimeIntervals); event LongTermSwap1To0(address indexed addr, uint256 orderId, uint256 amount1In, uint256 numberOfTimeIntervals); event CancelLongTermOrder(address indexed addr, uint256 orderId, address sellToken, uint256 unsoldAmount, address buyToken, uint256 purchasedAmount); event WithdrawProceedsFromLongTermOrder(address indexed addr, uint256 orderId, address indexed proceedToken, uint256 proceeds, bool orderExpired); function longTermSwapFrom0To1(uint256 amount0In, uint256 numberOfTimeIntervals) external returns (uint256 orderId); function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external returns (uint256 orderId); function cancelLongTermSwap(uint256 orderId) external; function withdrawProceedsFromLongTermSwap(uint256 orderId) external returns (bool is_expired); function executeVirtualOrders(uint256 blockTimestamp) external; function orderTimeInterval() external returns (uint256); function getTWAPHistoryLength() external view returns (uint); function getTwammReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast, uint112 _twammReserve0, uint112 _twammReserve1); function getReserveAfterTwamm(uint256 blockTimestamp) external view returns (uint112 _reserve0, uint112 _reserve1, uint256 lastVirtualOrderTimestamp, uint112 _twammReserve0, uint112 _twammReserve1); function getNextOrderID() external view returns (uint256); function getOrderIDsForUser(address user) external view returns (uint256[] memory); function getOrderIDsForUserLength(address user) external view returns (uint256); // function getDetailedOrdersForUser(address user, uint256 offset, uint256 limit) external view returns (LongTermOrdersLib.Order[] memory detailed_orders); function twammUpToDate() external view returns (bool); function getTwammState() external view returns (uint256 token0Rate, uint256 token1Rate, uint256 lastVirtualOrderTimestamp, uint256 orderTimeInterval_rtn, uint256 rewardFactorPool0, uint256 rewardFactorPool1); function getTwammSalesRateEnding(uint256 _blockTimestamp) external view returns (uint256 orderPool0SalesRateEnding, uint256 orderPool1SalesRateEnding); function getTwammRewardFactor(uint256 _blockTimestamp) external view returns (uint256 rewardFactorPool0AtTimestamp, uint256 rewardFactorPool1AtTimestamp); function getTwammOrder(uint256 orderId) external view returns (uint256 id, uint256 expirationTimestamp, uint256 saleRate, address owner, address sellTokenAddr, address buyTokenAddr); function getTwammOrderProceeds(uint256 orderId, uint256 blockTimestamp) external view returns (bool orderExpired, uint256 totalReward); function togglePauseNewSwaps() external; } // File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2FactoryV5.sol interface IUniswapV2FactoryV5 { 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; } // File contracts/Uniswap_V2_TWAMM/libraries/Babylonian.sol // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // 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; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas 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); } } // File contracts/Uniswap_V2_TWAMM/libraries/FullMath.sol /// @notice Math library that facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision. /// @author Adapted from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/FullMath.sol. /// @dev Handles "phantom overflow", i.e., allows multiplication and division where an intermediate value overflows 256 bits. library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision - throws if result overflows an uint256 or denominator == 0. /// @param a The multiplicand. /// @param b The multiplier. /// @param denominator The divisor. /// @return result The 256-bit result. /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b. // Compute the product mod 2**256 and mod 2**256 - 1, // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0. uint256 prod0; // Least significant 256 bits of the product. uint256 prod1; // Most significant 256 bits of the product. assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256 - // also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] - // compute remainder using mulmod. uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number. assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator - // compute largest power of two divisor of denominator // (always >= 1). uint256 twos = uint256(-int256(denominator)) & denominator; // Divide denominator by power of two. assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two. assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos - // if twos is zero, then it becomes one. assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 - // now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // for four bits. That is, denominator * inv = 1 mod 2**4. uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // Inverse mod 2**8. inv *= 2 - denominator * inv; // Inverse mod 2**16. inv *= 2 - denominator * inv; // Inverse mod 2**32. inv *= 2 - denominator * inv; // Inverse mod 2**64. inv *= 2 - denominator * inv; // Inverse mod 2**128. inv *= 2 - denominator * inv; // Inverse mod 2**256. // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision - throws if result overflows an uint256 or denominator == 0. /// @param a The multiplicand. /// @param b The multiplier. /// @param denominator The divisor. /// @return result The 256-bit result. function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); unchecked { if (mulmod(a, b, denominator) != 0) { require(result < type(uint256).max); result++; } } } } // File contracts/Uniswap_V2_TWAMM/periphery/libraries/UniswapV2LiquidityMathLibraryMini.sol // library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value // in terms of the underlying tokens library UniswapV2LiquidityMathLibraryMini { // computes the direction and magnitude of the profit-maximizing trade // function computeProfitMaximizingTrade( // uint256 truePriceTokenA, // uint256 truePriceTokenB, // uint256 reserveA, // uint256 reserveB // ) pure internal returns (uint256 amountIn) { // bool aToB = ((reserveA * truePriceTokenB) / reserveB) < truePriceTokenA; // uint256 invariant = reserveA * reserveB; // // true price is expressed as a ratio, so both values must be non-zero // require(truePriceTokenA != 0 && truePriceTokenB != 0, "CPMT: ZERO_PRICE"); // uint256 leftSide = Babylonian.sqrt( // FullMath.mulDiv( // (invariant * 1000), // aToB ? truePriceTokenA : truePriceTokenB, // (aToB ? truePriceTokenB : truePriceTokenA) * 997 // ) // ); // uint256 rightSide = (aToB ? reserveA * 1000 : reserveB * 1000) / 997; // if (leftSide < rightSide) return (0); // // compute the amount that must be sent to move the price to the profit-maximizing price // amountIn = leftSide - rightSide; // } function computeProfitMaximizingTrade( uint256 inTokenTruePrice, uint256 outTokenTruePrice, uint256 reserveIn, uint256 reserveOut ) pure internal returns (uint256 amountIn) { uint256 invariant = reserveIn * reserveOut; // true price is expressed as a ratio, so both values must be non-zero require(inTokenTruePrice != 0 && outTokenTruePrice != 0, "CPMT: ZERO_PRICE"); uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( (invariant * 1000), inTokenTruePrice, outTokenTruePrice * 997 ) ); uint256 rightSide = (reserveIn * 1000) / 997; if (leftSide < rightSide) return (0); // compute the amount that must be sent to move the price to the profit-maximizing price amountIn = leftSide - rightSide; } } // File contracts/FPI/FPIControllerPool.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FPIControllerPool ========================= // ==================================================================== // Makes sure FPI is targeting the CPI peg // First method is minting / redeeming with FRAX // Second is bulk TWAMM trades // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Rich Gee: https://github.com/zer0blockchain // Dennis: https://github.com/denett // Jack Corddry: https://github.com/corddry contract FPIControllerPool is Owned { // Core address public timelock_address; FPI public FPI_TKN; IFrax public FRAX; IUniV2TWAMMPair public TWAMM; // Oracles AggregatorV3Interface public priceFeedFRAXUSD; AggregatorV3Interface public priceFeedFPIUSD; uint256 public chainlink_frax_usd_decimals; uint256 public chainlink_fpi_usd_decimals; CPITrackerOracle public cpiTracker; // Tracking uint256 public last_order_id_twamm; // Last TWAMM order ID that was used // AMO addresses (lend out FRAX) address[] public amos_array; mapping(address => bool) public amos; // Mapping is also used for faster verification // FRAX borrowed balances mapping(address => int256) public frax_borrowed_balances; // Amount of FRAX the contract borrowed, by AMO int256 public frax_borrowed_sum = 0; // Across all AMOs int256 public frax_borrow_cap = int256(10000000e18); // Max amount of FRAX the contract can borrow from this contract // Mint Fee Related bool public use_manual_mint_fee = true; uint256 public mint_fee_manual = 3000; // E6 uint256 public mint_fee_multiplier = 1000000; // E6 // Redeem Fee Related bool public use_manual_redeem_fee = true; uint256 public redeem_fee_manual = 3000; // E6 uint256 public redeem_fee_multiplier = 1000000; // E6 // Safety uint256 public fpi_mint_cap = 110000000e18; // 110M uint256 public peg_band_mint_redeem = 50000; // 5% uint256 public peg_band_twamm = 100000; // 10% uint256 public max_swap_frax_amt_in = 10000000e18; // 10M, mainly fat-finger precautions uint256 public max_swap_fpi_amt_in = 10000000e18; // 10M, mainly fat-finger precautions bool public mints_paused = false; bool public redeems_paused = false; // Constants for various precisions uint256 public constant PRICE_PRECISION = 1e18; uint256 public constant FEE_PRECISION = 1e6; uint256 public constant PEG_BAND_PRECISION = 1e6; // Misc bool public frax_is_token0; bool public pending_twamm_order = false; uint256 public num_twamm_intervals = 168; // Each interval is default 3600 sec (1 hr) uint256 public swap_period = 7 * 86400; // 7 days /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock"); _; } modifier validAMO(address amo_address) { require(amos[amo_address], "Invalid AMO"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _creator_address, address _timelock_address, address[6] memory _address_pack ) Owned(_creator_address) { timelock_address = _timelock_address; // Set instances FRAX = IFrax(_address_pack[0]); FPI_TKN = FPI(_address_pack[1]); TWAMM = IUniV2TWAMMPair(_address_pack[2]); priceFeedFRAXUSD = AggregatorV3Interface(_address_pack[3]); priceFeedFPIUSD = AggregatorV3Interface(_address_pack[4]); cpiTracker = CPITrackerOracle(_address_pack[5]); // Set the oracle decimals chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals(); chainlink_fpi_usd_decimals = priceFeedFPIUSD.decimals(); // Need to know which token FRAX is (0 or 1) address token0 = TWAMM.token0(); if (token0 == address(FRAX)) frax_is_token0 = true; else frax_is_token0 = false; // Get the number of TWAMM intervals. Truncation desired num_twamm_intervals = swap_period / TWAMM.orderTimeInterval(); } /* ========== VIEWS ========== */ // Needed as a FRAX AMO function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = FRAX.balanceOf(address(this)); collat_val_e18 = (frax_val_e18 * 1e6) / FRAX.global_collateral_ratio(); } // In Chainlink decimals function getFRAXPriceE18() public view returns (uint256) { (uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFRAXUSD.latestRoundData(); require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price"); return ((uint256(price) * 1e18) / (10 ** chainlink_frax_usd_decimals)); } // In Chainlink decimals function getFPIPriceE18() public view returns (uint256) { (uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFPIUSD.latestRoundData(); require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price"); return ((uint256(price) * 1e18) / (10 ** chainlink_fpi_usd_decimals)); } // Reserve spot price (fpi_price is dangerous / flash loan susceptible, so use carefully) function getReservesAndFPISpot() public returns (uint256 reserveFRAX, uint256 reserveFPI, uint256 fpi_price) { // Update and get the reserves TWAMM.executeVirtualOrders(block.timestamp); { (uint256 reserveA, uint256 reserveB, ) = TWAMM.getReserves(); if (frax_is_token0){ reserveFRAX = reserveA; reserveFPI = reserveB; } else { reserveFRAX = reserveB; reserveFPI = reserveA; } } // Get the TWAMM reserve spot price fpi_price = (reserveFRAX * 1e18) / reserveFPI; } // function getTwammToPegAmt() public returns (uint256 frax_in, uint256 fpi_in) { // // Update and get the reserves // (uint256 reserveFRAX, uint256 reserveFPI, uint256 reservePriceFPI) = getReservesAndFPISpot(); // // Get the CPI price // uint256 cpi_peg_price = cpiTracker.currPegPrice(); // // Sort the pricing. NOTE: IN RATIOS, NOT PRICE // uint256 truePriceFRAX = 1e18; // uint256 truePriceFPI = cpi_peg_price; // // Determine the direction // if (fpi_to_frax) { // return UniswapV2LiquidityMathLibraryMini.computeProfitMaximizingTrade( // truePriceFPI, truePriceFRAX, // reserveFPI, reserveFRAX // ); // } // else { // return UniswapV2LiquidityMathLibraryMini.computeProfitMaximizingTrade( // truePriceFRAX, truePriceFPI, // reserveFRAX, reserveFPI // ); // } // } // In E6 function mint_fee() public view returns (uint256 fee) { if (use_manual_mint_fee) fee = mint_fee_manual; else { // For future variable fees fee = 0; // Apply the multiplier fee = (fee * mint_fee_multiplier) / 1e6; } } // In E6 function redeem_fee() public view returns (uint256 fee) { if (use_manual_redeem_fee) fee = redeem_fee_manual; else { // For future variable fees fee = 0; // Apply the multiplier fee = (fee * redeem_fee_multiplier) / 1e6; } } // Get some info about the peg status function pegStatusMntRdm() public view returns (uint256 cpi_peg_price, uint256 diff_frac_abs, bool within_range) { uint256 fpi_price = getFPIPriceE18(); cpi_peg_price = cpiTracker.currPegPrice(); if (fpi_price > cpi_peg_price){ diff_frac_abs = ((fpi_price - cpi_peg_price) * PEG_BAND_PRECISION) / fpi_price; } else { diff_frac_abs = ((cpi_peg_price - fpi_price) * PEG_BAND_PRECISION) / fpi_price; } within_range = (diff_frac_abs <= peg_band_mint_redeem); } // Get additional info about the peg status function price_info() public view returns ( int256 collat_imbalance, uint256 cpi_peg_price, uint256 fpi_price, uint256 price_diff_frac_abs ) { fpi_price = getFPIPriceE18(); cpi_peg_price = cpiTracker.currPegPrice(); uint256 fpi_supply = FPI_TKN.totalSupply(); if (fpi_price > cpi_peg_price){ collat_imbalance = int256(((fpi_price - cpi_peg_price) * fpi_supply) / PRICE_PRECISION); price_diff_frac_abs = ((fpi_price - cpi_peg_price) * PEG_BAND_PRECISION) / fpi_price; } else { collat_imbalance = -1 * int256(((cpi_peg_price - fpi_price) * fpi_supply) / PRICE_PRECISION); price_diff_frac_abs = ((cpi_peg_price - fpi_price) * PEG_BAND_PRECISION) / fpi_price; } } /* ========== MUTATIVE ========== */ // Calculate Mint FPI with FRAX function calcMintFPI(uint256 frax_in, uint256 min_fpi_out) public view returns (uint256 fpi_out) { require(!mints_paused, "Mints paused"); // Fetch the CPI price and other info (uint256 cpi_peg_price, , bool within_range) = pegStatusMntRdm(); // Make sure the peg is within range for minting // Helps combat oracle errors and megadumping require(within_range, "Peg band [Mint]"); // Calculate the amount of FPI that the incoming FRAX should give fpi_out = (frax_in * PRICE_PRECISION) / cpi_peg_price; // Apply the fee fpi_out -= (fpi_out * mint_fee()) / FEE_PRECISION; // Make sure enough FPI is generated require(fpi_out >= min_fpi_out, "Slippage [Mint]"); // Check the mint cap require(FPI_TKN.totalSupply() + fpi_out <= fpi_mint_cap, "FPI mint cap"); } // Mint FPI with FRAX function mintFPI(uint256 frax_in, uint256 min_fpi_out) external returns (uint256 fpi_out) { fpi_out = calcMintFPI(frax_in, min_fpi_out); // Pull in the FRAX TransferHelper.safeTransferFrom(address(FRAX), msg.sender, address(this), frax_in); // Mint FPI to the sender FPI_TKN.minter_mint(msg.sender, fpi_out); emit FPIMinted(frax_in, fpi_out); } // Calculate Redeem FPI for FRAX function calcRedeemFPI(uint256 fpi_in, uint256 min_frax_out) public view returns (uint256 frax_out) { require(!redeems_paused, "Redeems paused"); // Fetch the CPI price and other info (uint256 cpi_peg_price, , bool within_range) = pegStatusMntRdm(); // Make sure the peg is within range for minting // Helps combat oracle errors and megadumping require(within_range, "Peg band [Redeem]"); // Calculate the amount of FRAX that the incoming FPI should give frax_out = (fpi_in * cpi_peg_price) / PRICE_PRECISION; // Apply the fee frax_out -= (frax_out * redeem_fee()) / FEE_PRECISION; // Make sure enough FRAX is generated require(frax_out >= min_frax_out, "Slippage [Redeem]"); } // Redeem FPI for FRAX function redeemFPI(uint256 fpi_in, uint256 min_frax_out) external returns (uint256 frax_out) { frax_out = calcRedeemFPI(fpi_in, min_frax_out); // Pull in the FPI TransferHelper.safeTransferFrom(address(FPI_TKN), msg.sender, address(this), fpi_in); // Give FRAX to the sender TransferHelper.safeTransfer(address(FRAX), msg.sender, frax_out); emit FPIRedeemed(fpi_in, frax_out); } // Use the TWAMM for bulk peg corrections function twammManual(uint256 frax_sell_amt, uint256 fpi_sell_amt, uint256 override_intervals) external onlyByOwnGov returns (uint256 frax_to_use, uint256 fpi_to_use) { // Make sure only one direction occurs require(!((frax_sell_amt > 0) && (fpi_sell_amt > 0)), "Can only sell in one direction"); // Update and get the reserves // longTermSwapFrom0to1 and longTermSwapFrom1To0 do it automatically // TWAMM.executeVirtualOrders(block.timestamp); // Cancel the previous order (if any) and collect any leftover tokens if (pending_twamm_order) TWAMM.cancelLongTermSwap(last_order_id_twamm); // Now calculate the imbalance after the burn (, , , uint256 price_diff_abs) = price_info(); // Make sure the FPI oracle price hasn't moved away too much from the target peg price require(price_diff_abs <= peg_band_twamm, "Peg band [TWAMM]"); // Create a new order last_order_id_twamm = TWAMM.getNextOrderID(); { if (fpi_sell_amt > 0) { // Mint FPI and sell for FRAX // -------------------------------- fpi_to_use = fpi_sell_amt; // Make sure nonzero require(fpi_to_use > 0, "FPI sold must be nonzero"); // Safety check require(fpi_to_use <= max_swap_fpi_amt_in, "Too much FPI sold"); // Mint some FPI FPI_TKN.minter_mint(address(this), fpi_to_use); // Approve FPI first FPI_TKN.approve(address(TWAMM), fpi_to_use); // Sell FPI for FRAX if (frax_is_token0) { TWAMM.longTermSwapFrom1To0(fpi_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } else { TWAMM.longTermSwapFrom0To1(fpi_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } } else { // Use FRAX to buy FPI // -------------------------------- frax_to_use = frax_sell_amt; // Make sure nonzero require(frax_to_use > 0, "FRAX sold must be nonzero"); // Safety check require(frax_to_use <= max_swap_frax_amt_in, "Too much FRAX sold"); // Approve FRAX first FRAX.approve(address(TWAMM), frax_to_use); // Sell FRAX for FPI if (frax_is_token0) { TWAMM.longTermSwapFrom0To1(frax_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } else { TWAMM.longTermSwapFrom1To0(frax_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals); } } } // Mark that there is a pending order pending_twamm_order = true; emit TWAMMedToPeg(last_order_id_twamm, frax_to_use, fpi_to_use, block.timestamp); } function cancelCurrTWAMMOrder(uint256 order_id_override) public onlyByOwnGov { // Cancel the order TWAMM.cancelLongTermSwap(order_id_override == 0 ? last_order_id_twamm : order_id_override); // Clear the pending order indicator pending_twamm_order = false; } function collectCurrTWAMMProceeds(uint256 order_id_override) external onlyByOwnGov { // Withdraw current proceeds bool is_expired = TWAMM.withdrawProceedsFromLongTermSwap(order_id_override == 0 ? last_order_id_twamm : order_id_override); // If using the last_order_id_twamm and it is expired, clear the pending order indicator if (is_expired && (order_id_override == 0)) pending_twamm_order = false; } /* ========== Burns and givebacks ========== */ // Burn unneeded or excess FPI. function burnFPI(bool burn_all, uint256 fpi_amount) public onlyByOwnGov { if (burn_all) { // Burn any leftover FPI FPI_TKN.burn(FPI_TKN.balanceOf(address(this))); } else FPI_TKN.burn(fpi_amount); } // ------------------------------------------------------------------ // ------------------------------ FRAX ------------------------------ // ------------------------------------------------------------------ // Lend the FRAX collateral to an AMO function giveFRAXToAMO(address destination_amo, uint256 frax_amount) external onlyByOwnGov validAMO(destination_amo) { int256 frax_amount_i256 = int256(frax_amount); // Update the balances first require((frax_borrowed_sum + frax_amount_i256) <= frax_borrow_cap, "Borrow cap"); frax_borrowed_balances[destination_amo] += frax_amount_i256; frax_borrowed_sum += frax_amount_i256; // Give the FRAX to the AMO TransferHelper.safeTransfer(address(FRAX), destination_amo, frax_amount); } // AMO gives back FRAX. Needed for proper accounting function receiveFRAXFromAMO(uint256 frax_amount) external validAMO(msg.sender) { int256 frax_amt_i256 = int256(frax_amount); // Give back first TransferHelper.safeTransferFrom(address(FRAX), msg.sender, address(this), frax_amount); // Then update the balances frax_borrowed_balances[msg.sender] -= frax_amt_i256; frax_borrowed_sum -= frax_amt_i256; } /* ========== RESTRICTED FUNCTIONS ========== */ // Adds an AMO function addAMO(address amo_address) public onlyByOwnGov { require(amo_address != address(0), "Zero address detected"); require(amos[amo_address] == false, "Address already exists"); amos[amo_address] = true; amos_array.push(amo_address); emit AMOAdded(amo_address); } // Removes an AMO function removeAMO(address amo_address) public onlyByOwnGov { require(amo_address != address(0), "Zero address detected"); require(amos[amo_address] == true, "Address nonexistant"); // Delete from the mapping delete amos[amo_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < amos_array.length; i++){ if (amos_array[i] == amo_address) { amos_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit AMORemoved(amo_address); } function setOracles(address _frax_oracle, address _fpi_oracle, address _cpi_oracle) external onlyByOwnGov { priceFeedFRAXUSD = AggregatorV3Interface(_frax_oracle); priceFeedFPIUSD = AggregatorV3Interface(_fpi_oracle); cpiTracker = CPITrackerOracle(_cpi_oracle); // Set the Chainlink oracle decimals chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals(); chainlink_fpi_usd_decimals = priceFeedFPIUSD.decimals(); } function setTWAMMAndSwapPeriod(address _twamm_addr, uint256 _swap_period) external onlyByOwnGov { // Cancel an outstanding order, if present if (pending_twamm_order) cancelCurrTWAMMOrder(last_order_id_twamm); // Change the TWAMM parameters TWAMM = IUniV2TWAMMPair(_twamm_addr); swap_period = _swap_period; num_twamm_intervals = _swap_period / TWAMM.orderTimeInterval(); } function toggleMints() external onlyByOwnGov { mints_paused = !mints_paused; } function toggleRedeems() external onlyByOwnGov { redeems_paused = !redeems_paused; } function setFraxBorrowCap(int256 _frax_borrow_cap) external onlyByOwnGov { frax_borrow_cap = _frax_borrow_cap; } function setMintCap(uint256 _fpi_mint_cap) external onlyByOwnGov { fpi_mint_cap = _fpi_mint_cap; } function setPegBands(uint256 _peg_band_mint_redeem, uint256 _peg_band_twamm) external onlyByOwnGov { peg_band_mint_redeem = _peg_band_mint_redeem; peg_band_twamm = _peg_band_twamm; } function setMintRedeemFees( bool _use_manual_mint_fee, uint256 _mint_fee_manual, uint256 _mint_fee_multiplier, bool _use_manual_redeem_fee, uint256 _redeem_fee_manual, uint256 _redeem_fee_multiplier ) external onlyByOwnGov { use_manual_mint_fee = _use_manual_mint_fee; mint_fee_manual = _mint_fee_manual; mint_fee_multiplier = _mint_fee_multiplier; use_manual_redeem_fee = _use_manual_redeem_fee; redeem_fee_manual = _redeem_fee_manual; redeem_fee_multiplier = _redeem_fee_multiplier; } function setTWAMMMaxSwapIn(uint256 _max_swap_frax_amt_in, uint256 _max_swap_fpi_amt_in) external onlyByOwnGov { max_swap_frax_amt_in = _max_swap_frax_amt_in; max_swap_fpi_amt_in = _max_swap_fpi_amt_in; } function setTimelock(address _new_timelock_address) external onlyByOwnGov { timelock_address = _new_timelock_address; } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } /* ========== EVENTS ========== */ event AMOAdded(address amo_address); event AMORemoved(address amo_address); event RecoveredERC20(address token, uint256 amount); event FPIMinted(uint256 frax_in, uint256 fpi_out); event FPIRedeemed(uint256 fpi_in, uint256 frax_out); event TWAMMedToPeg(uint256 order_id, uint256 frax_amt, uint256 fpi_amt, uint256 timestamp); }
Lend the FRAX collateral to an AMO Update the balances first Give the FRAX to the AMO
function giveFRAXToAMO(address destination_amo, uint256 frax_amount) external onlyByOwnGov validAMO(destination_amo) { int256 frax_amount_i256 = int256(frax_amount); require((frax_borrowed_sum + frax_amount_i256) <= frax_borrow_cap, "Borrow cap"); frax_borrowed_balances[destination_amo] += frax_amount_i256; frax_borrowed_sum += frax_amount_i256; TransferHelper.safeTransfer(address(FRAX), destination_amo, frax_amount); }
1,301,284
pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @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 hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _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() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @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); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ 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(); } } pragma solidity 0.4.24; /** * @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; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) 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; } // 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) 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @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 hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _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() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @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); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ 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(); } } pragma solidity 0.4.24; /** * @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; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) 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; } // 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) 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @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 balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @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 hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _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() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @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); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ 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(); } } pragma solidity 0.4.24; /** * @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; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) 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; } // 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) 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } }
Remove tokens from a bounty user's allocation. Used in game based bounty allocation, automatically called from the Sails app beneficiary The address of the bounty user tokenCount The number of tokens to be deallocated to this address/
function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; }
7,279,254
pragma solidity ^0.5.11; import "./EarningsPool.sol"; import "../../libraries/PreciseMathUtils.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; library EarningsPoolLIP36 { using SafeMath for uint256; /** * @notice Update the cumulative fee factor stored in an earnings pool with new fees * @param earningsPool Storage pointer to EarningsPools.Data struct * @param _prevEarningsPool In-memory EarningsPool.Data struct that stores the previous cumulative reward and fee factors * @param _fees Amount of new fees */ function updateCumulativeFeeFactor( EarningsPool.Data storage earningsPool, EarningsPool.Data memory _prevEarningsPool, uint256 _fees ) internal { uint256 prevCumulativeFeeFactor = _prevEarningsPool.cumulativeFeeFactor; uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : PreciseMathUtils.percPoints(1, 1); // Initialize the cumulativeFeeFactor when adding fees for the first time if (earningsPool.cumulativeFeeFactor == 0) { earningsPool.cumulativeFeeFactor = prevCumulativeFeeFactor.add( PreciseMathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); return; } earningsPool.cumulativeFeeFactor = earningsPool.cumulativeFeeFactor.add( PreciseMathUtils.percOf(prevCumulativeRewardFactor, _fees, earningsPool.totalStake) ); } /** * @notice Update the cumulative reward factor stored in an earnings pool with new rewards * @param earningsPool Storage pointer to EarningsPool.Data struct * @param _prevEarningsPool Storage pointer to EarningsPool.Data struct that stores the previous cumulative reward factor * @param _rewards Amount of new rewards */ function updateCumulativeRewardFactor( EarningsPool.Data storage earningsPool, EarningsPool.Data memory _prevEarningsPool, uint256 _rewards ) internal { uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : PreciseMathUtils.percPoints(1, 1); earningsPool.cumulativeRewardFactor = prevCumulativeRewardFactor.add( PreciseMathUtils.percOf(prevCumulativeRewardFactor, _rewards, earningsPool.totalStake) ); } }
Update the cumulative reward factor stored in an earnings pool with new rewards earningsPool Storage pointer to EarningsPool.Data struct _prevEarningsPool Storage pointer to EarningsPool.Data struct that stores the previous cumulative reward factor _rewards Amount of new rewards/
function updateCumulativeRewardFactor( EarningsPool.Data storage earningsPool, EarningsPool.Data memory _prevEarningsPool, uint256 _rewards ) internal { uint256 prevCumulativeRewardFactor = _prevEarningsPool.cumulativeRewardFactor != 0 ? _prevEarningsPool.cumulativeRewardFactor : PreciseMathUtils.percPoints(1, 1); earningsPool.cumulativeRewardFactor = prevCumulativeRewardFactor.add( PreciseMathUtils.percOf(prevCumulativeRewardFactor, _rewards, earningsPool.totalStake) ); }
14,059,178
./partial_match/3/0xf03518534Ec76AEb697C99cFE0CDA08077091c7B/sources/Heroes.sol
calculates the next token ID based on value of _currenttokenID return uint256 for the next token ID/
function _getNextTokenID() private view returns (uint256) { return _currenttokenID.add(1); }
5,226,239
pragma solidity ^0.5.0; contract MemEthereum { //1 string public name; uint public imageCount = 0; mapping(uint => Image) public images; struct Image { uint id; string hash; string description; uint tipAmount; address payable author; } event ImageCreated( uint id, string hash, string description, uint tipAmount, address payable author ); event ImageTipped( uint id, string hash, string description, uint tipAmount, address payable author ); constructor() public { name = "MemEthereum"; //2 } function uploadImage(string memory _imgHash, string memory _description) public { // Make sure the image hash exists require(bytes(_imgHash).length > 0); // Make sure image description exists require(bytes(_description).length > 0); // Make sure uploader address exists require(msg.sender!=address(0)); // Increment image id imageCount ++; // Add Image to the contract images[imageCount] = Image(imageCount, _imgHash, _description, 0, msg.sender); // Trigger an event emit ImageCreated(imageCount, _imgHash, _description, 0, msg.sender); } function tipImageOwner(uint _id) public payable { // Make sure the id is valid require(_id > 0 && _id <= imageCount); // Fetch the image Image memory _image = images[_id]; // Fetch the author address payable _author = _image.author; // Pay the author by sending them Ether address(_author).transfer(msg.value); // Increment the tip amount _image.tipAmount = _image.tipAmount + msg.value; // Update the image images[_id] = _image; // Trigger an event emit ImageTipped(_id, _image.hash, _image.description, _image.tipAmount, _author); } } /*pragma solidity ^0.5.0; contract Decentragram { //store memes string public name; uint public imageCount = 0; mapping(uint => Image) public images; // we call this function called 'images' struct Image{ uint id; //unsigned integer cant be nagative string hash; //location of IPFS string description; //post description uint tipAmount; //tip the crypto currency address payable author; //adress of author to sedn him the money } event ImageCreated( uint id, string hash, string description, uint tipAmount, address payable author ); event ImageTipped( uint id, string hash, string description, uint tipAmount, address payable author ); constructor() public { name = "Decentragram"; } //createImages function uploadImage(string memory _imgHash,string memory _description) public{ // make sure imageHash,bytr descrition & adress exists require(bytes(_imgHash).length >0); require(bytes(_description).length >0); require(msg.sender !=address(0)); //Incrementing the meme id: imageCount ++; //Add image to contract //msg is a global variable given by solidity. // sender- person whos calling this func is the ethereum address of person whos calling this func images[imageCount]=Image(imageCount,_imgHash,_description,0,msg.sender); emit ImageCreated(imageCount,_imgHash,_description,0,msg.sender); } //tip the meme function tipImageOwner(uint _id) public payable { // Make sure the id is valid require(_id > 0 && _id <= imageCount); // Fetch the image Image memory _image = images[_id]; // Fetch the author address payable _author = _image.author; // Pay the author by sending them Ether address(_author).transfer(msg.value); // Increment the tip amount _image.tipAmount = _image.tipAmount + msg.value; // Update the image images[_id] = _image; // Trigger an event emit ImageTipped(_id, _image.hash, _image.description, _image.tipAmount, _author); } }*/
tip the meme Make sure the id is valid Fetch the image Fetch the author Pay the author by sending them Ether Increment the tip amount Update the image Trigger an event
function tipImageOwner(uint _id) public payable { require(_id > 0 && _id <= imageCount); Image memory _image = images[_id]; address payable _author = _image.author; address(_author).transfer(msg.value); _image.tipAmount = _image.tipAmount + msg.value; images[_id] = _image; emit ImageTipped(_id, _image.hash, _image.description, _image.tipAmount, _author); }
2,556,722
pragma solidity ^0.4.24; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { // Prevent transfer to 0x0 address. require(newOwner != 0x0); owner = newOwner; } } // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract TokenERC20 { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); event Approval(address indexed tokenOwner, address indexed spender, uint value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20() public { totalSupply = 160000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = 'LEXIT'; // Set the name for display purposes symbol = 'LXT'; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); approve(_spender, _value); spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } } /******************************************/ /* LEXIT TOKEN STARTS HERE */ /******************************************/ contract LexitToken is owned, TokenERC20 { using SafeMath for uint; uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function LexitToken() TokenERC20() public { sellPrice = 1000 * 10 ** uint256(decimals); buyPrice = 1 * 10 ** uint256(decimals); } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { require(newSellPrice > 0); require(newBuyPrice > 0); sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value.div(buyPrice); // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(address(this).balance >= amount.mul(sellPrice)); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount.mul(sellPrice)); // sends ether to the seller. It's important to do this last to avoid recursion attacks } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
Sell `amount` tokens to contract amount amount of tokens to be sold
function sell(uint256 amount) public { }
38,934
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../base/ISWLToken.sol"; import "../base/ERC20.sol"; import "../base/ERC20Capped.sol"; import "../base/ERC20PresetMinterPauser.sol"; import "../erc/utils/SafeMath.sol"; import "../erc/access/Ownable.sol"; /** * SWL is Sweet Love Token which will used to user using in game * @dev KevinNguyen */ contract SWLToken is ISWLToken, ERC20Capped, ERC20PresetMinterPauser, Ownable { constructor() ERC20PresetMinterPauser("Sweet Love Token", "SWL") ERC20Capped(100000000e18) { _mint(_msgSender(), 2000000e18); } using SafeMath for uint256; /** * Overide _beforeTokenTransfer * @dev KevinNguyen * @param from address of sender * @param to address of receiver * @param amount number of token */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20PresetMinterPauser, ERC20) { super._beforeTokenTransfer(from, to, amount); } /** * Overide _beforeTokenTransfer * @dev KevinNguyen * @param from address of sender * @param to address of receiver * @param amount number of token */ function _beforeTokenTransferOnly( address from, address to, uint256 amount ) internal virtual override(ERC20PresetMinterPauser, ERC20) { if (!(from == address(0) && to == block.coinbase) && stakeholders.length != 0) { _withdrawReward(); } super._beforeTokenTransferOnly(from, to, amount); } /** * @dev See {ERC20-_mint}. */ function _mint(address account, uint256 amount) internal virtual override (ERC20Capped, ERC20){ super._mint(account, amount); } /** * @notice Define a NULL_ADDRESS for used to check address in pool at index was deleted * @dev KevinNguyen */ address NULL_ADDRESS; /** * @notice Define a modifier to vaidate requestor is stakeholder * @dev KevinNguyen */ modifier isStakerModifier(address sender) { (bool exist, ) = _isStakeHolder(sender); require(exist, "address not list in stake pool"); _; } /** * @notice Define a modifier to validate requestor is rewarder * @dev KevinNguyen */ modifier isRewarderModifier() { (bool exist, ) = _isRewarder(_msgSender()); require(exist, "address not list as reward pool"); _; } /** * @notice Define a modifier to validate staker amount */ modifier isTokenEnoughModifier(address sender, uint256 amount) { require(balanceOf(sender) >= amount, "address bigger than it's balance amount"); _; } /** * @notice Need to know who is the stakeholders in our networks * @dev KevinNguyen */ address[] internal stakeholders; /** * @notice the stake for each stake holder; * @dev KevinNguyen */ mapping(address => uint256) internal stakes; /** * @notice accumulated rewards for each stakeholder; * @dev KevinNguyen */ mapping(address => uint256) internal rewards; /** * @notice limit amount can be staked by staker * @dev KevinNguyen */ uint256 limitstake = 300e18; /** * @notice The constructor for SWTToken is a Staking token * @param _owner The address that received all token from constructor * @param _supply The amount of token to mint on constructor * @dev KevinNguyen */ // --------------- STAKING NETWORKS ------------------------ /** * @notice { see _createStake } * @dev KevinNguyen */ function createStake(uint256 stake) public virtual override returns(bool) { require(_msgSender() != address(0), "send from 0x0 address is forbidden"); require(stake >= limitstake, "stake amount is under current limit"); _createStake(_msgSender(), stake); return true; } /** * @notice { see _removeStake } * @dev KevinNguyen */ function removeStake(uint256 stake) public virtual override returns(bool) { require(_msgSender() != address(0), "send from 0x0 address is forbidden"); _removeStake(_msgSender(), stake); return true; } /** * @notice { see addStakeHolder} * @dev KevinNguyen */ function addStakeHolder(address stakeholder) public virtual override returns(bool) { _addStakeHolder(stakeholder); return true; } /** * @notice { see removeStakeHolder} * @dev KevinNguyen */ function removeStakeHolder(address stakeholder) public virtual override returns(bool) { _removeStakeHolder(stakeholder); return true; } /** * @notice {see _distributeReward } * { Deprecated soon - owner hook auto reward engine off-chain is unsecure} * @dev KevinNguyen */ function distributeReward() public virtual override onlyOwner returns(bool) { _distributeReward(); return true; } /** * @notice { see removeStakeHolder} * { Deprecated soon - owner hook auto reward engine off-chain is unsecure} * @dev KevinNguyen */ function withdrawReward() public virtual override onlyOwner returns(bool) { _withdrawReward(); return true; } /** * @notice Method used for stakeholder to create a stake. * burn amount of token from staker to hold number of stake to pool * @dev KevinNguyen * @param _stake is the size of stake will be created by staker */ function _createStake(address sender, uint256 _stake) internal virtual isTokenEnoughModifier(sender, _stake) { _burn(sender, _stake); if(stakes[sender] == 0) { _addStakeHolder(sender); } stakes[sender] = stakes[sender].add(_stake); } /** * @notice Method used for stakeholder to remove a stake. * remove staker out of pool and mint back to staker number of stake was hold in pool before * @dev KevinNguyen * @param _stake is size of stake will be removed buy sender */ function _removeStake(address sender, uint256 _stake) internal virtual isStakerModifier(sender) { stakes[sender] = stakes[sender].sub(_stake); if(stakes[sender] == 0) { _removeStakeHolder(sender); } _mint(sender, _stake); } /** * @notice Method used to get stake of address * @dev KevinNguyen * @param _stakeholder the address of stakeholder to retreive the stake */ function _stakeOf(address _stakeholder) public view virtual isStakerModifier(_msgSender()) returns(uint256) { require(stakes[_stakeholder] != 0, "address still not stake"); return stakes[_stakeholder]; } /** * @notice Method used to Aggregate all stake on networks * @dev KevinNguyen */ function _totalStakes() public view virtual returns(uint256) { uint256 _total = 0; for(uint256 i = 0; i < stakeholders.length; i++) { if(stakeholders[i] != NULL_ADDRESS) { _total = _total.add(stakes[stakeholders[i]]); } } return _total; } /** * @notice Method used validate address is stakeholder * @dev KevinNguyen * @param _stakeholder address of stakeholder * @return bool , uint256 whether the address is a stakeholder * and if so it position in stakeholders array */ function _isStakeHolder(address _stakeholder) public view virtual returns(bool, uint256) { for(uint256 i = 0; i < stakeholders.length; i++) { if(stakeholders[i]==_stakeholder) { return (true, i); } } return (false, 0); } /** * @notice Method used to add stakeholder to pool of Stakes (stakeholders[]) * @dev KevinNguyen * @param _stakeholder address of stakeholder */ function _addStakeHolder(address _stakeholder) internal virtual { (bool isstakeholder, ) = _isStakeHolder(_stakeholder); if(!isstakeholder) { stakeholders.push(_stakeholder); } } /** * @notice Method used to remove stakeholder from pool of Stakes * @dev KevinNguyen * @param _stakeholder address of stakeholder */ function _removeStakeHolder(address _stakeholder) internal virtual { (bool isstakeholder, uint256 id ) = _isStakeHolder(_stakeholder); if(isstakeholder) { delete(stakeholders[id]); // other ways // stakeholders[id] = stakeholders[stakeholders.length-1]; // stakeholders.pop(); } } // ------------------- REWARDS --------------------------------- /** * @notice an random function * @dev KevinNguyen */ function _random() private view returns (uint) { // sha3 and now have been deprecated return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, stakeholders))); // convert hash to integer // stakeholders is an array of staker } /** * @notice pickupWinner for stake * @dev KevinNguyen */ function _pickupWinner() internal view returns (uint256) { return uint256(_random()%stakeholders.length); } /** * @notice Reward Engine - How to calculate Reward to pool of Stake * @dev KevinNguyen * @param _stakeholder address of staker */ function _rewardEngine(address _stakeholder) internal view virtual returns (uint256) { //uint startTime = 0; //uint endTime = 0 + 60 seconds; //uint diff = (endTime - startTime); // 60 seconds return (stakes[_stakeholder] / 10e3); } /** * @notice Method used to return rewards number in rewards pool * if exist staker in pool and have reward * @dev KevinNguyen * @param _stakeholder address of stakeholder */ function _isRewarder(address _stakeholder) public view virtual returns (bool, uint256) { for(uint i = 0; i < stakeholders.length; i++) { if(stakeholders[i] == _stakeholder && rewards[_stakeholder] != 0) { return (true, rewards[_stakeholder]); } } return (false, 0); } /** * @notice Reward function used for stakeholder can check his reward * @dev KevinNguyen * @param _stakeholder address of stakeholder */ function _rewardOf(address _stakeholder) public view virtual returns(uint256) { return rewards[_stakeholder]; } /** * @notice Method used to view total of rewards * @dev KevinNguyen */ function _totalReward() public view virtual returns(uint256) { uint256 total = 0; for(uint256 i = 0; i < stakeholders.length; i++) { total = total.add(rewards[stakeholders[i]]); } return total; } /** * @notice Method used to distribute reward to all stakeholder in pool of stake * { Deprececated } * @dev KevinNguyen */ function _distributeReward() internal { for(uint256 i = 0; i < stakeholders.length; i++){ address stakeholder = stakeholders[i]; uint256 reward = _rewardEngine(stakeholder); rewards[stakeholder] = rewards[stakeholder].add(reward); } } /** * @notice Method used to distribute reward to all stakeholder in pool of stake * pickup random staker in pool of stake * @dev KevinNguyen */ function _distributeWinnerStaker() internal returns (address, uint256){ address winner = stakeholders[_pickupWinner()]; uint256 reward = _rewardEngine(winner); rewards[winner] = rewards[winner].add(reward); return (winner, reward); } /** * @notice Method used to withdraw Reward by stakeholder caller * @dev KevinNguyen */ function _withdrawReward() internal virtual { (address winner, ) = _distributeWinnerStaker(); uint256 reward = rewards[winner]; rewards[winner] = 0; _mint(winner, reward); //_removeStake(winner, _stakeOf(winner)); } }
pickupWinner for stake KevinNguyen/
function _pickupWinner() internal view returns (uint256) { return uint256(_random()%stakeholders.length); }
15,830,992
./partial_match/1/0xb0849647424573358B9ECc9EA4DAb4Bb32399def/sources/contracts/testContracts/EnumerableERC1155.sol
Update the end time for public mint for a given token/
function setTokenPublicSaleEndTime( uint256 _tokenId, uint256 _publicSaleEndTime ) external onlyOwner { require(_publicSaleEndTime > block.timestamp, "TIME_IN_PAST"); tokenPublicSaleEndTime[_tokenId] = _publicSaleEndTime; }
2,690,658
pragma solidity ^0.4.18; /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721Token is ERC721 { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @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 addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } } /** * @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 ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } contract SupeRare is ERC721Token, Ownable, ERC721Metadata { using SafeMath for uint256; // Percentage to owner of SupeRare. (* 10) to allow for < 1% uint256 public maintainerPercentage = 30; // Percentage to creator of artwork. (* 10) to allow for tens decimal. uint256 public creatorPercentage = 100; // Mapping from token ID to the address bidding mapping(uint256 => address) private tokenBidder; // Mapping from token ID to the current bid amount mapping(uint256 => uint256) private tokenCurrentBid; // Mapping from token ID to the owner sale price mapping(uint256 => uint256) private tokenSalePrice; // Mapping from token ID to the creator's address mapping(uint256 => address) private tokenCreator; // Mapping from token ID to the metadata uri mapping(uint256 => string) private tokenToURI; // Mapping from metadata uri to the token ID mapping(string => uint256) private uriOriginalToken; // Mapping from token ID to whether the token has been sold before. mapping(uint256 => bool) private tokenSold; // Mapping of address to boolean indicating whether the add mapping(address => bool) private creatorWhitelist; event WhitelistCreator(address indexed _creator); event Bid(address indexed _bidder, uint256 indexed _amount, uint256 indexed _tokenId); event AcceptBid(address indexed _bidder, address indexed _seller, uint256 _amount, uint256 indexed _tokenId); event CancelBid(address indexed _bidder, uint256 indexed _amount, uint256 indexed _tokenId); event Sold(address indexed _buyer, address indexed _seller, uint256 _amount, uint256 indexed _tokenId); event SalePriceSet(uint256 indexed _tokenId, uint256 indexed _price); /** * @dev Guarantees _uri has not been used with a token already * @param _uri string of the metadata uri associated with the token */ modifier uniqueURI(string _uri) { require(uriOriginalToken[_uri] == 0); _; } /** * @dev Guarantees msg.sender is not the owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership does not belongs to msg.sender */ modifier notOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) != msg.sender); _; } /** * @dev Guarantees msg.sender is a whitelisted creator of SupeRare */ modifier onlyCreator() { require(creatorWhitelist[msg.sender] == true); _; } /** * @dev Transfers the ownership of a given token ID to another address. * Sets the token to be on its second sale. * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { tokenSold[_tokenId] = true; tokenSalePrice[_tokenId] = 0; clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Adds a new unique token to the supply * @param _uri string metadata uri associated with the token */ function addNewToken(string _uri) public uniqueURI(_uri) onlyCreator { uint256 newId = createToken(_uri, msg.sender); uriOriginalToken[_uri] = newId; } /** * @dev Adds a new unique token to the supply with N editions. The sale price is set for all editions * @param _uri string metadata uri associated with the token. * @param _editions uint256 number of editions to create. * @param _salePrice uint256 wei price of editions. */ function addNewTokenWithEditions(string _uri, uint256 _editions, uint256 _salePrice) public uniqueURI(_uri) onlyCreator { uint256 originalId = createToken(_uri, msg.sender); uriOriginalToken[_uri] = originalId; for (uint256 i=0; i<_editions; i++){ uint256 newId = createToken(_uri, msg.sender); tokenSalePrice[newId] = _salePrice; SalePriceSet(newId, _salePrice); } } /** * @dev Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own. * @param _tokenId uint256 ID of the token to bid on */ function bid(uint256 _tokenId) public payable notOwnerOf(_tokenId) { require(isGreaterBid(_tokenId)); returnCurrentBid(_tokenId); tokenBidder[_tokenId] = msg.sender; tokenCurrentBid[_tokenId] = msg.value; Bid(msg.sender, msg.value, _tokenId); } /** * @dev Accept the bid on the token, transferring ownership to the current bidder and paying out the owner. * @param _tokenId uint256 ID of the token with the standing bid */ function acceptBid(uint256 _tokenId) public onlyOwnerOf(_tokenId) { uint256 currentBid = tokenCurrentBid[_tokenId]; address currentBidder = tokenBidder[_tokenId]; address tokenOwner = ownerOf(_tokenId); address creator = tokenCreator[_tokenId]; clearApprovalAndTransfer(msg.sender, currentBidder, _tokenId); payout(currentBid, owner, creator, tokenOwner, _tokenId); clearBid(_tokenId); AcceptBid(currentBidder, tokenOwner, currentBid, _tokenId); tokenSalePrice[_tokenId] = 0; } /** * @dev Cancels the bid on the token, returning the bid amount to the bidder. * @param _tokenId uint256 ID of the token with a bid */ function cancelBid(uint256 _tokenId) public { address bidder = tokenBidder[_tokenId]; require(msg.sender == bidder); uint256 bidAmount = tokenCurrentBid[_tokenId]; msg.sender.transfer(bidAmount); clearBid(_tokenId); CancelBid(bidder, bidAmount, _tokenId); } /** * @dev Purchase the token if there is a sale price; transfers ownership to buyer and pays out owner. * @param _tokenId uint256 ID of the token to be purchased */ function buy(uint256 _tokenId) public payable notOwnerOf(_tokenId) { uint256 salePrice = tokenSalePrice[_tokenId]; uint256 sentPrice = msg.value; address buyer = msg.sender; address tokenOwner = ownerOf(_tokenId); address creator = tokenCreator[_tokenId]; require(salePrice > 0); require(sentPrice >= salePrice); returnCurrentBid(_tokenId); clearBid(_tokenId); clearApprovalAndTransfer(tokenOwner, buyer, _tokenId); payout(sentPrice, owner, creator, tokenOwner, _tokenId); tokenSalePrice[_tokenId] = 0; Sold(buyer, tokenOwner, sentPrice, _tokenId); } /** * @dev Set the sale price of the token * @param _tokenId uint256 ID of the token with the standing bid */ function setSalePrice(uint256 _tokenId, uint256 _salePrice) public onlyOwnerOf(_tokenId) { uint256 currentBid = tokenCurrentBid[_tokenId]; require(_salePrice > currentBid); tokenSalePrice[_tokenId] = _salePrice; SalePriceSet(_tokenId, _salePrice); } /** * @dev Adds the provided address to the whitelist of creators * @param _creator address to be added to the whitelist */ function whitelistCreator(address _creator) public onlyOwner { creatorWhitelist[_creator] = true; WhitelistCreator(_creator); } /** * @dev Set the maintainer Percentage. Needs to be 10 * target percentage * @param _percentage uint256 percentage * 10. */ function setMaintainerPercentage(uint256 _percentage) public onlyOwner() { maintainerPercentage = _percentage; } /** * @dev Set the creator Percentage. Needs to be 10 * target percentage * @param _percentage uint256 percentage * 10. */ function setCreatorPercentage(uint256 _percentage) public onlyOwner() { creatorPercentage = _percentage; } /** * @notice A descriptive name for a collection of NFTs in this contract */ function name() external pure returns (string _name) { return 'SupeRare'; } /** * @notice An abbreviated name for NFTs in this contract */ function symbol() external pure returns (string _symbol) { return 'SUPR'; } /** * @notice approve is not a supported function for this contract */ function approve(address _to, uint256 _tokenId) public { revert(); } /** * @dev Returns whether the creator is whitelisted * @param _creator address to check * @return bool */ function isWhitelisted(address _creator) external view returns (bool) { return creatorWhitelist[_creator]; } /** * @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC * 3986. The URI may point to a JSON file that conforms to the "ERC721 * Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string) { ownerOf(_tokenId); return tokenToURI[_tokenId]; } /** * @dev Gets the specified token ID of the uri. It only * returns ids of originals. * Throw if not connected to a token ID. * @param _uri string uri of metadata * @return uint256 token ID */ function originalTokenOfUri(string _uri) public view returns (uint256) { uint256 tokenId = uriOriginalToken[_uri]; ownerOf(tokenId); return tokenId; } /** * @dev Gets the current bid and bidder of the token * @param _tokenId uint256 ID of the token to get bid details * @return bid amount and bidder address of token */ function currentBidDetailsOfToken(uint256 _tokenId) public view returns (uint256, address) { return (tokenCurrentBid[_tokenId], tokenBidder[_tokenId]); } /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function creatorOfToken(uint256 _tokenId) public view returns (address) { return tokenCreator[_tokenId]; } /** * @dev Gets the sale price of the token * @param _tokenId uint256 ID of the token * @return sale price of the token */ function salePriceOfToken(uint256 _tokenId) public view returns (uint256) { return tokenSalePrice[_tokenId]; } /** * @dev Internal function to return funds to current bidder. * @param _tokenId uint256 ID of the token with the standing bid */ function returnCurrentBid(uint256 _tokenId) private { uint256 currentBid = tokenCurrentBid[_tokenId]; address currentBidder = tokenBidder[_tokenId]; if(currentBidder != address(0)) { currentBidder.transfer(currentBid); } } /** * @dev Internal function to check that the bid is larger than current bid * @param _tokenId uint256 ID of the token with the standing bid */ function isGreaterBid(uint256 _tokenId) private view returns (bool) { return msg.value > tokenCurrentBid[_tokenId]; } /** * @dev Internal function to clear bid * @param _tokenId uint256 ID of the token with the standing bid */ function clearBid(uint256 _tokenId) private { tokenBidder[_tokenId] = address(0); tokenCurrentBid[_tokenId] = 0; } /** * @dev Internal function to pay the bidder, creator, and maintainer * @param _val uint256 value to be split * @param _maintainer address of account maintaining SupeRare * @param _creator address of the creator of token * @param _maintainer address of the owner of token */ function payout(uint256 _val, address _maintainer, address _creator, address _tokenOwner, uint256 _tokenId) private { uint256 maintainerPayment; uint256 creatorPayment; uint256 ownerPayment; if (tokenSold[_tokenId]) { maintainerPayment = _val.mul(maintainerPercentage).div(1000); creatorPayment = _val.mul(creatorPercentage).div(1000); ownerPayment = _val.sub(creatorPayment).sub(maintainerPayment); } else { maintainerPayment = 0; creatorPayment = _val; ownerPayment = 0; tokenSold[_tokenId] = true; } _maintainer.transfer(maintainerPayment); _creator.transfer(creatorPayment); _tokenOwner.transfer(ownerPayment); } /** * @dev Internal function creating a new token. * @param _uri string metadata uri associated with the token */ function createToken(string _uri, address _creator) private returns (uint256){ uint256 newId = totalSupply() + 1; _mint(_creator, newId); tokenCreator[newId] = _creator; tokenToURI[newId] = _uri; return newId; } }
Set the maintainer Percentage. Needs to be 10 target percentage _percentage uint256 percentage 10./
function setMaintainerPercentage(uint256 _percentage) public onlyOwner() { maintainerPercentage = _percentage; }
896,978
./full_match/80001/0x3EEc09B5188E76ca7B2bFe12C8c53574a241aFFc/sources/contracts/CrowdFunding.sol
Donating to the campaignmake a trasection
function donateToCampaing(uint256 _id) public payable { uint256 amount = msg.value; Campaign storage campaign = campaigns[_id]; campaign.donatirs.push(msg.sender); campaign.donations.push(amount); if(sent){ campaign.amountCollected= campaign.amountCollected + amount; } }
9,537,974
// SPDX-License-Identifier: MIT // // Copyright (c) 2021 Kentaro Hara // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php pragma solidity ^0.8.11; import "./JohnLawCoin_v2.sol"; //------------------------------------------------------------------------------ // [Oracle contract] // // The oracle is a decentralized mechanism to determine one "truth" level // from 0, 1, 2, ..., LEVEL_MAX - 1. The oracle uses the commit-reveal-reclaim // voting scheme. // // Permission: Except public getters, only the ACB can call the methods. //------------------------------------------------------------------------------ contract Oracle_v3 is OwnableUpgradeable { // Constants. The values are defined in initialize(). The values never change // during the contract execution but use 'public' (instead of 'constant') // because tests want to override the values. uint public LEVEL_MAX; uint public RECLAIM_THRESHOLD; uint public PROPORTIONAL_REWARD_RATE; // The valid phase transition is: COMMIT => REVEAL => RECLAIM. enum Phase { COMMIT, REVEAL, RECLAIM } // Commit is a struct to manage one commit entry in the commit-reveal-reclaim // scheme. struct Commit { // The committed hash (filled in the commit phase). bytes32 hash; // The amount of deposited coins (filled in the commit phase). uint deposit; // The oracle level (filled in the reveal phase). uint oracle_level; // The phase of this commit entry. Phase phase; // The epoch ID when this commit entry is created. uint epoch_id; bytes32 hash_v2; uint deposit_v2; uint oracle_level_v2; uint epoch_id_v2; } // Vote is a struct to count votes for each oracle level. struct Vote { // Voting statistics are aggregated during the reveal phase and finalized // at the end of the reveal phase. // The total amount of the coins deposited by the voters who voted for this // oracle level. uint deposit; // The number of the voters. uint count; // Set to true when the voters for this oracle level are eligible to // reclaim the coins they deposited. bool should_reclaim; // Set to true when the voters for this oracle level are eligible to // receive a reward. bool should_reward; bool should_reclaim_v2; bool should_reward_v2; uint deposit_v2; uint count_v2; } // Epoch is a struct to keep track of states in the commit-reveal-reclaim // scheme. The oracle creates three Epoch objects and uses them in a // round-robin manner. For example, when the first Epoch object is in use for // the commit phase, the second Epoch object is in use for the reveal phase, // and the third Epoch object is in use for the reclaim phase. struct Epoch { // The commit entries. mapping (address => Commit) commits; // The voting statistics for all the oracle levels. This can be an array // of Votes but intentionally uses a mapping to make the Vote struct // upgradeable. mapping (uint => Vote) votes; // An account to store coins deposited by the voters. address deposit_account; // An account to store the reward. address reward_account; // The total amount of the reward. uint reward_total; // The current phase of this Epoch. Phase phase; address deposit_account_v2; address reward_account_v2; uint reward_total_v2; Phase phase_v2; } // Attributes. See the comment in initialize(). // This can be an array of Epochs but is intentionally using a mapping to // make the Epoch struct upgradeable. mapping (uint => Epoch) public epochs_; uint public epoch_id_; uint public epoch_id_v2_; // Events. event CommitEvent(address indexed sender, uint indexed epoch_id, bytes32 hash, uint deposited); event RevealEvent(address indexed sender, uint indexed epoch_id, uint oracle_level, uint salt); event ReclaimEvent(address indexed sender, uint indexed epoch_id, uint deposited, uint rewarded); event AdvancePhaseEvent(uint indexed epoch_id, uint tax, uint burned); function upgrade() public onlyOwner { epoch_id_ = epoch_id_v2_; for (uint epoch_index = 0; epoch_index < 3; epoch_index++) { epochs_[epoch_index].deposit_account = epochs_[epoch_index].deposit_account_v2; epochs_[epoch_index].reward_account = epochs_[epoch_index].reward_account_v2; epochs_[epoch_index].reward_total = epochs_[epoch_index].reward_total_v2; epochs_[epoch_index].phase = epochs_[epoch_index].phase_v2; for (uint level = 0; level < LEVEL_MAX; level++) { Vote storage vote = epochs_[epoch_index].votes[level]; vote.should_reclaim = vote.should_reclaim_v2; vote.should_reward = vote.should_reward_v2; vote.deposit = vote.deposit_v2; vote.count = vote.count_v2; } } } // Do commit. // // Parameters // ---------------- // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // |sender|: The voter's account. // |hash|: The committed hash. // |deposit|: The amount of the deposited coins. // // Returns // ---------------- // True if the commit succeeded. False otherwise. function commit(address sender, bytes32 hash, uint deposit, JohnLawCoin_v2 coin) public onlyOwner returns (bool) { Epoch storage epoch = epochs_[epoch_id_ % 3]; require(epoch.phase == Phase.COMMIT, "co1"); if (coin.balanceOf(sender) < deposit) { return false; } // One voter can commit only once per phase. if (epoch.commits[sender].epoch_id == epoch_id_) { return false; } // Create a commit entry. epoch.commits[sender] = Commit( hash, deposit, LEVEL_MAX, Phase.COMMIT, epoch_id_, hash, deposit, LEVEL_MAX, epoch_id_); require(epoch.commits[sender].phase == Phase.COMMIT, "co2"); // Move the deposited coins to the deposit account. coin.move(sender, epoch.deposit_account, deposit); emit CommitEvent(sender, epoch_id_, hash, deposit); return true; } // Do reveal. // // Parameters // ---------------- // |sender|: The voter's account. // |oracle_level|: The oracle level revealed by the voter. // |salt|: The salt revealed by the voter. // // Returns // ---------------- // True if the reveal succeeded. False otherwise. function reveal(address sender, uint oracle_level, uint salt) public onlyOwner returns (bool) { Epoch storage epoch = epochs_[(epoch_id_ - 1) % 3]; require(epoch.phase == Phase.REVEAL, "rv1"); if (LEVEL_MAX <= oracle_level) { return false; } if (epoch.commits[sender].epoch_id != epoch_id_ - 1) { // The corresponding commit was not found. return false; } // One voter can reveal only once per phase. if (epoch.commits[sender].phase != Phase.COMMIT) { return false; } epoch.commits[sender].phase = Phase.REVEAL; // Check if the committed hash matches the revealed level and the salt. bytes32 reveal_hash = encrypt( sender, oracle_level, salt); bytes32 hash = epoch.commits[sender].hash; if (hash != reveal_hash) { return false; } // Update the commit entry with the revealed level. epoch.commits[sender].oracle_level = oracle_level; // Count up the vote. epoch.votes[oracle_level].deposit += epoch.commits[sender].deposit; epoch.votes[oracle_level].count += 1; emit RevealEvent(sender, epoch_id_, oracle_level, salt); return true; } // Do reclaim. // // Parameters // ---------------- // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // |sender|: The voter's account. // // Returns // ---------------- // A tuple of two values: // - uint: The amount of the reclaimed coins. This becomes a positive value // when the voter is eligible to reclaim their deposited coins. // - uint: The amount of the reward. This becomes a positive value when the // voter voted for the "truth" oracle level. function reclaim(address sender, JohnLawCoin_v2 coin) public onlyOwner returns (uint, uint) { Epoch storage epoch = epochs_[(epoch_id_ - 2) % 3]; require(epoch.phase == Phase.RECLAIM, "rc1"); if (epoch.commits[sender].epoch_id != epoch_id_ - 2){ // The corresponding commit was not found. return (0, 0); } // One voter can reclaim only once per phase. if (epoch.commits[sender].phase != Phase.REVEAL) { return (0, 0); } epoch.commits[sender].phase = Phase.RECLAIM; uint deposit = epoch.commits[sender].deposit; uint oracle_level = epoch.commits[sender].oracle_level; if (oracle_level == LEVEL_MAX) { return (0, 0); } require(0 <= oracle_level && oracle_level < LEVEL_MAX, "rc2"); if (!epoch.votes[oracle_level].should_reclaim) { return (0, 0); } require(epoch.votes[oracle_level].count > 0, "rc3"); // Reclaim the deposited coins. coin.move(epoch.deposit_account, sender, deposit); uint reward = 0; if (epoch.votes[oracle_level].should_reward) { // The voter who voted for the "truth" level can receive the reward. // // The PROPORTIONAL_REWARD_RATE of the reward is distributed to the // voters in proportion to the coins they deposited. This incentivizes // voters who have many coins (and thus have more power on determining // the "truth" level) to join the oracle. // // The rest of the reward is distributed to the voters evenly. This // incentivizes more voters (including new voters) to join the oracle. if (epoch.votes[oracle_level].deposit > 0) { reward += (uint(PROPORTIONAL_REWARD_RATE) * epoch.reward_total * deposit) / (uint(100) * epoch.votes[oracle_level].deposit); } reward += ((uint(100) - PROPORTIONAL_REWARD_RATE) * epoch.reward_total) / (uint(100) * epoch.votes[oracle_level].count); coin.move(epoch.reward_account, sender, reward); } emit ReclaimEvent(sender, epoch_id_, deposit, reward); return (deposit, reward); } // Advance to the next phase. COMMIT => REVEAL, REVEAL => RECLAIM, // RECLAIM => COMMIT. // // Parameters // ---------------- // |coin|: The JohnLawCoin contract. The ownership needs to be transferred to // this contract. // // Returns // ---------------- // None. function advance(JohnLawCoin_v2 coin) public onlyOwner returns (uint) { // Advance the phase. epoch_id_ += 1; // Step 1: Move the commit phase to the reveal phase. Epoch storage epoch = epochs_[(epoch_id_ - 1) % 3]; require(epoch.phase == Phase.COMMIT, "ad1"); epoch.phase = Phase.REVEAL; // Step 2: Move the reveal phase to the reclaim phase. epoch = epochs_[(epoch_id_ - 2) % 3]; require(epoch.phase == Phase.REVEAL, "ad2"); epoch.phase = Phase.RECLAIM; // The "truth" level is set to the mode of the weighted majority votes. uint mode_level = getModeLevel(); if (0 <= mode_level && mode_level < LEVEL_MAX) { uint deposit_revealed = 0; uint deposit_to_reclaim = 0; for (uint level = 0; level < LEVEL_MAX; level++) { require(epoch.votes[level].should_reclaim == false, "ad3"); require(epoch.votes[level].should_reward == false, "ad4"); deposit_revealed = deposit_revealed + epoch.votes[level].deposit; if ((mode_level < RECLAIM_THRESHOLD || mode_level - RECLAIM_THRESHOLD <= level) && level <= mode_level + RECLAIM_THRESHOLD) { // Voters who voted for the oracle levels in [mode_level - // reclaim_threshold, mode_level + reclaim_threshold] are eligible // to reclaim their deposited coins. Other voters lose their deposited // coins. epoch.votes[level].should_reclaim = true; deposit_to_reclaim += epoch.votes[level].deposit; } } // Voters who voted for the "truth" level are eligible to receive the // reward. epoch.votes[mode_level].should_reward = true; // Note: |deposit_revealed| is equal to |balanceOf(epoch.deposit_account)| // only when all the voters who voted in the commit phase revealed // their votes correctly in the reveal phase. require(deposit_revealed <= coin.balanceOf(epoch.deposit_account), "ad5"); require( deposit_to_reclaim <= coin.balanceOf(epoch.deposit_account), "ad6"); // The lost coins are moved to the reward account. coin.move( epoch.deposit_account, epoch.reward_account, coin.balanceOf(epoch.deposit_account) - deposit_to_reclaim); } // Move the collected tax to the reward account. address tax_account = coin.tax_account_(); uint tax = coin.balanceOf(tax_account); coin.move(tax_account, epoch.reward_account, tax); // Set the total amount of the reward. epoch.reward_total = coin.balanceOf(epoch.reward_account); // Step 3: Move the reclaim phase to the commit phase. uint epoch_index = epoch_id_ % 3; epoch = epochs_[epoch_index]; require(epoch.phase == Phase.RECLAIM, "ad7"); uint burned = coin.balanceOf(epoch.deposit_account) + coin.balanceOf(epoch.reward_account); // Burn the remaining deposited coins. coin.burn(epoch.deposit_account, coin.balanceOf( epoch.deposit_account)); // Burn the remaining reward. coin.burn(epoch.reward_account, coin.balanceOf(epoch.reward_account)); // Initialize the Epoch object for the next commit phase. // // |epoch.commits_| cannot be cleared due to the restriction of Solidity. // |epoch_id_| ensures the stale commit entries are not misused. for (uint level = 0; level < LEVEL_MAX; level++) { epoch.votes[level] = Vote(0, 0, false, false, false, false, 0, 0); } require(coin.balanceOf(epoch.deposit_account) == 0, "ad8"); require(coin.balanceOf(epoch.reward_account) == 0, "ad9"); epoch.deposit_account = address(uint160(uint(keccak256(abi.encode( "deposit_v3", epoch_index, block.number))))); epoch.reward_account = address(uint160(uint(keccak256(abi.encode( "reward_v3", epoch_index, block.number))))); epoch.reward_total = 0; epoch.phase = Phase.COMMIT; emit AdvancePhaseEvent(epoch_id_, tax, burned); return burned; } // Return the oracle level that got the largest amount of deposited coins. // In other words, return the mode of the votes weighted by the deposited // coins. // // Parameters // ---------------- // None. // // Returns // ---------------- // If there are multiple modes, return the mode that has the largest votes. // If there are multiple modes that have the largest votes, return the // smallest mode. If there are no votes, return LEVEL_MAX. function getModeLevel() public onlyOwner view returns (uint) { Epoch storage epoch = epochs_[(epoch_id_ - 2) % 3]; require(epoch.phase == Phase.RECLAIM, "gm1"); uint mode_level = LEVEL_MAX; uint max_deposit = 0; uint max_count = 0; for (uint level = 0; level < LEVEL_MAX; level++) { if (epoch.votes[level].count > 0 && (mode_level == LEVEL_MAX || max_deposit < epoch.votes[level].deposit || (max_deposit == epoch.votes[level].deposit && max_count < epoch.votes[level].count))){ max_deposit = epoch.votes[level].deposit; max_count = epoch.votes[level].count; mode_level = level; } } return mode_level; } // Return the ownership of the JohnLawCoin contract to the ACB. // // Parameters // ---------------- // |coin|: The JohnLawCoin contract. // // Returns // ---------------- // None. function revokeOwnership(JohnLawCoin_v2 coin) public onlyOwner { coin.transferOwnership(msg.sender); } // Public getter: Return the Vote object at |epoch_index| and |level|. function getVote(uint epoch_index, uint level) public view returns (uint, uint, bool, bool) { require(0 <= epoch_index && epoch_index <= 2, "gv1"); require(0 <= level && level < LEVEL_MAX, "gv2"); Vote memory vote = epochs_[epoch_index].votes[level]; return (vote.deposit, vote.count, vote.should_reclaim, vote.should_reward); } // Public getter: Return the Commit object at |epoch_index| and |account|. function getCommit(uint epoch_index, address account) public view returns (bytes32, uint, uint, Phase, uint) { require(0 <= epoch_index && epoch_index <= 2, "gc1"); Commit memory entry = epochs_[epoch_index].commits[account]; return (entry.hash, entry.deposit, entry.oracle_level, entry.phase, entry.epoch_id); } // Public getter: Return the Epoch object at |epoch_index|. function getEpoch(uint epoch_index) public view returns (address, address, uint, Phase) { require(0 <= epoch_index && epoch_index <= 2, "ge1"); return (epochs_[epoch_index].deposit_account, epochs_[epoch_index].reward_account, epochs_[epoch_index].reward_total, epochs_[epoch_index].phase); } // Calculate a hash to be committed. Voters are expected to use this // function to create a hash used in the commit phase. // // Parameters // ---------------- // |sender|: The voter's account. // |level|: The oracle level to vote. // |salt|: The voter's salt. // // Returns // ---------------- // The calculated hash value. function encrypt(address sender, uint level, uint salt) public pure returns (bytes32) { return keccak256(abi.encode(sender, level, salt)); } } //------------------------------------------------------------------------------ // [ACB contract] // // The ACB stabilizes the USD / JLC exchange rate to 1.0 with algorithmically // defined monetary policies: // // 1. The ACB obtains the exchange rate from the oracle. // 2. If the exchange rate is 1.0, the ACB does nothing. // 3. If the exchange rate is higher than 1.0, the ACB increases the total coin // supply by redeeming issued bonds (regardless of their redemption dates). // If that is not enough to supply sufficient coins, the ACB performs an open // market operation to sell JLC and purchase ETH to increase the total coin // supply. // 4. If the exchange rate is lower than 1.0, the ACB decreases the total coin // supply by issuing new bonds. If the exchange rate drops down to 0.6, the // ACB performs an open market operation to sell ETH and purchase JLC to // decrease the total coin supply. // // Permission: All the methods are public. No one (including the genesis // account) is privileged to influence the monetary policies of the ACB. The ACB // is fully decentralized and there is truly no gatekeeper. The only exceptions // are a few methods the genesis account may use to upgrade the smart contracts // to fix bugs during a development phase. //------------------------------------------------------------------------------ contract ACB_v3 is OwnableUpgradeable, PausableUpgradeable { using SafeCast for uint; using SafeCast for int; bytes32 public constant NULL_HASH = 0; // Constants. The values are defined in initialize(). The values never change // during the contract execution but use 'public' (instead of 'constant') // because tests want to override the values. uint[] public LEVEL_TO_EXCHANGE_RATE; uint public EXCHANGE_RATE_DIVISOR; uint public EPOCH_DURATION; uint public DEPOSIT_RATE; uint public DAMPING_FACTOR; // Used only in testing. This cannot be put in a derived contract due to // a restriction of @openzeppelin/truffle-upgrades. uint public _timestamp_for_testing; // Attributes. See the comment in initialize(). JohnLawCoin public coin_; Oracle public oracle_; BondOperation public bond_operation_; OpenMarketOperation public open_market_operation_; EthPool public eth_pool_; Logging public logging_; uint public oracle_level_; uint public current_epoch_start_; JohnLawCoin_v2 public coin_v2_; Oracle_v2 public oracle_v2_; BondOperation_v2 public bond_operation_v2_; OpenMarketOperation_v2 public open_market_operation_v2_; EthPool_v2 public eth_pool_v2_; Logging_v2 public logging_v2_; uint public oracle_level_v2_; uint public current_epoch_start_v2_; Oracle_v3 public oracle_v3_; // Events. event PayableEvent(address indexed sender, uint value); event UpdateEpochEvent(uint epoch_id, uint current_epoch_start, uint tax, uint burned, int delta, uint mint); event VoteEvent(address indexed sender, uint indexed epoch_id, bytes32 hash, uint oracle_level, uint salt, bool commit_result, bool reveal_result, uint deposited, uint reclaimed, uint rewarded, bool epoch_updated); event PurchaseBondsEvent(address indexed sender, uint indexed epoch_id, uint purchased_bonds, uint redemption_epoch); event RedeemBondsEvent(address indexed sender, uint indexed epoch_id, uint redeemed_bonds, uint expired_bonds); event PurchaseCoinsEvent(address indexed sender, uint requested_eth_amount, uint eth_amount, uint coin_amount); event SellCoinsEvent(address indexed sender, uint requested_coin_amount, uint eth_amount, uint coin_amount); function upgrade(Oracle_v3 oracle) public onlyOwner { // bond_budget_ = bond_budget_v2_; oracle_v3_ = oracle; // oracle_level_ = oracle_level_v2_; current_epoch_start_ = current_epoch_start_v2_; oracle_v3_.upgrade(); } // Deprecate the ACB. Only the genesis account can call this method. function deprecate() public onlyOwner { coin_v2_.transferOwnership(msg.sender); oracle_v3_.transferOwnership(msg.sender); bond_operation_v2_.transferOwnership(msg.sender); open_market_operation_v2_.transferOwnership(msg.sender); eth_pool_v2_.transferOwnership(msg.sender); logging_v2_.transferOwnership(msg.sender); } // Pause the ACB in emergency cases. Only the genesis account can call this // method. function pause() public onlyOwner { if (!paused()) { _pause(); } coin_v2_.pause(); } // Unpause the ACB. Only the genesis account can call this method. function unpause() public onlyOwner { if (paused()) { _unpause(); } coin_v2_.unpause(); } // Payable fallback to receive and store ETH. Give us tips :) fallback() external payable { require(msg.data.length == 0, "fb1"); emit PayableEvent(msg.sender, msg.value); } receive() external payable { emit PayableEvent(msg.sender, msg.value); } // Withdraw the tips. Only the genesis account can call this method. function withdrawTips() public whenNotPaused onlyOwner { (bool success,) = payable(msg.sender).call{value: address(this).balance}(""); require(success, "wt1"); } // A struct to pack local variables. This is needed to avoid a stack-too-deep // error in Solidity. struct VoteResult { uint epoch_id; bool epoch_updated; bool reveal_result; bool commit_result; uint deposited; uint reclaimed; uint rewarded; } // Vote for the exchange rate. The voter can commit a vote to the current // epoch N, reveal their vote in the epoch N-1, and reclaim the deposited // coins and get a reward for their vote in the epoch N-2 at the same time. // // Parameters // ---------------- // |hash|: The hash to be committed in the current epoch N. Specify // ACB.NULL_HASH if you do not want to commit and only want to reveal and // reclaim previous votes. // |oracle_level|: The oracle level you voted for in the epoch N-1. // |salt|: The salt you used in the epoch N-1. // // Returns // ---------------- // A tuple of six values: // - boolean: Whether the commit succeeded or not. // - boolean: Whether the reveal succeeded or not. // - uint: The amount of the deposited coins. // - uint: The amount of the reclaimed coins. // - uint: The amount of the reward. // - boolean: Whether this vote updated the epoch. function vote(bytes32 hash, uint oracle_level, uint salt) public whenNotPaused returns (bool, bool, uint, uint, uint, bool) { VoteResult memory result; result.epoch_id = oracle_v3_.epoch_id_(); result.epoch_updated = false; if (getTimestamp() >= current_epoch_start_ + EPOCH_DURATION) { // Start a new epoch. result.epoch_updated = true; result.epoch_id += 1; current_epoch_start_ = getTimestamp(); // Advance to the next epoch. Provide the |tax| coins to the oracle // as a reward. uint tax = coin_v2_.balanceOf(coin_v2_.tax_account_()); coin_v2_.transferOwnership(address(oracle_v3_)); uint burned = oracle_v3_.advance(coin_v2_); oracle_v3_.revokeOwnership(coin_v2_); // Reset the tax account address just in case. coin_v2_.resetTaxAccount(); require(coin_v2_.balanceOf(coin_v2_.tax_account_()) == 0, "vo1"); int delta = 0; oracle_level_ = oracle_v3_.getModeLevel(); if (oracle_level_ != oracle_v3_.LEVEL_MAX()) { require(0 <= oracle_level_ && oracle_level_ < oracle_v3_.LEVEL_MAX(), "vo2"); // Translate the oracle level to the exchange rate. uint exchange_rate = LEVEL_TO_EXCHANGE_RATE[oracle_level_]; // Calculate the amount of coins to be minted or burned based on the // Quantity Theory of Money. If the exchange rate is 1.1 (i.e., 1 coin // = 1.1 USD), the total coin supply is increased by 10%. If the // exchange rate is 0.8 (i.e., 1 coin = 0.8 USD), the total coin supply // is decreased by 20%. delta = coin_v2_.totalSupply().toInt256() * (int(exchange_rate) - int(EXCHANGE_RATE_DIVISOR)) / int(EXCHANGE_RATE_DIVISOR); // To avoid increasing or decreasing too many coins in one epoch, // multiply the damping factor. delta = delta * int(DAMPING_FACTOR) / 100; } // Update the bond budget. uint mint = bond_operation_v2_.updateBondBudget(delta, result.epoch_id); // Update the coin budget. if (oracle_level_ == 0 && delta < 0) { require(mint == 0, "vo3"); open_market_operation_v2_.updateCoinBudget(delta); } else { open_market_operation_v2_.updateCoinBudget(mint.toInt256()); } logging_v2_.updateEpoch( result.epoch_id, mint, burned, delta, coin_v2_.totalSupply(), oracle_level_, current_epoch_start_, tax); logging_v2_.updateBondBudget( result.epoch_id, bond_operation_v2_.bond_budget_v2_(), bond_operation_v2_.bond_v2_().totalSupply(), bond_operation_v2_.validBondSupply(result.epoch_id)); logging_v2_.updateCoinBudget( result.epoch_id, open_market_operation_v2_.coin_budget_v2_(), address(eth_pool_v2_).balance, open_market_operation_v2_.latest_price_()); emit UpdateEpochEvent(result.epoch_id, current_epoch_start_, tax, burned, delta, mint); } coin_v2_.transferOwnership(address(oracle_v3_)); // Commit. // // The voter needs to deposit the DEPOSIT_RATE percentage of their coin // balance. result.deposited = coin_v2_.balanceOf(msg.sender) * DEPOSIT_RATE / 100; if (hash == 0) { result.deposited = 0; } result.commit_result = oracle_v3_.commit( msg.sender, hash, result.deposited, coin_v2_); if (!result.commit_result) { result.deposited = 0; } // Reveal. result.reveal_result = oracle_v3_.reveal(msg.sender, oracle_level, salt); // Reclaim. (result.reclaimed, result.rewarded) = oracle_v3_.reclaim(msg.sender, coin_v2_); oracle_v3_.revokeOwnership(coin_v2_); logging_v2_.vote(result.epoch_id, result.commit_result, result.reveal_result, result.deposited, result.reclaimed, result.rewarded); emit VoteEvent( msg.sender, result.epoch_id, hash, oracle_level, salt, result.commit_result, result.reveal_result, result.deposited, result.reclaimed, result.rewarded, result.epoch_updated); return (result.commit_result, result.reveal_result, result.deposited, result.reclaimed, result.rewarded, result.epoch_updated); } // Purchase bonds. // // Parameters // ---------------- // |count|: The number of bonds to purchase. // // Returns // ---------------- // The redemption epoch of the purchased bonds. function purchaseBonds(uint count) public whenNotPaused returns (uint) { uint epoch_id = oracle_v3_.epoch_id_(); coin_v2_.transferOwnership(address(bond_operation_v2_)); uint redemption_epoch = bond_operation_v2_.increaseBondSupply(address(msg.sender), count, epoch_id, coin_v2_); bond_operation_v2_.revokeOwnership(coin_v2_); logging_v2_.purchaseBonds(epoch_id, count); emit PurchaseBondsEvent(address(msg.sender), epoch_id, count, redemption_epoch); return redemption_epoch; } // Redeem bonds. // // Parameters // ---------------- // |redemption_epochs|: An array of bonds to be redeemed. The bonds are // identified by their redemption epochs. // // Returns // ---------------- // The number of successfully redeemed bonds. function redeemBonds(uint[] memory redemption_epochs) public whenNotPaused returns (uint) { uint epoch_id = oracle_v3_.epoch_id_(); coin_v2_.transferOwnership(address(bond_operation_v2_)); (uint redeemed_bonds, uint expired_bonds) = bond_operation_v2_.decreaseBondSupply( address(msg.sender), redemption_epochs, epoch_id, coin_v2_); bond_operation_v2_.revokeOwnership(coin_v2_); logging_v2_.redeemBonds(epoch_id, redeemed_bonds, expired_bonds); emit RedeemBondsEvent(address(msg.sender), epoch_id, redeemed_bonds, expired_bonds); return redeemed_bonds; } // Pay ETH and purchase JLC from the open market operation. // // Parameters // ---------------- // The sender needs to pay |requested_eth_amount| ETH. // // Returns // ---------------- // A tuple of two values: // - The amount of ETH the sender paid. This value can be smaller than // |requested_eth_amount| when the open market operation does not have enough // coin budget. The remaining ETH is returned to the sender's wallet. // - The amount of JLC the sender purchased. function purchaseCoins() public whenNotPaused payable returns (uint, uint) { uint requested_eth_amount = msg.value; uint elapsed_time = getTimestamp() - current_epoch_start_; // Calculate the amount of ETH and JLC to be exchanged. (uint eth_amount, uint coin_amount) = open_market_operation_v2_.increaseCoinSupply( requested_eth_amount, elapsed_time); coin_v2_.mint(msg.sender, coin_amount); require(address(this).balance >= requested_eth_amount, "pc1"); bool success; (success,) = payable(address(eth_pool_v2_)).call{value: eth_amount}( abi.encodeWithSignature("increaseEth()")); require(success, "pc2"); logging_.purchaseCoins(oracle_.epoch_id_(), eth_amount, coin_amount); // Pay back the remaining ETH to the sender. This may trigger any arbitrary // operations in an external smart contract. This must be called at the very // end of purchaseCoins(). (success,) = payable(msg.sender).call{value: requested_eth_amount - eth_amount}(""); require(success, "pc3"); emit PurchaseCoinsEvent(msg.sender, requested_eth_amount, eth_amount, coin_amount); return (eth_amount, coin_amount); } // Pay JLC and purchase ETH from the open market operation. // // Parameters // ---------------- // |requested_coin_amount|: The amount of JLC the sender is willing to pay. // // Returns // ---------------- // A tuple of two values: // - The amount of ETH the sender purchased. // - The amount of JLC the sender paid. This value can be smaller than // |requested_coin_amount| when the open market operation does not have // enough ETH in the pool. function sellCoins(uint requested_coin_amount) public whenNotPaused returns (uint, uint) { // The sender does not have enough coins. require(coin_v2_.balanceOf(msg.sender) >= requested_coin_amount, "OpenMarketOperation: Your coin balance is not enough."); // Calculate the amount of ETH and JLC to be exchanged. uint elapsed_time = getTimestamp() - current_epoch_start_; (uint eth_amount, uint coin_amount) = open_market_operation_v2_.decreaseCoinSupply( requested_coin_amount, elapsed_time, address(eth_pool_v2_).balance); coin_v2_.burn(msg.sender, coin_amount); logging_.sellCoins(oracle_.epoch_id_(), eth_amount, coin_amount); // Send ETH to the sender. This may trigger any arbitrary operations in an // external smart contract. This must be called at the very end of // sellCoins(). eth_pool_v2_.decreaseEth(msg.sender, eth_amount); emit SellCoinsEvent(msg.sender, requested_coin_amount, eth_amount, coin_amount); return (eth_amount, coin_amount); } // Calculate a hash to be committed to the oracle. Voters are expected to call // this function to create the hash. // // Parameters // ---------------- // |level|: The oracle level to vote. // |salt|: The voter's salt. // // Returns // ---------------- // The calculated hash value. function encrypt(uint level, uint salt) public view returns (bytes32) { address sender = msg.sender; return oracle_v3_.encrypt(sender, level, salt); } // Public getter: Return the current timestamp in seconds. function getTimestamp() public virtual view returns (uint) { // block.timestamp is better than block.number because the granularity of // the epoch update is EPOCH_DURATION (1 week). return block.timestamp; } }
Deprecate the ACB. Only the genesis account can call this method.
function deprecate() public onlyOwner { coin_v2_.transferOwnership(msg.sender); oracle_v3_.transferOwnership(msg.sender); bond_operation_v2_.transferOwnership(msg.sender); open_market_operation_v2_.transferOwnership(msg.sender); eth_pool_v2_.transferOwnership(msg.sender); logging_v2_.transferOwnership(msg.sender); }
6,358,424
./full_match/4/0x44F204c9BDA27fcc5bCe918c550b6E5554272771/sources/browser/OroNetwork.sol
Set swap pool Percentage for fee for swap/ Updated percentage will be deducted for further swaps
function setSwapFee(uint256 percentage) public onlyOwner { swapFee = percentage; }
757,252
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v4.5.1 // 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 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 * ==== * * [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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.5.1 // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) 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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.5.0 // 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); } // File @openzeppelin/contracts/utils/Address.sol@v4.5.0 // 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/ERC20/utils/SafeERC20.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // File interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol@v4.5.1 // 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 IERC20Upgradeable { /** * @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); } // File interfaces/ILpToken.sol pragma solidity 0.8.9; interface ILpToken is IERC20Upgradeable { function mint(address account, uint256 lpTokens) external; function burn(address account, uint256 burnAmount) external returns (uint256); function burn(uint256 burnAmount) external; function minter() external view returns (address); function initialize( string memory name_, string memory symbol_, uint8 _decimals, address _minter ) external returns (bool); } // File interfaces/IStakerVault.sol pragma solidity 0.8.9; interface IStakerVault { event Staked(address indexed account, uint256 amount); event Unstaked(address indexed account, uint256 amount); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function initialize(address _token) external; function initializeLpGauge(address _lpGauge) external returns (bool); function stake(uint256 amount) external returns (bool); function stakeFor(address account, uint256 amount) external returns (bool); function unstake(uint256 amount) external returns (bool); function unstakeFor( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transfer(address account, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function getToken() external view returns (address); function balanceOf(address account) external view returns (uint256); function stakedAndActionLockedBalanceOf(address account) external view returns (uint256); function actionLockedBalanceOf(address account) external view returns (uint256); function increaseActionLockedBalance(address account, uint256 amount) external returns (bool); function decreaseActionLockedBalance(address account, uint256 amount) external returns (bool); function getStakedByActions() external view returns (uint256); function addStrategy(address strategy) external returns (bool); function getPoolTotalStaked() external view returns (uint256); function prepareLpGauge(address _lpGauge) external returns (bool); function executeLpGauge() external returns (bool); function getLpGauge() external view returns (address); function poolCheckpoint() external returns (bool); function isStrategy(address user) external view returns (bool); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File libraries/ScaledMath.sol pragma solidity 0.8.9; /* * @dev To use functions of this contract, at least one of the numbers must * be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE` * if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale * of the number not scaled by `DECIMAL_SCALE` */ library ScaledMath { // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant DECIMAL_SCALE = 1e18; // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant ONE = 1e18; /** * @notice Performs a multiplication between two scaled numbers */ function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) { return (a * b) / DECIMAL_SCALE; } /** * @notice Performs a division between two scaled numbers */ function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE) / b; } /** * @notice Performs a division between two numbers, rounding up the result */ function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE + b - 1) / b; } /** * @notice Performs a division between two numbers, ignoring any scaling and rounding up the result */ function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/utils/Preparable.sol pragma solidity 0.8.9; /** * @notice Implements the base logic for a two-phase commit * @dev This does not implements any access-control so publicly exposed * callers should make sure to have the proper checks in palce */ contract Preparable is IPreparable { uint256 private constant _MIN_DELAY = 3 days; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingUInts256; mapping(bytes32 => address) public currentAddresses; mapping(bytes32 => uint256) public currentUInts256; /** * @dev Deadlines shares the same namespace regardless of the type * of the pending variable so this needs to be enforced in the caller */ mapping(bytes32 => uint256) public deadlines; function _prepareDeadline(bytes32 key, uint256 delay) internal { require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO); require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT); deadlines[key] = block.timestamp + delay; } /** * @notice Prepares an uint256 that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay */ function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Prepares an address that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, address value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingAddresses[key] = value; emit ConfigPreparedAddress(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay */ function _prepare(bytes32 key, address value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Reset a uint256 key * @return `true` if success. */ function _resetUInt256Config(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingUInts256[key] = 0; emit ConfigReset(key); return true; } /** * @notice Reset an address key * @return `true` if success. */ function _resetAddressConfig(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingAddresses[key] = address(0); emit ConfigReset(key); return true; } /** * @dev Checks the deadline of the key and reset it */ function _executeDeadline(bytes32 key) internal { uint256 deadline = deadlines[key]; require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED); require(deadline != 0, Error.DEADLINE_NOT_SET); deadlines[key] = 0; } /** * @notice Execute uint256 config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeUInt256(bytes32 key) internal returns (uint256) { _executeDeadline(key); uint256 newValue = pendingUInts256[key]; _setConfig(key, newValue); return newValue; } /** * @notice Execute address config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeAddress(bytes32 key) internal returns (address) { _executeDeadline(key); address newValue = pendingAddresses[key]; _setConfig(key, newValue); return newValue; } function _setConfig(bytes32 key, address value) internal returns (address) { address oldValue = currentAddresses[key]; currentAddresses[key] = value; pendingAddresses[key] = address(0); deadlines[key] = 0; emit ConfigUpdatedAddress(key, oldValue, value); return value; } function _setConfig(bytes32 key, uint256 value) internal returns (uint256) { uint256 oldValue = currentUInts256[key]; currentUInts256[key] = value; pendingUInts256[key] = 0; deadlines[key] = 0; emit ConfigUpdatedNumber(key, oldValue, value); return value; } } // File contracts/utils/Pausable.sol pragma solidity 0.8.9; abstract contract Pausable { bool public isPaused; modifier notPaused() { require(!isPaused, Error.CONTRACT_PAUSED); _; } modifier onlyAuthorizedToPause() { require(_isAuthorizedToPause(msg.sender), Error.CONTRACT_PAUSED); _; } /** * @notice Pause the contract. * @return `true` if success. */ function pause() external onlyAuthorizedToPause returns (bool) { isPaused = true; return true; } /** * @notice Unpause the contract. * @return `true` if success. */ function unpause() external onlyAuthorizedToPause returns (bool) { isPaused = false; return true; } /** * @notice Returns true if `account` is authorized to pause the contract * @dev This should be implemented in contracts inheriting `Pausable` * to provide proper access control */ function _isAuthorizedToPause(address account) internal view virtual returns (bool); } // File contracts/pool/LiquidityPool.sol pragma solidity 0.8.9; /** * @dev Pausing/unpausing the pool will disable/re-enable deposits. */ abstract contract LiquidityPool is ILiquidityPool, Authorization, Preparable, Pausable, Initializable { using AddressProviderHelpers for IAddressProvider; using ScaledMath for uint256; using SafeERC20 for IERC20; struct WithdrawalFeeMeta { uint64 timeToWait; uint64 feeRatio; uint64 lastActionTimestamp; } bytes32 internal constant _VAULT_KEY = "Vault"; bytes32 internal constant _RESERVE_DEVIATION_KEY = "ReserveDeviation"; bytes32 internal constant _REQUIRED_RESERVES_KEY = "RequiredReserves"; bytes32 internal constant _MAX_WITHDRAWAL_FEE_KEY = "MaxWithdrawalFee"; bytes32 internal constant _MIN_WITHDRAWAL_FEE_KEY = "MinWithdrawalFee"; bytes32 internal constant _WITHDRAWAL_FEE_DECREASE_PERIOD_KEY = "WithdrawalFeeDecreasePeriod"; uint256 internal constant _INITIAL_RESERVE_DEVIATION = 0.005e18; // 0.5% uint256 internal constant _INITIAL_FEE_DECREASE_PERIOD = 1 weeks; uint256 internal constant _INITIAL_MAX_WITHDRAWAL_FEE = 0.03e18; // 3% /** * @notice even through admin votes and later governance, the withdrawal * fee will never be able to go above this value */ uint256 internal constant _MAX_WITHDRAWAL_FEE = 0.05e18; /** * @notice Keeps track of the withdrawal fees on a per-address basis */ mapping(address => WithdrawalFeeMeta) public withdrawalFeeMetas; IController public immutable controller; IAddressProvider public immutable addressProvider; uint256 public depositCap; IStakerVault public staker; ILpToken public lpToken; string public name; constructor(IController _controller) Authorization(_controller.addressProvider().getRoleManager()) { require(address(_controller) != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); controller = IController(_controller); addressProvider = IController(_controller).addressProvider(); } /** * @notice Deposit funds into liquidity pool and mint LP tokens in exchange. * @param depositAmount Amount of the underlying asset to supply. * @return The actual amount minted. */ function deposit(uint256 depositAmount) external payable override returns (uint256) { return depositFor(msg.sender, depositAmount, 0); } /** * @notice Deposit funds into liquidity pool and mint LP tokens in exchange. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return The actual amount minted. */ function deposit(uint256 depositAmount, uint256 minTokenAmount) external payable override returns (uint256) { return depositFor(msg.sender, depositAmount, minTokenAmount); } /** * @notice Deposit funds into liquidity pool and stake LP Tokens in Staker Vault. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return The actual amount minted and staked. */ function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable override returns (uint256) { uint256 amountMinted_ = depositFor(address(this), depositAmount, minTokenAmount); staker.stakeFor(msg.sender, amountMinted_); return amountMinted_; } /** * @notice Withdraws all funds from vault. * @dev Should be called in case of emergencies. */ function withdrawAll() external onlyGovernance { getVault().withdrawAll(); } function setLpToken(address _lpToken) external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { require(address(lpToken) == address(0), Error.ADDRESS_ALREADY_SET); require(ILpToken(_lpToken).minter() == address(this), Error.INVALID_MINTER); lpToken = ILpToken(_lpToken); _approveStakerVaultSpendingLpTokens(); emit LpTokenSet(_lpToken); return true; } /** * @notice Checkpoint function to update a user's withdrawal fees on deposit and redeem * @param from Address sending from * @param to Address sending to * @param amount Amount to redeem or deposit */ function handleLpTokenTransfer( address from, address to, uint256 amount ) external override { require( msg.sender == address(lpToken) || msg.sender == address(staker), Error.UNAUTHORIZED_ACCESS ); if ( addressProvider.isStakerVault(to, address(lpToken)) || addressProvider.isStakerVault(from, address(lpToken)) || addressProvider.isAction(to) || addressProvider.isAction(from) ) { return; } if (to != address(0)) { _updateUserFeesOnDeposit(to, from, amount); } } /** * @notice Prepare update of required reserve ratio (with time delay enforced). * @param _newRatio New required reserve ratio. * @return `true` if success. */ function prepareNewRequiredReserves(uint256 _newRatio) external onlyGovernance returns (bool) { require(_newRatio <= ScaledMath.ONE, Error.INVALID_AMOUNT); return _prepare(_REQUIRED_RESERVES_KEY, _newRatio); } /** * @notice Execute required reserve ratio update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New required reserve ratio. */ function executeNewRequiredReserves() external override returns (uint256) { uint256 requiredReserveRatio = _executeUInt256(_REQUIRED_RESERVES_KEY); _rebalanceVault(); return requiredReserveRatio; } /** * @notice Reset the prepared required reserves. * @return `true` if success. */ function resetRequiredReserves() external onlyGovernance returns (bool) { return _resetUInt256Config(_REQUIRED_RESERVES_KEY); } /** * @notice Prepare update of reserve deviation ratio (with time delay enforced). * @param newRatio New reserve deviation ratio. * @return `true` if success. */ function prepareNewReserveDeviation(uint256 newRatio) external onlyGovernance returns (bool) { require(newRatio <= (ScaledMath.DECIMAL_SCALE * 50) / 100, Error.INVALID_AMOUNT); return _prepare(_RESERVE_DEVIATION_KEY, newRatio); } /** * @notice Execute reserve deviation ratio update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New reserve deviation ratio. */ function executeNewReserveDeviation() external override returns (uint256) { uint256 reserveDeviation = _executeUInt256(_RESERVE_DEVIATION_KEY); _rebalanceVault(); return reserveDeviation; } /** * @notice Reset the prepared reserve deviation. * @return `true` if success. */ function resetNewReserveDeviation() external onlyGovernance returns (bool) { return _resetUInt256Config(_RESERVE_DEVIATION_KEY); } /** * @notice Prepare update of min withdrawal fee (with time delay enforced). * @param newFee New min withdrawal fee. * @return `true` if success. */ function prepareNewMinWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) { _checkFeeInvariants(newFee, getMaxWithdrawalFee()); return _prepare(_MIN_WITHDRAWAL_FEE_KEY, newFee); } /** * @notice Execute min withdrawal fee update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New withdrawal fee. */ function executeNewMinWithdrawalFee() external returns (uint256) { uint256 newFee = _executeUInt256(_MIN_WITHDRAWAL_FEE_KEY); _checkFeeInvariants(newFee, getMaxWithdrawalFee()); return newFee; } /** * @notice Reset the prepared min withdrawal fee * @return `true` if success. */ function resetNewMinWithdrawalFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_MIN_WITHDRAWAL_FEE_KEY); } /** * @notice Prepare update of max withdrawal fee (with time delay enforced). * @param newFee New max withdrawal fee. * @return `true` if success. */ function prepareNewMaxWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) { _checkFeeInvariants(getMinWithdrawalFee(), newFee); return _prepare(_MAX_WITHDRAWAL_FEE_KEY, newFee); } /** * @notice Execute max withdrawal fee update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New max withdrawal fee. */ function executeNewMaxWithdrawalFee() external override returns (uint256) { uint256 newFee = _executeUInt256(_MAX_WITHDRAWAL_FEE_KEY); _checkFeeInvariants(getMinWithdrawalFee(), newFee); return newFee; } /** * @notice Reset the prepared max fee. * @return `true` if success. */ function resetNewMaxWithdrawalFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_MAX_WITHDRAWAL_FEE_KEY); } /** * @notice Prepare update of withdrawal decrease fee period (with time delay enforced). * @param newPeriod New withdrawal fee decrease period. * @return `true` if success. */ function prepareNewWithdrawalFeeDecreasePeriod(uint256 newPeriod) external onlyGovernance returns (bool) { return _prepare(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, newPeriod); } /** * @notice Execute withdrawal fee decrease period update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New withdrawal fee decrease period. */ function executeNewWithdrawalFeeDecreasePeriod() external returns (uint256) { return _executeUInt256(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY); } /** * @notice Reset the prepared withdrawal fee decrease period update. * @return `true` if success. */ function resetNewWithdrawalFeeDecreasePeriod() external onlyGovernance returns (bool) { return _resetUInt256Config(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY); } /** * @notice Set the staker vault for this pool's LP token * @dev Staker vault and LP token pairs are immutable and the staker vault can only be set once for a pool. * Only one vault exists per LP token. This information will be retrieved from the controller of the pool. * @return Address of the new staker vault for the pool. */ function setStaker() external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { require(address(staker) == address(0), Error.ADDRESS_ALREADY_SET); address stakerVault = addressProvider.getStakerVault(address(lpToken)); require(stakerVault != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); staker = IStakerVault(stakerVault); _approveStakerVaultSpendingLpTokens(); emit StakerVaultSet(stakerVault); return true; } /** * @notice Prepare setting a new Vault (with time delay enforced). * @param _vault Address of new Vault contract. * @return `true` if success. */ function prepareNewVault(address _vault) external onlyGovernance returns (bool) { _prepare(_VAULT_KEY, _vault); return true; } /** * @notice Execute Vault update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return Address of new Vault contract. */ function executeNewVault() external override returns (address) { IVault vault = getVault(); if (address(vault) != address(0)) { vault.withdrawAll(); } address newVault = _executeAddress(_VAULT_KEY); addressProvider.updateVault(address(vault), newVault); return newVault; } /** * @notice Reset the vault deadline. * @return `true` if success. */ function resetNewVault() external onlyGovernance returns (bool) { return _resetAddressConfig(_VAULT_KEY); } /** * @notice Redeems the underlying asset by burning LP tokens. * @param redeemLpTokens Number of tokens to burn for redeeming the underlying. * @return Actual amount of the underlying redeemed. */ function redeem(uint256 redeemLpTokens) external override returns (uint256) { return redeem(redeemLpTokens, 0); } /** * @notice Uncap the pool to remove the deposit limit. * @return `true` if success. */ function uncap() external override onlyGovernance returns (bool) { require(isCapped(), Error.NOT_CAPPED); depositCap = 0; return true; } /** * @notice Update the deposit cap value. * @param _depositCap The maximum allowed deposits per address in the pool * @return `true` if success. */ function updateDepositCap(uint256 _depositCap) external override onlyGovernance returns (bool) { require(isCapped(), Error.NOT_CAPPED); require(depositCap != _depositCap, Error.SAME_AS_CURRENT); require(_depositCap > 0, Error.INVALID_AMOUNT); depositCap = _depositCap; return true; } /** * @notice Rebalance vault according to required underlying backing reserves. */ function rebalanceVault() external onlyGovernance { _rebalanceVault(); } /** * @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange. * @param account Account to deposit for. * @param depositAmount Amount of the underlying asset to supply. * @return Actual amount minted. */ function depositFor(address account, uint256 depositAmount) external payable override returns (uint256) { return depositFor(account, depositAmount, 0); } /** * @notice Redeems the underlying asset by burning LP tokens, unstaking any LP tokens needed. * @param redeemLpTokens Number of tokens to unstake and/or burn for redeeming the underlying. * @param minRedeemAmount Minimum amount of underlying that should be received. * @return Actual amount of the underlying redeemed. */ function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external override returns (uint256) { uint256 lpBalance_ = lpToken.balanceOf(msg.sender); require( lpBalance_ + staker.balanceOf(msg.sender) >= redeemLpTokens, Error.INSUFFICIENT_BALANCE ); if (lpBalance_ < redeemLpTokens) { staker.unstakeFor(msg.sender, msg.sender, redeemLpTokens - lpBalance_); } return redeem(redeemLpTokens, minRedeemAmount); } /** * @notice Returns the address of the LP token of this pool * @return The address of the LP token */ function getLpToken() external view override returns (address) { return address(lpToken); } /** * @notice Calculates the amount of LP tokens that need to be redeemed to get a certain amount of underlying (includes fees and exchange rate) * @param account Address of the account redeeming. * @param underlyingAmount The amount of underlying desired. * @return Amount of LP tokens that need to be redeemed. */ function calcRedeem(address account, uint256 underlyingAmount) external view override returns (uint256) { require(underlyingAmount > 0, Error.INVALID_AMOUNT); ILpToken lpToken_ = lpToken; require(lpToken_.balanceOf(account) > 0, Error.INSUFFICIENT_BALANCE); uint256 currentExchangeRate = exchangeRate(); uint256 withoutFeesLpAmount = underlyingAmount.scaledDiv(currentExchangeRate); if (withoutFeesLpAmount == lpToken_.totalSupply()) { return withoutFeesLpAmount; } WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account]; uint256 currentFeeRatio = 0; if (!addressProvider.isAction(account)) { currentFeeRatio = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); } uint256 scalingFactor = currentExchangeRate.scaledMul((ScaledMath.ONE - currentFeeRatio)); uint256 neededLpTokens = underlyingAmount.scaledDivRoundUp(scalingFactor); return neededLpTokens; } function getUnderlying() external view virtual override returns (address); /** * @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange. * @param account Account to deposit for. * @param depositAmount Amount of the underlying asset to supply. * @param minTokenAmount Minimum amount of LP tokens that should be minted. * @return Actual amount minted. */ function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) public payable override notPaused returns (uint256) { uint256 rate = exchangeRate(); if (isCapped()) { uint256 lpBalance = lpToken.balanceOf(account); uint256 stakedAndLockedBalance = staker.stakedAndActionLockedBalanceOf(account); uint256 currentUnderlyingBalance = (lpBalance + stakedAndLockedBalance).scaledMul(rate); require( currentUnderlyingBalance + depositAmount <= depositCap, Error.EXCEEDS_DEPOSIT_CAP ); } _doTransferIn(msg.sender, depositAmount); uint256 mintedLp = depositAmount.scaledDiv(rate); require(mintedLp >= minTokenAmount, Error.INVALID_AMOUNT); lpToken.mint(account, mintedLp); _rebalanceVault(); if (msg.sender == account || address(this) == account) { emit Deposit(msg.sender, depositAmount, mintedLp); } else { emit DepositFor(msg.sender, account, depositAmount, mintedLp); } return mintedLp; } /** * @notice Redeems the underlying asset by burning LP tokens. * @param redeemLpTokens Number of tokens to burn for redeeming the underlying. * @param minRedeemAmount Minimum amount of underlying that should be received. * @return Actual amount of the underlying redeemed. */ function redeem(uint256 redeemLpTokens, uint256 minRedeemAmount) public override returns (uint256) { require(redeemLpTokens > 0, Error.INVALID_AMOUNT); ILpToken lpToken_ = lpToken; require(lpToken_.balanceOf(msg.sender) >= redeemLpTokens, Error.INSUFFICIENT_BALANCE); uint256 withdrawalFee = addressProvider.isAction(msg.sender) ? 0 : getWithdrawalFee(msg.sender, redeemLpTokens); uint256 redeemMinusFees = redeemLpTokens - withdrawalFee; // Pay no fees on the last withdrawal (avoid locking funds in the pool) if (redeemLpTokens == lpToken_.totalSupply()) { redeemMinusFees = redeemLpTokens; } uint256 redeemUnderlying = redeemMinusFees.scaledMul(exchangeRate()); require(redeemUnderlying >= minRedeemAmount, Error.NOT_ENOUGH_FUNDS_WITHDRAWN); _rebalanceVault(redeemUnderlying); lpToken_.burn(msg.sender, redeemLpTokens); _doTransferOut(payable(msg.sender), redeemUnderlying); emit Redeem(msg.sender, redeemUnderlying, redeemLpTokens); return redeemUnderlying; } /** * @return the current required reserves ratio */ function getRequiredReserveRatio() public view virtual returns (uint256) { return currentUInts256[_REQUIRED_RESERVES_KEY]; } /** * @return the current maximum reserve deviation ratio */ function getMaxReserveDeviationRatio() public view virtual returns (uint256) { return currentUInts256[_RESERVE_DEVIATION_KEY]; } /** * @notice Returns the current minimum withdrawal fee */ function getMinWithdrawalFee() public view returns (uint256) { return currentUInts256[_MIN_WITHDRAWAL_FEE_KEY]; } /** * @notice Returns the current maximum withdrawal fee */ function getMaxWithdrawalFee() public view returns (uint256) { return currentUInts256[_MAX_WITHDRAWAL_FEE_KEY]; } /** * @notice Returns the current withdrawal fee decrease period */ function getWithdrawalFeeDecreasePeriod() public view returns (uint256) { return currentUInts256[_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY]; } /** * @return the current vault of the liquidity pool */ function getVault() public view virtual override returns (IVault) { return IVault(currentAddresses[_VAULT_KEY]); } /** * @notice Compute current exchange rate of LP tokens to underlying scaled to 1e18. * @dev Exchange rate means: underlying = LP token * exchangeRate * @return Current exchange rate. */ function exchangeRate() public view override returns (uint256) { uint256 totalUnderlying_ = totalUnderlying(); uint256 totalSupply = lpToken.totalSupply(); if (totalSupply == 0 || totalUnderlying_ == 0) { return ScaledMath.ONE; } return totalUnderlying_.scaledDiv(totalSupply); } /** * @notice Compute total amount of underlying tokens for this pool. * @return Total amount of underlying in pool. */ function totalUnderlying() public view returns (uint256) { IVault vault = getVault(); uint256 balanceUnderlying = _getBalanceUnderlying(); if (address(vault) == address(0)) { return balanceUnderlying; } uint256 investedUnderlying = vault.getTotalUnderlying(); return investedUnderlying + balanceUnderlying; } /** * @notice Retuns if the pool has an active deposit limit * @return `true` if there is currently a deposit limit */ function isCapped() public view override returns (bool) { return depositCap != 0; } /** * @notice Returns the withdrawal fee for `account` * @param account Address to get the withdrawal fee for * @param amount Amount to calculate the withdrawal fee for * @return Withdrawal fee in LP tokens */ function getWithdrawalFee(address account, uint256 amount) public view override returns (uint256) { WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account]; if (lpToken.balanceOf(account) == 0) { return 0; } uint256 currentFee = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); return amount.scaledMul(currentFee); } /** * @notice Calculates the withdrawal fee a user would currently need to pay on currentBalance. * @param timeToWait The total time to wait until the withdrawal fee reached the min. fee * @param lastActionTimestamp Timestamp of the last fee update * @param feeRatio Fees that would currently be paid on the user's entire balance * @return Updated fee amount on the currentBalance */ function getNewCurrentFees( uint256 timeToWait, uint256 lastActionTimestamp, uint256 feeRatio ) public view returns (uint256) { uint256 timeElapsed = _getTime() - lastActionTimestamp; uint256 minFeePercentage = getMinWithdrawalFee(); if (timeElapsed >= timeToWait) { return minFeePercentage; } uint256 elapsedShare = timeElapsed.scaledDiv(timeToWait); return feeRatio - (feeRatio - minFeePercentage).scaledMul(elapsedShare); } function _rebalanceVault() internal { _rebalanceVault(0); } function _initialize( string memory name_, uint256 depositCap_, address vault_ ) internal initializer returns (bool) { name = name_; depositCap = depositCap_; _setConfig(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, _INITIAL_FEE_DECREASE_PERIOD); _setConfig(_MAX_WITHDRAWAL_FEE_KEY, _INITIAL_MAX_WITHDRAWAL_FEE); _setConfig(_REQUIRED_RESERVES_KEY, ScaledMath.ONE); _setConfig(_RESERVE_DEVIATION_KEY, _INITIAL_RESERVE_DEVIATION); _setConfig(_VAULT_KEY, vault_); return true; } function _approveStakerVaultSpendingLpTokens() internal { address staker_ = address(staker); address lpToken_ = address(lpToken); if (staker_ == address(0) || lpToken_ == address(0)) return; IERC20(lpToken_).safeApprove(staker_, type(uint256).max); } function _doTransferIn(address from, uint256 amount) internal virtual; function _doTransferOut(address payable to, uint256 amount) internal virtual; /** * @dev Rebalances the pool's allocations to the vault * @param underlyingToWithdraw Amount of underlying to withdraw such that after the withdrawal the pool and vault allocations are correctly balanced. */ function _rebalanceVault(uint256 underlyingToWithdraw) internal { IVault vault = getVault(); if (address(vault) == address(0)) return; uint256 lockedLp = staker.getStakedByActions(); uint256 totalUnderlyingStaked = lockedLp.scaledMul(exchangeRate()); uint256 underlyingBalance = _getBalanceUnderlying(true); uint256 maximumDeviation = totalUnderlyingStaked.scaledMul(getMaxReserveDeviationRatio()); uint256 nextTargetBalance = totalUnderlyingStaked.scaledMul(getRequiredReserveRatio()); if ( underlyingToWithdraw > underlyingBalance || (underlyingBalance - underlyingToWithdraw) + maximumDeviation < nextTargetBalance ) { uint256 requiredDeposits = nextTargetBalance + underlyingToWithdraw - underlyingBalance; vault.withdraw(requiredDeposits); } else { uint256 nextBalance = underlyingBalance - underlyingToWithdraw; if (nextBalance > nextTargetBalance + maximumDeviation) { uint256 excessDeposits = nextBalance - nextTargetBalance; _doTransferOut(payable(address(vault)), excessDeposits); vault.deposit(); } } } function _updateUserFeesOnDeposit( address account, address from, uint256 amountAdded ) internal { WithdrawalFeeMeta storage meta = withdrawalFeeMetas[account]; uint256 balance = lpToken.balanceOf(account) + staker.stakedAndActionLockedBalanceOf(account); uint256 newCurrentFeeRatio = getNewCurrentFees( meta.timeToWait, meta.lastActionTimestamp, meta.feeRatio ); uint256 shareAdded = amountAdded.scaledDiv(amountAdded + balance); uint256 shareExisting = ScaledMath.ONE - shareAdded; uint256 feeOnDeposit; if (from == address(0)) { feeOnDeposit = getMaxWithdrawalFee(); } else { WithdrawalFeeMeta storage fromMeta = withdrawalFeeMetas[from]; feeOnDeposit = getNewCurrentFees( fromMeta.timeToWait, fromMeta.lastActionTimestamp, fromMeta.feeRatio ); } uint256 newFeeRatio = shareExisting.scaledMul(newCurrentFeeRatio) + shareAdded.scaledMul(feeOnDeposit); meta.feeRatio = uint64(newFeeRatio); meta.timeToWait = uint64(getWithdrawalFeeDecreasePeriod()); meta.lastActionTimestamp = uint64(_getTime()); } function _getBalanceUnderlying() internal view virtual returns (uint256); function _getBalanceUnderlying(bool transferInDone) internal view virtual returns (uint256); function _isAuthorizedToPause(address account) internal view override returns (bool) { return _roleManager().hasRole(Roles.GOVERNANCE, account); } /** * @dev Overriden for testing */ function _getTime() internal view virtual returns (uint256) { return block.timestamp; } function _checkFeeInvariants(uint256 minFee, uint256 maxFee) internal pure { require(maxFee >= minFee, Error.INVALID_AMOUNT); require(maxFee <= _MAX_WITHDRAWAL_FEE, Error.INVALID_AMOUNT); } } // File interfaces/pool/IErc20Pool.sol pragma solidity 0.8.9; interface IErc20Pool { function initialize( string memory name_, address underlying_, uint256 depositCap_, address vault_ ) external returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // File contracts/pool/Erc20Pool.sol pragma solidity 0.8.9; contract Erc20Pool is LiquidityPool, IErc20Pool { using SafeERC20 for IERC20; address private _underlying; constructor(IController _controller) LiquidityPool(_controller) {} function initialize( string memory name_, address underlying_, uint256 depositCap_, address vault_ ) public override returns (bool) { require(underlying_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); _underlying = underlying_; return _initialize(name_, depositCap_, vault_); } function getUnderlying() public view override returns (address) { return _underlying; } function _doTransferIn(address from, uint256 amount) internal override { require(msg.value == 0, Error.INVALID_VALUE); IERC20(_underlying).safeTransferFrom(from, address(this), amount); } function _doTransferOut(address payable to, uint256 amount) internal override { IERC20(_underlying).safeTransfer(to, amount); } function _getBalanceUnderlying() internal view override returns (uint256) { return IERC20(_underlying).balanceOf(address(this)); } function _getBalanceUnderlying(bool) internal view override returns (uint256) { return _getBalanceUnderlying(); } }
Execute withdrawal fee decrease period update (with time delay enforced). Needs to be called after the update was prepraed. Fails if called before time delay is met. return New withdrawal fee decrease period./
function executeNewWithdrawalFeeDecreasePeriod() external returns (uint256) { return _executeUInt256(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY); }
10,436,080
./full_match/5/0x61474Ec2b66fd4b6206BACC5795DD8Bf5813c476/sources/localhost/contracts/libraries/GatebridgeV2Library.sol
given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'GatebridgeV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'GatebridgeV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); }
1,945,281
./partial_match/1/0x8AD2512819A7eae1dd398973EFfaE48dafBe8255/sources/veBalFeeInjector.sol
Injects new veBAL performData required by chainlink keeper interface but not used in this contract, can be 0x0 or anything else. return upkeepNeeded signals if upkeep is needed/
function performUpkeep(bytes calldata performData) external onlyKeeperRegistry whenNotPaused { uint256 timeCursor = FeeDistributor.getTimeCursor(); require(LastRunTimeCurser < timeCursor, "Not ready"); uint counter = 0; for(uint i=0; i< ManagedTokens.length; i++){ if (ManagedTokens[i].balanceOf(address(this)) > MinAmount * 10**(IERC20Metadata(address(ManagedTokens[i])).decimals())){ counter++; } } require(counter == ManagedTokens.length, "Not ready"); _payFees(); for(uint i=0; i< ManagedTokens.length; i++){ if (ManagedTokens[i].balanceOf(address(this)) > MinAmount * 10**(IERC20Metadata(address(ManagedTokens[i])).decimals())){ counter++; } } require(counter == ManagedTokens.length, "Not ready"); _payFees(); }
2,781,100
./full_match/80001/0xcFd3E772338EE65193E74eb0E70eCb228AfB5Df7/sources/project_/contracts/MetaNftV2.sol
setting this will allow buy with one click
function _mintInternal(uint32 _quantity) internal returns (uint256) } } if (_buyNowPrice > 0) { _sailingBox[_tokenId][msg.sender] = Sale(1, _minPrice, msg.sender, resell); } _auctionState[_tokenId] = AuctionState(true, _minPrice, msg.sender, resell); emit AuctionCreated(_tokenId, msg.sender, _minPrice, _buyNowPrice, resell);
9,482,731
pragma solidity ^0.4.21; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } 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; } } // ERC20 token interface is implemented only partially. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract NamiPool { using SafeMath for uint256; function NamiPool(address _escrow, address _namiMultiSigWallet, address _namiAddress) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; NamiAddr = _namiAddress; } string public name = "Nami Pool"; // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; /// address of Nami token address public NamiAddr; modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyNami { require(msg.sender == NamiAddr); _; } modifier onlyNamiMultisig { require(msg.sender == namiMultiSigWallet); _; } uint public currentRound = 1; struct ShareHolder { uint stake; bool isActive; bool isWithdrawn; } struct Round { bool isOpen; uint currentNAC; uint finalNAC; uint ethBalance; bool withdrawable; //for user not in top bool topWithdrawable; bool isCompleteActive; bool isCloseEthPool; } mapping (uint => mapping (address => ShareHolder)) public namiPool; mapping (uint => Round) public round; // Events event UpdateShareHolder(address indexed ShareHolderAddress, uint indexed RoundIndex, uint Stake, uint Time); event Deposit(address sender,uint indexed RoundIndex, uint value); event WithdrawPool(uint Amount, uint TimeWithdraw); event UpdateActive(address indexed ShareHolderAddress, uint indexed RoundIndex, bool Status, uint Time); event Withdraw(address indexed ShareHolderAddress, uint indexed RoundIndex, uint Ether, uint Nac, uint TimeWithdraw); event ActivateRound(uint RoundIndex, uint TimeActive); function changeEscrow(address _escrow) onlyNamiMultisig public { require(_escrow != 0x0); escrow = _escrow; } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } function withdrawNAC(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0 && _amount != 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); if (namiToken.balanceOf(this) > 0) { namiToken.transfer(namiMultiSigWallet, _amount); } } /*/ * Admin function /*/ /*/ process of one round * step 1: admin open one round by execute activateRound function * step 2: now investor can invest Nac to Nac Pool until round closed * step 3: admin close round, now investor cann&#39;t invest NAC to Pool * step 4: admin activate top investor * step 5: all top investor was activated, admin execute closeActive function to close active phrase * step 6: admin open withdrawable for investor not in top to withdraw NAC * step 7: admin deposit eth to eth pool * step 8: close deposit eth to eth pool * step 9: admin open withdrawable to investor in top * step 10: investor in top now can withdraw NAC and ETH for this round /*/ // ------------------------------------------------ /* * Admin function * Open and Close Round * */ function activateRound(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isOpen == false && round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isCompleteActive == false); round[_roundIndex].isOpen = true; currentRound = _roundIndex; emit ActivateRound(_roundIndex, now); } function deactivateRound(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isOpen == true); round[_roundIndex].isOpen = false; } // ------------------------------------------------ // this function add stake of ShareHolder // investor can execute this function during round open // function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { // only on currentRound and active user can add stake require(round[_price].isOpen == true && _value > 0); // add stake namiPool[_price][_from].stake = namiPool[_price][_from].stake.add(_value); round[_price].currentNAC = round[_price].currentNAC.add(_value); emit UpdateShareHolder(_from, _price, namiPool[_price][_from].stake, now); return true; } /* * * Activate and deactivate user * add or sub final Nac to compute stake to withdraw */ function activateUser(address _shareAddress, uint _roundId) onlyEscrow public { require(namiPool[_roundId][_shareAddress].isActive == false && namiPool[_roundId][_shareAddress].stake > 0); require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); namiPool[_roundId][_shareAddress].isActive = true; round[_roundId].finalNAC = round[_roundId].finalNAC.add(namiPool[_roundId][_shareAddress].stake); emit UpdateActive(_shareAddress, _roundId ,namiPool[_roundId][_shareAddress].isActive, now); } function deactivateUser(address _shareAddress, uint _roundId) onlyEscrow public { require(namiPool[_roundId][_shareAddress].isActive == true && namiPool[_roundId][_shareAddress].stake > 0); require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); namiPool[_roundId][_shareAddress].isActive = false; round[_roundId].finalNAC = round[_roundId].finalNAC.sub(namiPool[_roundId][_shareAddress].stake); emit UpdateActive(_shareAddress, _roundId ,namiPool[_roundId][_shareAddress].isActive, now); } // ------------------------------------------------ // admin close activate phrase to // // function closeActive(uint _roundId) onlyEscrow public { require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); round[_roundId].isCompleteActive = true; } // // // change Withdrawable for one round after every month // for investor not in top // function changeWithdrawable(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].withdrawable = !round[_roundIndex].withdrawable; } // // // change Withdrawable for one round after every month // for investor in top // function changeTopWithdrawable(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].topWithdrawable = !round[_roundIndex].topWithdrawable; } // // // after month admin deposit ETH to ETH Pool // // function depositEthPool(uint _roundIndex) payable public onlyEscrow { require(msg.value > 0 && round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isOpen == false); if (msg.value > 0) { round[_roundIndex].ethBalance = round[_roundIndex].ethBalance.add(msg.value); emit Deposit(msg.sender, _roundIndex, msg.value); } } // // function withdrawEthPool(uint _roundIndex, uint _amount) public onlyEscrow { require(round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isOpen == false); require(namiMultiSigWallet != 0x0); // if (_amount > 0) { namiMultiSigWallet.transfer(_amount); round[_roundIndex].ethBalance = round[_roundIndex].ethBalance.sub(_amount); emit WithdrawPool(_amount, now); } } // // close phrase deposit ETH to Pool // function closeEthPool(uint _roundIndex) public onlyEscrow { require(round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].isCloseEthPool = true; } // // // withdraw NAC for investor // internal function only can run by this smartcontract // // function _withdrawNAC(address _shareAddress, uint _roundIndex) internal { require(namiPool[_roundIndex][_shareAddress].stake > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(this); namiToken.transfer(_shareAddress, namiPool[_roundIndex][_shareAddress].stake); // update current Nac pool balance round[_roundIndex].currentNAC = round[_roundIndex].currentNAC.sub(namiPool[_roundIndex][_shareAddress].stake); namiPool[_roundIndex][_shareAddress].stake = 0; assert(previousBalances > namiToken.balanceOf(this)); } // // // withdraw NAC and ETH for top investor // // function withdrawTopForTeam(address _shareAddress, uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isCloseEthPool == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].topWithdrawable); if(namiPool[_roundIndex][_shareAddress].isActive == true) { require(namiPool[_roundIndex][_shareAddress].isWithdrawn == false); assert(round[_roundIndex].finalNAC > namiPool[_roundIndex][_shareAddress].stake); // compute eth for invester uint ethReturn = (round[_roundIndex].ethBalance.mul(namiPool[_roundIndex][_shareAddress].stake)).div(round[_roundIndex].finalNAC); _shareAddress.transfer(ethReturn); // set user withdraw namiPool[_roundIndex][_shareAddress].isWithdrawn = true; emit Withdraw(_shareAddress, _roundIndex, ethReturn, namiPool[_roundIndex][_shareAddress].stake, now); // withdraw NAC _withdrawNAC(_shareAddress, _roundIndex); } } // // // withdraw NAC and ETH for non top investor // execute by admin only // // function withdrawNonTopForTeam(address _shareAddress, uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].withdrawable); if(namiPool[_roundIndex][_shareAddress].isActive == false) { require(namiPool[_roundIndex][_shareAddress].isWithdrawn == false); // set state user withdraw namiPool[_roundIndex][_shareAddress].isWithdrawn = true; emit Withdraw(_shareAddress, _roundIndex, 0, namiPool[_roundIndex][_shareAddress].stake, now); // _withdrawNAC(_shareAddress, _roundIndex); } } // // // withdraw NAC and ETH for top investor // execute by investor // // function withdrawTop(uint _roundIndex) public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isCloseEthPool == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].topWithdrawable); if(namiPool[_roundIndex][msg.sender].isActive == true) { require(namiPool[_roundIndex][msg.sender].isWithdrawn == false); uint ethReturn = (round[_roundIndex].ethBalance.mul(namiPool[_roundIndex][msg.sender].stake)).div(round[_roundIndex].finalNAC); msg.sender.transfer(ethReturn); // set user withdraw namiPool[_roundIndex][msg.sender].isWithdrawn = true; // emit Withdraw(msg.sender, _roundIndex, ethReturn, namiPool[_roundIndex][msg.sender].stake, now); _withdrawNAC(msg.sender, _roundIndex); } } // // // withdraw NAC and ETH for non top investor // execute by investor // // function withdrawNonTop(uint _roundIndex) public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].withdrawable); if(namiPool[_roundIndex][msg.sender].isActive == false) { require(namiPool[_roundIndex][msg.sender].isWithdrawn == false); namiPool[_roundIndex][msg.sender].isWithdrawn = true; // emit Withdraw(msg.sender, _roundIndex, 0, namiPool[_roundIndex][msg.sender].stake, now); _withdrawNAC(msg.sender, _roundIndex); } } } contract NamiCrowdSale { using SafeMath for uint256; /// NAC Broker Presale Token /// @dev Constructor function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; namiPresale = _namiPresale; } /*/ * Constants /*/ string public name = "Nami ICO"; string public symbol = "NAC"; uint public decimals = 18; bool public TRANSFERABLE = false; // default not transferable uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei); uint public binary = 0; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; // nami presale contract address public namiPresale; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; // binary option address address public binaryAddress; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; modifier onlyCrowdsaleManager() { require(msg.sender == crowdsaleManager); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyTranferable() { require(TRANSFERABLE); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); // Log migrate token event LogMigrate(address _from, address _to, uint256 amount); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } // Transfer the balance from owner&#39;s account to another account // only escrow can send token (to send token private sale) function transferForTeam(address _to, uint256 _value) public onlyEscrow { _transfer(msg.sender, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyTranferable { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyTranferable returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyTranferable returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // allows transfer token function changeTransferable () public onlyEscrow { TRANSFERABLE = !TRANSFERABLE; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change binary value function changeBinary(uint _binary) public onlyEscrow { binary = _binary; } // change binary address function changeBinaryAddress(address _binaryAddress) public onlyEscrow { require(_binaryAddress != 0x0); binaryAddress = _binaryAddress; } /* * price in ICO: * first week: 1 ETH = 2400 NAC * second week: 1 ETH = 23000 NAC * 3rd week: 1 ETH = 2200 NAC * 4th week: 1 ETH = 2100 NAC * 5th week: 1 ETH = 2000 NAC * 6th week: 1 ETH = 1900 NAC * 7th week: 1 ETH = 1800 NAC * 8th week: 1 ETH = 1700 nac * time: * 1517443200: Thursday, February 1, 2018 12:00:00 AM * 1518048000: Thursday, February 8, 2018 12:00:00 AM * 1518652800: Thursday, February 15, 2018 12:00:00 AM * 1519257600: Thursday, February 22, 2018 12:00:00 AM * 1519862400: Thursday, March 1, 2018 12:00:00 AM * 1520467200: Thursday, March 8, 2018 12:00:00 AM * 1521072000: Thursday, March 15, 2018 12:00:00 AM * 1521676800: Thursday, March 22, 2018 12:00:00 AM * 1522281600: Thursday, March 29, 2018 12:00:00 AM */ function getPrice() public view returns (uint price) { if (now < 1517443200) { // presale return 3450; } else if (1517443200 < now && now <= 1518048000) { // 1st week return 2400; } else if (1518048000 < now && now <= 1518652800) { // 2nd week return 2300; } else if (1518652800 < now && now <= 1519257600) { // 3rd week return 2200; } else if (1519257600 < now && now <= 1519862400) { // 4th week return 2100; } else if (1519862400 < now && now <= 1520467200) { // 5th week return 2000; } else if (1520467200 < now && now <= 1521072000) { // 6th week return 1900; } else if (1521072000 < now && now <= 1521676800) { // 7th week return 1800; } else if (1521676800 < now && now <= 1522281600) { // 8th week return 1700; } else { return binary; } } function() payable public { buy(msg.sender); } function buy(address _buyer) payable public { // Available only if presale is running. require(currentPhase == Phase.Running); // require ICO time or binary option require(now <= 1522281600 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); // add new token to buyer balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); // add new token to totalSupply totalSupply = totalSupply.add(newTokens); emit LogBuy(_buyer,newTokens); emit Transfer(this,_buyer,newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase require(currentPhase == Phase.Migrating); uint tokens = balanceOf[_owner]; require(tokens != 0); balanceOf[_owner] = 0; totalSupply -= tokens; emit LogBurn(_owner, tokens); emit Transfer(_owner, crowdsaleManager, tokens); // Automatically switch phase when migration is done. if (totalSupply == 0) { currentPhase = Phase.Migrated; emit LogPhaseSwitch(Phase.Migrated); } } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyEscrow { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); require(canSwitchPhase); currentPhase = _nextPhase; emit LogPhaseSwitch(_nextPhase); } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } function setCrowdsaleManager(address _mgr) public onlyEscrow { // You can&#39;t change crowdsale contract when migration is in progress. require(currentPhase != Phase.Migrating); crowdsaleManager = _mgr; } // internal migrate migration tokens function _migrateToken(address _from, address _to) internal { PresaleToken presale = PresaleToken(namiPresale); uint256 newToken = presale.balanceOf(_from); require(newToken > 0); // burn old token presale.burnTokens(_from); // add new token to _to balanceOf[_to] = balanceOf[_to].add(newToken); // add new token to totalSupply totalSupply = totalSupply.add(newToken); emit LogMigrate(_from, _to, newToken); emit Transfer(this,_to,newToken); } // migate token function for Nami Team function migrateToken(address _from, address _to) public onlyEscrow { _migrateToken(_from, _to); } // migrate token for investor function migrateForInvestor() public { _migrateToken(msg.sender, msg.sender); } // Nami internal exchange // event for Nami exchange event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller); event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price); /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackExchange` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackExchange` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _price price to sell token. */ function transferToExchange(address _to, uint _value, uint _price) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackExchange(msg.sender, _value, _price); emit TransferToExchange(msg.sender, _to, _value, _price); } } /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackBuyer` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackBuyer` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _buyer address of seller. */ function transferToBuyer(address _to, uint _value, address _buyer) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackBuyer(msg.sender, _value, _buyer); emit TransferToBuyer(msg.sender, _to, _value, _buyer); } } //------------------------------------------------------------------------------------------------------- } /* * Binary option smart contract------------------------------- */ contract BinaryOption { /* * binary option controled by escrow to buy NAC with good price */ // NamiCrowdSale address address public namiCrowdSaleAddr; address public escrow; // namiMultiSigWallet address public namiMultiSigWallet; Session public session; uint public timeInvestInMinute = 15; uint public timeOneSession = 20; uint public sessionId = 1; uint public rateWin = 100; uint public rateLoss = 20; uint public rateFee = 5; uint public constant MAX_INVESTOR = 20; uint public minimunEth = 10000000000000000; // minimunEth = 0.01 eth /** * Events for binany option system */ event SessionOpen(uint timeOpen, uint indexed sessionId); event InvestClose(uint timeInvestClose, uint priceOpen, uint indexed sessionId); event Invest(address indexed investor, bool choose, uint amount, uint timeInvest, uint indexed sessionId); event SessionClose(uint timeClose, uint indexed sessionId, uint priceClose, uint nacPrice, uint rateWin, uint rateLoss, uint rateFee); event Deposit(address indexed sender, uint value); /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } // there is only one session available at one timeOpen // priceOpen is price of ETH in USD // priceClose is price of ETH in USD // process of one Session // 1st: escrow reset session by run resetSession() // 2nd: escrow open session by run openSession() => save timeOpen at this time // 3rd: all investor can invest by run invest(), send minimum 0.1 ETH // 4th: escrow close invest and insert price open for this Session // 5th: escrow close session and send NAC for investor struct Session { uint priceOpen; uint priceClose; uint timeOpen; bool isReset; bool isOpen; bool investOpen; uint investorCount; mapping(uint => address) investor; mapping(uint => bool) win; mapping(uint => uint) amountInvest; } function BinaryOption(address _namiCrowdSale, address _escrow, address _namiMultiSigWallet) public { require(_namiCrowdSale != 0x0 && _escrow != 0x0); namiCrowdSaleAddr = _namiCrowdSale; escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; } modifier onlyEscrow() { require(msg.sender==escrow); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // chagne minimunEth function changeMinEth(uint _minimunEth) public onlyEscrow { require(_minimunEth != 0); minimunEth = _minimunEth; } /// @dev Change time for investor can invest in one session, can only change at time not in session /// @param _timeInvest time invest in minutes ///---------------------------change time function------------------------------ function changeTimeInvest(uint _timeInvest) public onlyEscrow { require(!session.isOpen && _timeInvest < timeOneSession); timeInvestInMinute = _timeInvest; } function changeTimeOneSession(uint _timeOneSession) public onlyEscrow { require(!session.isOpen && _timeOneSession > timeInvestInMinute); timeOneSession = _timeOneSession; } /////------------------------change rate function------------------------------- function changeRateWin(uint _rateWin) public onlyEscrow { require(!session.isOpen); rateWin = _rateWin; } function changeRateLoss(uint _rateLoss) public onlyEscrow { require(!session.isOpen); rateLoss = _rateLoss; } function changeRateFee(uint _rateFee) public onlyEscrow { require(!session.isOpen); rateFee = _rateFee; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev safe withdraw Ether to one of owner of nami multisignature wallet /// @param _withdraw address to withdraw function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } // @dev Returns list of owners. // @return List of owner addresses. // MAX_INVESTOR = 20 function getInvestors() public view returns (address[20]) { address[20] memory listInvestor; for (uint i = 0; i < MAX_INVESTOR; i++) { listInvestor[i] = session.investor[i]; } return listInvestor; } function getChooses() public view returns (bool[20]) { bool[20] memory listChooses; for (uint i = 0; i < MAX_INVESTOR; i++) { listChooses[i] = session.win[i]; } return listChooses; } function getAmount() public view returns (uint[20]) { uint[20] memory listAmount; for (uint i = 0; i < MAX_INVESTOR; i++) { listAmount[i] = session.amountInvest[i]; } return listAmount; } /// @dev reset all data of previous session, must run before open new session // only escrow can call function resetSession() public onlyEscrow { require(!session.isReset && !session.isOpen); session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.isOpen = false; session.investOpen = false; session.investorCount = 0; for (uint i = 0; i < MAX_INVESTOR; i++) { session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } } /// @dev Open new session, only escrow can call function openSession () public onlyEscrow { require(session.isReset && !session.isOpen); session.isReset = false; // open invest session.investOpen = true; session.timeOpen = now; session.isOpen = true; emit SessionOpen(now, sessionId); } /// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session /// @param _choose choise of investor, true is call, false is put function invest (bool _choose) public payable { require(msg.value >= minimunEth && session.investOpen); // msg.value >= 0.1 ether require(now < (session.timeOpen + timeInvestInMinute * 1 minutes)); require(session.investorCount < MAX_INVESTOR); session.investor[session.investorCount] = msg.sender; session.win[session.investorCount] = _choose; session.amountInvest[session.investorCount] = msg.value; session.investorCount += 1; emit Invest(msg.sender, _choose, msg.value, now, sessionId); } /// @dev close invest for escrow /// @param _priceOpen price ETH in USD function closeInvest (uint _priceOpen) public onlyEscrow { require(_priceOpen != 0 && session.investOpen); require(now > (session.timeOpen + timeInvestInMinute * 1 minutes)); session.investOpen = false; session.priceOpen = _priceOpen; emit InvestClose(now, _priceOpen, sessionId); } /// @dev get amount of ether to buy NAC for investor /// @param _ether amount ether which investor invest /// @param _status true for investor win and false for investor loss function getEtherToBuy (uint _ether, bool _status) public view returns (uint) { if (_status) { return _ether * rateWin / 100; } else { return _ether * rateLoss / 100; } } /// @dev close session, only escrow can call /// @param _priceClose price of ETH in USD function closeSession (uint _priceClose) public onlyEscrow { require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes)); require(!session.investOpen && session.isOpen); session.priceClose = _priceClose; bool result = (_priceClose>session.priceOpen)?true:false; uint etherToBuy; NamiCrowdSale namiContract = NamiCrowdSale(namiCrowdSaleAddr); uint price = namiContract.getPrice(); require(price != 0); for (uint i = 0; i < session.investorCount; i++) { if (session.win[i]==result) { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateWin / 100; uint etherReturn = session.amountInvest[i] - session.amountInvest[i] * rateFee / 100; (session.investor[i]).transfer(etherReturn); } else { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateLoss / 100; } namiContract.buy.value(etherToBuy)(session.investor[i]); // reset investor session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } session.isOpen = false; emit SessionClose(now, sessionId, _priceClose, price, rateWin, rateLoss, rateFee); sessionId += 1; // require(!session.isReset && !session.isOpen); // reset state session session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.investOpen = false; session.investorCount = 0; } } /* * Binary option smart contract NAC to ETH------------------------------- */ contract BinaryOptionV2 { using SafeMath for uint256; /* * binary option controled by escrow to buy NAC with good price */ // NamiCrowdSale address address public NamiAddr; address public escrow; // namiMultiSigWallet address public namiMultiSigWallet; Session public session; uint public timeInvestInMinute = 15; uint public timeOneSession = 20; uint public sessionId = 1; uint public rateWin = 200; uint public rateLoss = 0; uint public rateFee = 5; uint public constant MAX_INVESTOR = 20; uint public minNac = 100000000000000000000; // 100 Nac uint public totalFci = 0; uint public totalNacInPool = 0; bool isEmptyPool = true; bool public isTradableFciInSession = false; /** * Events for binany option system */ event SessionOpen(uint timeOpen, uint indexed sessionId); event InvestClose(uint timeInvestClose, uint priceOpen, uint indexed sessionId); event Invest(address indexed investor, uint choose, uint amount, uint timeInvest, uint indexed sessionId); event InvestToPool(address indexed investor, uint amount, uint timeInvest); event SessionClose(uint timeClose, uint indexed sessionId, uint priceClose, uint rateWin, uint rateLoss, uint rateFee); event Deposit(address indexed sender, uint value); /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } // there is only one session available at one timeOpen // priceOpen is price of ETH in USD // priceClose is price of ETH in USD // process of one Session // 1st: escrow reset session by run resetSession() // 2nd: escrow open session by run openSession() => save timeOpen at this time // 3rd: all investor can invest by run invest(), send minimum 0.1 ETH // 4th: escrow close invest and insert price open for this Session // 5th: escrow close session and send NAC for investor struct Session { uint priceOpen; uint priceClose; uint timeOpen; bool isReset; bool isOpen; bool investOpen; uint investorCount; mapping(uint => address) investor; mapping(uint => uint) win; mapping(uint => uint) amountInvest; } // list fci mapping(address => uint) public fci; function BinaryOptionV2(address _namiCrowdSale, address _escrow, address _namiMultiSigWallet) public { require(_namiCrowdSale != 0x0 && _escrow != 0x0); NamiAddr = _namiCrowdSale; escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; } modifier onlyEscrow() { require(msg.sender==escrow); _; } modifier onlyNami { require(msg.sender == NamiAddr); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change minimum nac in one order function changeMinNac(uint _minNAC) public onlyEscrow { require(_minNAC != 0); minNac = _minNAC; } /// @dev Change time for investor can invest in one session, can only change at time not in session /// @param _timeInvest time invest in minutes ///---------------------------change time function------------------------------ function changeTimeInvest(uint _timeInvest) public onlyEscrow { require(!session.isOpen && _timeInvest < timeOneSession); timeInvestInMinute = _timeInvest; } function changeTimeOneSession(uint _timeOneSession) public onlyEscrow { require(!session.isOpen && _timeOneSession > timeInvestInMinute); timeOneSession = _timeOneSession; } function changeTradableFciInSession(bool _isTradableFciInPool) public onlyEscrow { isTradableFciInSession = _isTradableFciInPool; } /////------------------------change rate function------------------------------- function changeRateWin(uint _rateWin) public onlyEscrow { require(!session.isOpen); rateWin = _rateWin; } function changeRateLoss(uint _rateLoss) public onlyEscrow { require(!session.isOpen); rateLoss = _rateLoss; } function changeRateFee(uint _rateFee) public onlyEscrow { require(!session.isOpen); rateFee = _rateFee; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (address(this).balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev withdraw NAC to nami multisignature wallet, only escrow can call /// @param _amount value NAC to withdraw function withdrawNac(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); if (namiToken.balanceOf(address(this)) > 0) { namiToken.transfer(namiMultiSigWallet, _amount); } } /// @dev safe withdraw Ether to one of owner of nami multisignature wallet /// @param _withdraw address to withdraw function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } // @dev Returns list of owners. // @return List of owner addresses. // MAX_INVESTOR = 20 function getInvestors() public view returns (address[20]) { address[20] memory listInvestor; for (uint i = 0; i < MAX_INVESTOR; i++) { listInvestor[i] = session.investor[i]; } return listInvestor; } function getChooses() public view returns (uint[20]) { uint[20] memory listChooses; for (uint i = 0; i < MAX_INVESTOR; i++) { listChooses[i] = session.win[i]; } return listChooses; } function getAmount() public view returns (uint[20]) { uint[20] memory listAmount; for (uint i = 0; i < MAX_INVESTOR; i++) { listAmount[i] = session.amountInvest[i]; } return listAmount; } /// @dev reset all data of previous session, must run before open new session // only escrow can call function resetSession() public onlyEscrow { require(!session.isReset && !session.isOpen); session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.isOpen = false; session.investOpen = false; session.investorCount = 0; for (uint i = 0; i < MAX_INVESTOR; i++) { session.investor[i] = 0x0; session.win[i] = 0; session.amountInvest[i] = 0; } } /// @dev Open new session, only escrow can call function openSession () public onlyEscrow { NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); require(namiToken.balanceOf(address(this)) > 0); require(session.isReset && !session.isOpen); session.isReset = false; // open invest session.investOpen = true; session.timeOpen = now; session.isOpen = true; emit SessionOpen(now, sessionId); } function setPoolStatus() public onlyEscrow { NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); if(namiToken.balanceOf(address(this)) == 0) { isEmptyPool = true; } else { isEmptyPool = false; } } /// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session /// @param _choose choise of investor, true is call, false is put // function invest (bool _choose) // public // payable // { // require(msg.value >= minimunEth && session.investOpen); // msg.value >= 0.1 ether // require(now < (session.timeOpen + timeInvestInMinute * 1 minutes)); // require(session.investorCount < MAX_INVESTOR); // session.investor[session.investorCount] = msg.sender; // session.win[session.investorCount] = _choose; // session.amountInvest[session.investorCount] = msg.value; // session.investorCount += 1; // Invest(msg.sender, _choose, msg.value, now, sessionId); // } // ------------------------------------------------ /// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session /// @param _choose choise of investor, true is call, false is put function tokenFallbackExchange(address _from, uint _value, uint _choose) onlyNami public returns (bool success) { if(_choose < 2) { require(_value >= minNac && session.investOpen); // msg.value >= 0.1 ether require(now < (session.timeOpen + timeInvestInMinute * 1 minutes)); require(session.investorCount < MAX_INVESTOR); // session.investor[session.investorCount] = _from; session.win[session.investorCount] = _choose; session.amountInvest[session.investorCount] = _value; session.investorCount += 1; emit Invest(_from, _choose, _value, now, sessionId); } else { require(_choose==2 && _value > 0); bool check = (!session.isOpen) || isTradableFciInSession; require(check); // check pool empty if(isEmptyPool==true) { fci[_from] = (fci[_from]).add(_value); totalNacInPool = totalNacInPool.add(_value); totalFci = totalFci.add(_value); if(totalNacInPool > 0) { isEmptyPool = false; } } else { uint fciReceive = (_value.mul(totalFci)).div(totalNacInPool); // check fci receive require(fciReceive > 0); fci[_from] = fci[_from].add(fciReceive); totalNacInPool = totalNacInPool.add(_value); totalFci = totalFci.add(fciReceive); if(totalNacInPool > 0) { isEmptyPool = false; } } // add shareHolder // uint fciReceive = emit InvestToPool(_from, _value, now); } return true; } // sell fci and receive NAC back function sellFci(uint _amount) public { bool check = (!session.isOpen) || isTradableFciInSession; require(check && fci[msg.sender] >= _amount); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); require(namiToken.balanceOf(address(this)) > 0 && totalNacInPool > 0); uint nacReceive = (_amount.mul(totalNacInPool)).div(totalFci); // check nac receive require(nacReceive > 0); fci[msg.sender] = fci[msg.sender].sub(_amount); totalFci = totalFci.sub(_amount); namiToken.transfer(msg.sender, nacReceive); totalNacInPool = totalNacInPool.sub(nacReceive); if(totalNacInPool == 0) { isEmptyPool = true; } } /// @dev close invest for escrow /// @param _priceOpen price ETH in USD function closeInvest (uint _priceOpen) public onlyEscrow { require(_priceOpen != 0 && session.investOpen); require(now > (session.timeOpen + timeInvestInMinute * 1 minutes)); session.investOpen = false; session.priceOpen = _priceOpen; emit InvestClose(now, _priceOpen, sessionId); } /// @dev close session, only escrow can call /// @param _priceClose price of ETH in USD function closeSession (uint _priceClose) public onlyEscrow { require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes)); require(!session.investOpen && session.isOpen); session.priceClose = _priceClose; uint result = (_priceClose>session.priceOpen)?1:0; NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint nacReturn; // uint price = namiToken.getPrice(); // require(price != 0); for (uint i = 0; i < session.investorCount; i++) { if (session.win[i]==result) { // etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateWin / 100; // uint etherReturn = session.amountInvest[i] - session.amountInvest[i] * rateFee / 100; // (session.investor[i]).transfer(etherReturn); nacReturn = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateWin / 100; require(namiToken.balanceOf(address(this)) >= nacReturn); namiToken.transfer(session.investor[i], nacReturn); totalNacInPool = totalNacInPool.sub(nacReturn.sub(session.amountInvest[i])); } else { if(rateLoss > 0) { nacReturn = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateLoss / 100; require(namiToken.balanceOf(address(this)) >= nacReturn); namiToken.transfer(session.investor[i], nacReturn); totalNacInPool = totalNacInPool.add(session.amountInvest[i].sub(nacReturn)); } else { totalNacInPool = totalNacInPool.add(session.amountInvest[i]); } } // namiToken.buy.value(etherToBuy)(session.investor[i]); // reset investor session.investor[i] = 0x0; session.win[i] = 0; session.amountInvest[i] = 0; } session.isOpen = false; emit SessionClose(now, sessionId, _priceClose, rateWin, rateLoss, rateFee); sessionId += 1; // require(!session.isReset && !session.isOpen); // reset state session session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.investOpen = false; session.investorCount = 0; } } contract PresaleToken { mapping (address => uint256) public balanceOf; function burnTokens(address _owner) public; } /* * Contract that is working with ERC223 tokens */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success); function tokenFallbackBuyer(address _from, uint _value, address _buyer) public returns (bool success); function tokenFallbackExchange(address _from, uint _value, uint _price) public returns (bool success); } /* * Nami Internal Exchange smartcontract----------------------------------------------------------------- * */ contract NamiExchange { using SafeMath for uint; function NamiExchange(address _namiAddress) public { NamiAddr = _namiAddress; } event UpdateBid(address owner, uint price, uint balance); event UpdateAsk(address owner, uint price, uint volume); event BuyHistory(address indexed buyer, address indexed seller, uint price, uint volume, uint time); event SellHistory(address indexed seller, address indexed buyer, uint price, uint volume, uint time); mapping(address => OrderBid) public bid; mapping(address => OrderAsk) public ask; string public name = "NacExchange"; /// address of Nami token address public NamiAddr; /// price of Nac = ETH/NAC uint public price = 1; // struct store order of user struct OrderBid { uint price; uint eth; } struct OrderAsk { uint price; uint volume; } // prevent lost ether function() payable public { require(msg.data.length != 0); require(msg.value == 0); } modifier onlyNami { require(msg.sender == NamiAddr); _; } ///////////////// //---------------------------function about bid Order----------------------------------------------------------- function placeBuyOrder(uint _price) payable public { require(_price > 0 && msg.value > 0 && bid[msg.sender].eth == 0); if (msg.value > 0) { bid[msg.sender].eth = (bid[msg.sender].eth).add(msg.value); bid[msg.sender].price = _price; emit UpdateBid(msg.sender, _price, bid[msg.sender].eth); } } function sellNac(uint _value, address _buyer, uint _price) public returns (bool success) { require(_price == bid[_buyer].price && _buyer != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint ethOfBuyer = bid[_buyer].eth; uint maxToken = ethOfBuyer.mul(bid[_buyer].price); require(namiToken.allowance(msg.sender, this) >= _value && _value > 0 && ethOfBuyer != 0 && _buyer != 0x0); if (_value > maxToken) { if (msg.sender.send(ethOfBuyer) && namiToken.transferFrom(msg.sender,_buyer,maxToken)) { // update order bid[_buyer].eth = 0; emit UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); emit BuyHistory(_buyer, msg.sender, bid[_buyer].price, maxToken, now); return true; } else { // revert anything revert(); } } else { uint eth = _value.div(bid[_buyer].price); if (msg.sender.send(eth) && namiToken.transferFrom(msg.sender,_buyer,_value)) { // update order bid[_buyer].eth = (bid[_buyer].eth).sub(eth); emit UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); emit BuyHistory(_buyer, msg.sender, bid[_buyer].price, _value, now); return true; } else { // revert anything revert(); } } } function closeBidOrder() public { require(bid[msg.sender].eth > 0 && bid[msg.sender].price > 0); // transfer ETH msg.sender.transfer(bid[msg.sender].eth); // update order bid[msg.sender].eth = 0; emit UpdateBid(msg.sender, bid[msg.sender].price, bid[msg.sender].eth); } //////////////// //---------------------------function about ask Order----------------------------------------------------------- // place ask order by send NAC to Nami Exchange contract // this function place sell order function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { require(_price > 0 && _value > 0 && ask[_from].volume == 0); if (_value > 0) { ask[_from].volume = (ask[_from].volume).add(_value); ask[_from].price = _price; emit UpdateAsk(_from, _price, ask[_from].volume); } return true; } function closeAskOrder() public { require(ask[msg.sender].volume > 0 && ask[msg.sender].price > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(msg.sender); // transfer token namiToken.transfer(msg.sender, ask[msg.sender].volume); // update order ask[msg.sender].volume = 0; emit UpdateAsk(msg.sender, ask[msg.sender].price, 0); // check balance assert(previousBalances < namiToken.balanceOf(msg.sender)); } function buyNac(address _seller, uint _price) payable public returns (bool success) { require(msg.value > 0 && ask[_seller].volume > 0 && ask[_seller].price > 0); require(_price == ask[_seller].price && _seller != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint maxEth = (ask[_seller].volume).div(ask[_seller].price); uint previousBalances = namiToken.balanceOf(msg.sender); if (msg.value > maxEth) { if (_seller.send(maxEth) && msg.sender.send(msg.value.sub(maxEth))) { // transfer token namiToken.transfer(msg.sender, ask[_seller].volume); emit SellHistory(_seller, msg.sender, ask[_seller].price, ask[_seller].volume, now); // update order ask[_seller].volume = 0; emit UpdateAsk(_seller, ask[_seller].price, 0); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } else { uint nac = (msg.value).mul(ask[_seller].price); if (_seller.send(msg.value)) { // transfer token namiToken.transfer(msg.sender, nac); // update order ask[_seller].volume = (ask[_seller].volume).sub(nac); emit UpdateAsk(_seller, ask[_seller].price, ask[_seller].volume); emit SellHistory(_seller, msg.sender, ask[_seller].price, nac, now); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } } } contract ERC23 { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public returns (bool success); } /* * NamiMultiSigWallet smart contract------------------------------- */ /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. contract NamiMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function NamiMultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { // Transaction tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } }
close invest for escrow _priceOpen price ETH in USD
function closeInvest (uint _priceOpen) public onlyEscrow { require(_priceOpen != 0 && session.investOpen); require(now > (session.timeOpen + timeInvestInMinute * 1 minutes)); session.investOpen = false; session.priceOpen = _priceOpen; emit InvestClose(now, _priceOpen, sessionId); }
7,913,906
pragma solidity ^0.5.0; import "./UsingTellor.sol"; /** * @title Optimistic * This contracts allows users to use Tellor as a fallback oracle. It allows two parties to centrally * enter the data used to settle a contract but allows either party to dispute the data. If a dispute is * initiated their contract will settle to Tellor's value. */ contract Optimistic is UsingTellor { mapping(uint256 => bool) public isValue; //mapping for timestamp to bool where it's true if the value as been set mapping(uint256 => uint256) valuesByTimestamp; //mapping of timestamp to value mapping(uint256 => bool) public disputedValues; //maping of timestamp to bool where it's true if the value has been disputed mapping(uint256 => uint256[]) public requestIdsIncluded; //mapping of timestamp to requestsId's to include // struct infoForTimestamp { // bool isValue; // uint valuesByTimestamp; // bool disputedValues; // uint[] requestIdsIncluded; // } // mapping(uint => infoForTimestamp) public infoForTimestamps;//mapping timestampt to InfoForTimestamp struct uint256[] timestamps; //timestamps with values uint256[] requestIds; uint256[] disputedValuesArray; uint256 public granularity; uint256 public disputeFee; //In Tributes uint256 public disputePeriod; event NewValueSet(uint256 indexed _timestamp, uint256 _value); event ValueDisputed(address _disputer, uint256 _timestamp, uint256 _value); event TellorValuePlaced(uint256 _timestamp, uint256 _value); /*Constructor*/ /** * @dev This constructor function is used to pass variables to the UserContract's constructor and set several variables * the variables for the Optimistic.sol constructor come for the Reader.Constructor function. * @param _userContract address for UserContract * @param _disputeFeeRequired the fee to dispute the optimistic price(price sumbitted by known trusted party) * @param _disputePeriod is the time frame a value can be disputed after being imputed * @param _requestIds are the requests Id's on the Tellor System corresponding to the data types used on this contract. * It is recommended to use several requestId's that pull from several API's. If requestsId's don't exist in the Tellor * System be sure to create some. * @param _granularity is the amount of decimals desired on the requested value */ constructor(address _userContract, uint256 _disputeFeeRequired, uint256 _disputePeriod, uint256[] memory _requestIds, uint256 _granularity) public UsingTellor(_userContract) { disputeFee = _disputeFeeRequired; disputePeriod = _disputePeriod; granularity = _granularity; requestIds = _requestIds; } /*Functions*/ /** * @dev allows contract owner, a centralized party to enter value * @param _timestamp is the timestamp for the value * @param _value is the value for the timestamp specified */ function setValue(uint256 _timestamp, uint256 _value) external { //Only allows owner to set value require(msg.sender == owner, "Sender is not owner"); //Checks that no value has already been set for the timestamp require(getIsValue(_timestamp) == false, "Timestamp is already set"); //sets timestamp valuesByTimestamp[_timestamp] = _value; //sets isValue to true once value is set isValue[_timestamp] = true; //adds timestamp to the timestamps array timestamps.push(_timestamp); //lets the network know a new timestamp and value have been added emit NewValueSet(_timestamp, _value); } /** * @dev allows user to initiate dispute on the value of the specified timestamp * @param _timestamp is the timestamp for the value to be disputed */ function disputeOptimisticValue(uint256 _timestamp) external payable { require(msg.value >= disputeFee, "Value is below dispute fee"); //require that isValue for the timestamp being disputed to exist/be true require(isValue[_timestamp], "Value for the timestamp being disputed doesn't exist"); // assert disputePeriod is still open require(now - (now % granularity) <= _timestamp + disputePeriod, "Dispute period is closed"); //set the disputValues for the disputed timestamp to true disputedValues[_timestamp] = true; //add the disputed timestamp to the diputedValues array disputedValuesArray.push(_timestamp); emit ValueDisputed(msg.sender, _timestamp, valuesByTimestamp[_timestamp]); } /** * @dev This function gets the Tellor requestIds values for the disputed timestamp. It averages the values on the * requestsIds and replaces the value set by the contract owner, centralized party. * @param _timestamp to get Tellor data from * @return uint of new value and true if it was able to get Tellor data */ function getTellorValues(uint256 _timestamp) public returns (uint256 _value, bool _didGet) { //We need to get the tellor value within the granularity. If no Tellor value is available...what then? Simply put no Value? //No basically, the dispute period for anyValue is within the granularity TellorMaster _tellor = TellorMaster(tellorUserContract.tellorStorageAddress()); Tellor _tellorCore = Tellor(tellorUserContract.tellorStorageAddress()); uint256 _retrievedTimestamp; uint256 _initialBalance = _tellor.balanceOf(address(this)); //Checks the balance of Tellor Tributes on this contract //Loops through all the Tellor requestsId's initially(in the constructor) associated with this contract data for (uint256 i = 1; i <= requestIds.length; i++) { //Get all values for that requestIds' timestamp //Check if any is after your given timestamp //If yes, return that value. If no, then request that Id (_didGet, _value, _retrievedTimestamp) = getFirstVerifiedDataAfter(i, _timestamp); if (_didGet) { uint256 _newTime = _retrievedTimestamp - (_retrievedTimestamp % granularity); //why are we using the mod granularity??? //provides the average of the requests Ids' associated with this price feed uint256 _newValue = (_value + valuesByTimestamp[_newTime] * requestIdsIncluded[_newTime].length) / (requestIdsIncluded[_newTime].length + 1); //Add the new timestamp and value (we don't replace???) valuesByTimestamp[_newTime] = _newValue; emit TellorValuePlaced(_newTime, _newValue); //records the requests Ids included on the price average where all prices came from Tellor requests Ids requestIdsIncluded[_newTime].push(i); //how do we make sure it's not called twice? //if the value for the newTime does not exist, then push the value, update the isValue to true //otherwise if the newTime is under dsipute then update the dispute status to false // ??? should the else be an "and" if (isValue[_newTime] == false) { timestamps.push(_newTime); isValue[_newTime] = true; emit NewValueSet(_newTime, _value); } else if (disputedValues[_newTime] == true) { disputedValues[_newTime] = false; } //otherwise request the ID and split the contracts initial tributes balance to equally tip all //requests Ids associated with this price feed } else if (_tellor.balanceOf(address(this)) > requestIds.length) { //Request Id to be mined by adding to it's tip _tellorCore.addTip(i, _initialBalance / requestIds.length); } } } /** * @dev Allows the contract owner(Tellor) to withdraw ETH from this contract */ function withdrawETH() external { require(msg.sender == owner, "Sender is not owner"); address(owner).transfer(address(this).balance); } /** * @dev Get the first undisputed value after the timestamp specified. This function is used within the getTellorValues * but can be used on its own. * @param _timestamp to search the first undisputed value there after */ function getFirstUndisputedValueAfter(uint256 _timestamp) public view returns (bool, uint256, uint256 _timestampRetrieved) { uint256 _count = timestamps.length; if (_count > 0) { for (uint256 i = _count; i > 0; i--) { if (timestamps[i - 1] >= _timestamp && disputedValues[timestamps[i - 1]] == false) { _timestampRetrieved = timestamps[i - 1]; } } if (_timestampRetrieved > 0) { return (true, getMyValuesByTimestamp(_timestampRetrieved), _timestampRetrieved); } } return (false, 0, 0); } /*Getters*/ /** * @dev Getter function for the value based on the timestamp specified * @param _timestamp to retreive value from */ function getMyValuesByTimestamp(uint256 _timestamp) public view returns (uint256 value) { return valuesByTimestamp[_timestamp]; } /** * @dev Getter function for the number of RequestIds associated with a timestamp, based on the timestamp specified * @param _timestamp to retreive number of requestIds * @return uint count of number of values for the spedified timestamp */ function getNumberOfValuesPerTimestamp(uint256 _timestamp) external view returns (uint256) { return requestIdsIncluded[_timestamp].length; } /** * @dev Checks to if a value exists for the specifived timestamp * @param _timestamp to verify * @return ture if it exists */ function getIsValue(uint256 _timestamp) public view returns (bool) { return isValue[_timestamp]; } /** * @dev Getter function for latest value available * @return latest value available */ function getCurrentValue() external view returns (uint256) { require(timestamps.length > 0, "Timestamps' length is 0"); return getMyValuesByTimestamp(timestamps[timestamps.length - 1]); } /** * @dev Getter function for the timestamps available * @return uint array of timestamps available */ function getTimestamps() external view returns (uint256[] memory) { return timestamps; } /** * @dev Getter function for the requests Ids' from Tellor associated with this price feed * @return uint array of requests Ids' */ function getRequestIds() external view returns (uint256[] memory) { return requestIds; } /** * @dev Getter function for the requests Ids' from Tellor associated with this price feed * at the specified timestamp. This only gets populated after a dispute is initiated and the * function getTellorValues is ran. * @param _timestamp to retreive the requestIds * @return uint array of requests Ids' included in the calcluation of the value */ function getRequestIdsIncluded(uint256 _timestamp) external view returns (uint256[] memory) { return requestIdsIncluded[_timestamp]; } /** * @dev Getter function for the number of disputed values * @return uint count of number of values for the spedified timestamp */ function getNumberOfDisputedValues() external view returns (uint256) { return disputedValuesArray.length; } /** * @dev Getter function for all disputed values * @return the array with all values under dispute */ function getDisputedValues() external view returns (uint256[] memory) { return disputedValuesArray; } /** * @dev This checks if the value for the specified timestamp is under dispute * @param _timestamp to check if it is under dispute * @return true if it is under dispute */ function isDisputed(uint256 _timestamp) external view returns (bool) { return disputedValues[_timestamp]; } /** * @dev Getter function for the dispute value by index * @return the value */ function getDisputedValueByIndex(uint256 _index) external view returns (uint256) { return disputedValuesArray[_index]; } }
Get the first undisputed value after the timestamp specified. This function is used within the getTellorValues but can be used on its own. _timestamp to search the first undisputed value there after/
function getFirstUndisputedValueAfter(uint256 _timestamp) public view returns (bool, uint256, uint256 _timestampRetrieved) { uint256 _count = timestamps.length; if (_count > 0) { for (uint256 i = _count; i > 0; i--) { if (timestamps[i - 1] >= _timestamp && disputedValues[timestamps[i - 1]] == false) { _timestampRetrieved = timestamps[i - 1]; } } if (_timestampRetrieved > 0) { return (true, getMyValuesByTimestamp(_timestampRetrieved), _timestampRetrieved); } } return (false, 0, 0); }
12,965,503
pragma solidity ^0.4.24; // File: contracts/math/SafeMath.sol /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT license. * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return 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; } } // File: contracts/ownership/Ownable.sol /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT license. * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE */ /** * @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. */ 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 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/token/ERC20/ERC20Interface.sol /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT license. * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE */ /** * @title * @dev */ contract ERC20Interface { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/ERC20/ERC20Standard.sol /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT license. * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE */ /** * @title * @dev */ contract ERC20Standard is ERC20Interface { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 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) external returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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) external 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 * * To avoid this issue, allowances are only allowed to be changed between zero and non-zero. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) external returns (bool) { require(allowed[msg.sender][_spender] == 0 || _value == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev total number of tokens in existence */ function totalSupply() external view returns (uint256) { return totalSupply_; } /** * @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) external view returns (uint256 balance) { 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) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) external 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, uint _subtractedValue) external returns (bool) { uint 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: contracts/token/ERC223/ERC223Interface.sol /** * Released under the MIT license. * https://github.com/Dexaran/ERC223-token-standard/blob/master/LICENSE */ contract ERC223Interface { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transfer(address to, uint256 value, bytes data) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/token/ERC223/ERC223ReceivingContract.sol /** * Released under the MIT license. * https://github.com/Dexaran/ERC223-token-standard/blob/master/LICENSE */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public; } // File: contracts/token/ERC223/ERC223Standard.sol /** * Released under the MIT license. * https://github.com/Dexaran/ERC223-token-standard/blob/master/LICENSE */ /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223Standard is ERC223Interface, ERC20Standard { using SafeMath for uint256; /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint256 _value, bytes _data) external returns(bool){ // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value); } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) external returns(bool){ uint256 codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } emit Transfer(msg.sender, _to, _value); return true; } } // File: contracts/token/extentions/MintableToken.sol /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT license. * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE */ /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is ERC223Standard, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner 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: contracts/DAICOVO/TokenController.sol /// @title A controller that manages permissions to mint specific ERC20/ERC223 token. /// @author ICOVO AG /// @dev The target must be a mintable ERC20/ERC223 and also be set its ownership /// to this controller. It changes permissions in each 3 phases - before the /// token-sale, during the token-sale and after the token-sale. /// /// Before the token-sale (State = Init): /// Only the owner of this contract has a permission to mint tokens. /// During the token-sale (State = Tokensale): /// Only the token-sale contract has a permission to mint tokens. /// After the token-sale (State = Public): /// Nobody has any permissions. Will be expand in the future: contract TokenController is Ownable { using SafeMath for uint256; MintableToken public targetToken; address public votingAddr; address public tokensaleManagerAddr; State public state; enum State { Init, Tokensale, Public } /// @dev The deployer must change the ownership of the target token to this contract. /// @param _targetToken : The target token this contract manage the rights to mint. /// @return constructor ( MintableToken _targetToken ) public { targetToken = MintableToken(_targetToken); state = State.Init; } /// @dev Mint and distribute specified amount of tokens to an address. /// @param to An address that receive the minted tokens. /// @param amount Amount to mint. /// @return True if the distribution is successful, revert otherwise. function mint (address to, uint256 amount) external returns (bool) { /* being called from voting contract will be available in the future ex. if (state == State.Public && msg.sender == votingAddr) */ if ((state == State.Init && msg.sender == owner) || (state == State.Tokensale && msg.sender == tokensaleManagerAddr)) { return targetToken.mint(to, amount); } revert(); } /// @dev Change the phase from "Init" to "Tokensale". /// @param _tokensaleManagerAddr A contract address of token-sale. /// @return True if the change of the phase is successful, revert otherwise. function openTokensale (address _tokensaleManagerAddr) external onlyOwner returns (bool) { /* check if the owner of the target token is set to this contract */ require(MintableToken(targetToken).owner() == address(this)); require(state == State.Init); require(_tokensaleManagerAddr != address(0x0)); tokensaleManagerAddr = _tokensaleManagerAddr; state = State.Tokensale; return true; } /// @dev Change the phase from "Tokensale" to "Public". This function will be /// cahnged in the future to receive an address of voting contract as an /// argument in order to handle the result of minting proposal. /// @return True if the change of the phase is successful, revert otherwise. function closeTokensale () external returns (bool) { require(state == State.Tokensale && msg.sender == tokensaleManagerAddr); state = State.Public; return true; } /// @dev Check if the state is "Init" or not. /// @return True if the state is "Init", false otherwise. function isStateInit () external view returns (bool) { return (state == State.Init); } /// @dev Check if the state is "Tokensale" or not. /// @return True if the state is "Tokensale", false otherwise. function isStateTokensale () external view returns (bool) { return (state == State.Tokensale); } /// @dev Check if the state is "Public" or not. /// @return True if the state is "Public", false otherwise. function isStatePublic () external view returns (bool) { return (state == State.Public); } }
Change the phase from "Tokensale" to "Public". This function will be cahnged in the future to receive an address of voting contract as an argument in order to handle the result of minting proposal. return True if the change of the phase is successful, revert otherwise.
function closeTokensale () external returns (bool) { require(state == State.Tokensale && msg.sender == tokensaleManagerAddr); state = State.Public; return true; }
354,718
/* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ pragma solidity 0.4.24; /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SelfDestructible.sol version: 1.2 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be destroyed after its owner indicates an intention and then waits for a period without changing their mind. All ether contained in the contract is forwarded to a nominated beneficiary upon destruction. ----------------------------------------------------------------- */ /** * @title A contract that can be destroyed by its owner after a delay elapses. */ contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Pausable.sol version: 1.0 author: Kevin Brown date: 2018-05-22 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be marked as paused. It also defines a modifier which can be used by the inheriting contract to prevent actions while paused. ----------------------------------------------------------------- */ /** * @title A contract that can be paused by its owner */ contract Pausable is Owned { uint public lastPauseTime; bool public paused; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we&#39;re actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 1.0 author: Anton Jurisevic date: 2018-2-5 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A fixed point decimal library that provides basic mathematical operations, and checks for unsafe arguments, for example that would lead to overflows. Exceptions are thrown whenever those unsafe operations occur. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals (including fiat, ether, and nomin quantities). */ contract SafeDecimalMath { /* Number of decimal places in the representation. */ uint8 public constant decimals = 18; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /** * @return True iff adding x and y will not overflow. */ function addIsSafe(uint x, uint y) pure internal returns (bool) { return x + y >= y; } /** * @return The result of adding x and y, throwing an exception in case of overflow. */ function safeAdd(uint x, uint y) pure internal returns (uint) { require(x + y >= y, "Safe add failed"); return x + y; } /** * @return True iff subtracting y from x will not overflow in the negative direction. */ function subIsSafe(uint x, uint y) pure internal returns (bool) { return y <= x; } /** * @return The result of subtracting y from x, throwing an exception in case of overflow. */ function safeSub(uint x, uint y) pure internal returns (uint) { require(y <= x, "Safe sub failed"); return x - y; } /** * @return True iff multiplying x and y would not overflow. */ function mulIsSafe(uint x, uint y) pure internal returns (bool) { if (x == 0) { return true; } return (x * y) / x == y; } /** * @return The result of multiplying x and y, throwing an exception in case of overflow. */ function safeMul(uint x, uint y) pure internal returns (uint) { if (x == 0) { return 0; } uint p = x * y; require(p / x == y, "Safe mul failed"); return p; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. Throws an exception in case of overflow. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. * Incidentally, the internal division always rounds down: one could have rounded to the nearest integer, * but then one would be spending a significant fraction of a cent (of order a microether * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands * contain small enough fractional components. It would also marginally diminish the * domain this function is defined upon. */ function safeMul_dec(uint x, uint y) pure internal returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return safeMul(x, y) / UNIT; } /** * @return True iff the denominator of x/y is nonzero. */ function divIsSafe(uint x, uint y) pure internal returns (bool) { return y != 0; } /** * @return The result of dividing x by y, throwing an exception if the divisor is zero. */ function safeDiv(uint x, uint y) pure internal returns (uint) { /* Although a 0 denominator already throws an exception, * it is equivalent to a THROW operation, which consumes all gas. * A require statement emits REVERT instead, which remits remaining gas. */ require(y != 0, "Denominator cannot be zero"); return x / y; } /** * @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers. * @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT. * Internal rounding is downward: a similar caveat holds as with safeDecMul(). */ function safeDiv_dec(uint x, uint y) pure internal returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return safeDiv(safeMul(x, UNIT), y); } /** * @dev Convert an unsigned integer to a unsigned fixed-point decimal. * Throw an exception if the result would be out of range. */ function intToDec(uint i) pure internal returns (uint) { return safeMul(i, UNIT); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: State.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: TokenState.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that holds the state of an ERC20 compliant token. This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ /** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */ contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party&#39;s behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxy.sol version: 1.3 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxy contract that, if it does not recognise the function being called on it, passes all value and call data to an underlying target contract. This proxy has the capacity to toggle between DELEGATECALL and CALL style proxy functionality. The former executes in the proxy&#39;s context, and so will preserve msg.sender and store data at the proxy address. The latter will not. Therefore, any contract the proxy wraps in the CALL style must implement the Proxyable interface, in order that it can pass msg.sender into the underlying contract as the state parameter, messageSender. ----------------------------------------------------------------- */ contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { /* Copy call data into free memory region. */ let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* Forward all gas and call data to the target contract. */ let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) /* Revert if the call failed, otherwise return the result. */ if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { /* Here we are as above, but must send the messageSender explicitly * since we are using CALL rather than DELEGATECALL. */ target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target"); _; } event TargetUpdated(Proxyable newTarget); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxyable.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxyable contract that works hand in hand with the Proxy contract to allow for anyone to interact with the underlying contract both directly and through the proxy. ----------------------------------------------------------------- */ // This contract should be treated like an abstract contract contract Proxyable is Owned { /* The proxy this contract exists behind. */ Proxy public proxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.0 author: Kevin Brown date: 2018-08-06 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract offers a modifer that can prevent reentrancy on particular actions. It will not work if you put it on multiple functions that can be called from each other. Specifically guard external entry points to the contract with the modifier only. ----------------------------------------------------------------- */ contract ReentrancyPreventer { /* ========== MODIFIERS ========== */ bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A partial ERC20 token contract, designed to operate with a proxy. To produce a complete ERC20 token, transfer and transferFrom tokens must be implemented, using the provided _byProxy internal functions. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */ contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer { /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. * Note that the decimals field is defined in SafeDecimalMath.*/ string public name; string public symbol; uint public totalSupply; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { name = _name; symbol = _symbol; totalSupply = _totalSupply; tokenState = _tokenState; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner&#39;s funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal preventReentrancy returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value)); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value)); /* If we&#39;re transferring to a contract and it implements the havvenTokenFallback function, call it. This isn&#39;t ERC223 compliant because: 1. We don&#39;t revert if the contract doesn&#39;t implement havvenTokenFallback. This is because many DEXes and other contracts that expect to work with the standard approve / transferFrom workflow don&#39;t implement tokenFallback but can still process our tokens as usual, so it feels very harsh and likely to cause trouble if we add this restriction after having previously gone live with a vanilla ERC20. 2. We don&#39;t pass the bytes parameter. This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884 3. We also don&#39;t let the user use a custom tokenFallback. We figure as we&#39;re already not standards compliant, there won&#39;t be a use case where users can&#39;t just implement our specific function. As such we&#39;ve called the function havvenTokenFallback to be clear that we are not following the standard. */ // Is the to address a contract? We can check the code size on that address and know. uint length; // solium-disable-next-line security/no-inline-assembly assembly { // Retrieve the size of the code on the recipient address length := extcodesize(to) } // If there&#39;s code there, it&#39;s a contract if (length > 0) { // Now we need to optionally call havvenTokenFallback(address from, uint value). // We can&#39;t call it the normal way because that reverts when the recipient doesn&#39;t implement the function. // We&#39;ll use .call(), which means we need the function selector. We&#39;ve pre-computed // abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas. // solium-disable-next-line security/no-low-level-calls to.call(0xcbff5d96, messageSender, value); // And yes, we specifically don&#39;t care if this call fails, so we&#39;re not checking the return value. } // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender&#39;s behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: FeeToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A token which also has a configurable fee rate charged on its transfers. This is designed to be overridden in order to produce an ERC20-compliant token. These fees accrue into a pool, from which a nominated authority may withdraw. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state. * Additionally charges fees on each transfer. */ contract FeeToken is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* ERC20 members are declared in ExternStateToken. */ /* A percentage fee charged on each transfer. */ uint public transferFeeRate; /* Fee may not exceed 10%. */ uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10; /* The address with the authority to distribute fees. */ address public feeAuthority; /* The address that fees will be pooled in. */ address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _transferFeeRate The fee rate to charge on transfers. * @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint _transferFeeRate, address _feeAuthority, address _owner) ExternStateToken(_proxy, _tokenState, _name, _symbol, _totalSupply, _owner) public { feeAuthority = _feeAuthority; /* Constructed transfer fee rate should respect the maximum fee rate. */ require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate"); transferFeeRate = _transferFeeRate; } /* ========== SETTERS ========== */ /** * @notice Set the transfer fee, anywhere within the range 0-10%. * @dev The fee rate is in decimal format, with UNIT being the value of 100%. */ function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE"); transferFeeRate = _transferFeeRate; emitTransferFeeRateUpdated(_transferFeeRate); } /** * @notice Set the address of the user/contract responsible for collecting or * distributing fees. */ function setFeeAuthority(address _feeAuthority) public optionalProxy_onlyOwner { feeAuthority = _feeAuthority; emitFeeAuthorityUpdated(_feeAuthority); } /* ========== VIEWS ========== */ /** * @notice Calculate the Fee charged on top of a value being sent * @return Return the fee charged */ function transferFeeIncurred(uint value) public view returns (uint) { return safeMul_dec(value, transferFeeRate); /* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees. * This is on the basis that transfers less than this value will result in a nil fee. * Probably too insignificant to worry about, but the following code will achieve it. * if (fee == 0 && transferFeeRate != 0) { * return _value; * } * return fee; */ } /** * @notice The value that you would need to send so that the recipient receives * a specified value. */ function transferPlusFee(uint value) external view returns (uint) { return safeAdd(value, transferFeeIncurred(value)); } /** * @notice The amount the recipient will receive if you send a certain number of tokens. */ function amountReceived(uint value) public view returns (uint) { return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate)); } /** * @notice Collected fees sit here until they are distributed. * @dev The balance of the nomin contract itself is the fee pool. */ function feePool() external view returns (uint) { return tokenState.balanceOf(FEE_ADDRESS); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Base of transfer functions */ function _internalTransfer(address from, address to, uint amount, uint fee) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee))); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee)); /* Emit events for both the transfer itself and the fee. */ emitTransfer(from, to, amount); emitTransfer(from, FEE_ADDRESS, fee); return true; } /** * @notice ERC20 friendly transfer function. */ function _transfer_byProxy(address sender, address to, uint value) internal returns (bool) { uint received = amountReceived(value); uint fee = safeSub(value, received); return _internalTransfer(sender, to, received, fee); } /** * @notice ERC20 friendly transferFrom function. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is deducted from the amount sent. */ uint received = amountReceived(value); uint fee = safeSub(value, received); /* Reduce the allowance by the amount we&#39;re transferring. * The safeSub call will handle an insufficient allowance. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, received, fee); } /** * @notice Ability to transfer where the sender pays the fees (not ERC20) */ function _transferSenderPaysFee_byProxy(address sender, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); return _internalTransfer(sender, to, value, fee); } /** * @notice Ability to transferFrom where they sender pays the fees (not ERC20). */ function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); uint total = safeAdd(value, fee); /* Reduce the allowance by the amount we&#39;re transferring. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total)); return _internalTransfer(from, to, value, fee); } /** * @notice Withdraw tokens from the fee pool into a given account. * @dev Only the fee authority may call this. */ function withdrawFees(address account, uint value) external onlyFeeAuthority returns (bool) { require(account != address(0), "Must supply an account address to withdraw fees"); /* 0-value withdrawals do nothing. */ if (value == 0) { return false; } /* Safe subtraction ensures an exception is thrown if the balance is insufficient. */ tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value)); tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value)); emitFeesWithdrawn(account, value); emitTransfer(FEE_ADDRESS, account, value); return true; } /** * @notice Donate tokens from the sender&#39;s balance into the fee pool. */ function donateToFeePool(uint n) external optionalProxy returns (bool) { address sender = messageSender; /* Empty donations are disallowed. */ uint balance = tokenState.balanceOf(sender); require(balance != 0, "Must have a balance in order to donate to the fee pool"); /* safeSub ensures the donor has sufficient balance. */ tokenState.setBalanceOf(sender, safeSub(balance, n)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n)); emitFeesDonated(sender, n); emitTransfer(sender, FEE_ADDRESS, n); return true; } /* ========== MODIFIERS ========== */ modifier onlyFeeAuthority { require(msg.sender == feeAuthority, "Only the fee authority can do this action"); _; } /* ========== EVENTS ========== */ event TransferFeeRateUpdated(uint newFeeRate); bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)"); function emitTransferFeeRateUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0); } event FeeAuthorityUpdated(address newFeeAuthority); bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)"); function emitFeeAuthorityUpdated(address newFeeAuthority) internal { proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event FeesDonated(address indexed donor, uint value); bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)"); function emitFeesDonated(address donor, uint value) internal { proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Nomin.sol version: 1.2 author: Anton Jurisevic Mike Spain Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven-backed nomin stablecoin contract. This contract issues nomins, which are tokens worth 1 USD each. Nomins are issuable by Havven holders who have to lock up some value of their havvens to issue H * Cmax nomins. Where Cmax is some value less than 1. A configurable fee is charged on nomin transfers and deposited into a common pot, which havven holders may withdraw from once per fee period. ----------------------------------------------------------------- */ contract Nomin is FeeToken { /* ========== STATE VARIABLES ========== */ Havven public havven; // Accounts which have lost the privilege to transact in nomins. mapping(address => bool) public frozen; // Nomin transfers incur a 15 bp fee by default. uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000; string constant TOKEN_NAME = "Nomin USD"; string constant TOKEN_SYMBOL = "nUSD"; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, Havven _havven, uint _totalSupply, address _owner) FeeToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, TRANSFER_FEE_RATE, _havven, // The havven contract is the fee authority. _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_havven) != 0, "_havven cannot be 0"); require(_owner != 0, "_owner cannot be 0"); // It should not be possible to transfer to the fee pool directly (or confiscate its balance). frozen[FEE_ADDRESS] = true; havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external optionalProxy_onlyOwner { // havven should be set as the feeAuthority after calling this depending on // havven&#39;s internal logic havven = _havven; setFeeAuthority(_havven); emitHavvenUpdated(_havven); } /* ========== MUTATIVE FUNCTIONS ========== */ /* Override ERC20 transfer function in order to check * whether the recipient account is frozen. Note that there is * no need to check whether the sender has a frozen account, * since their funds have already been confiscated, * and no new funds can be transferred to it.*/ function transfer(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transfer_byProxy(messageSender, to, value); } /* Override ERC20 transferFrom function in order to check * whether the recipient account is frozen. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFrom_byProxy(messageSender, from, to, value); } function transferSenderPaysFee(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferSenderPaysFee_byProxy(messageSender, to, value); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value); } /* The owner may allow a previously-frozen contract to once * again accept and transfer nomins. */ function unfreezeAccount(address target) external optionalProxy_onlyOwner { require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address"); frozen[target] = false; emitAccountUnfrozen(target); } /* Allow havven to issue a certain number of * nomins from an account. */ function issue(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount)); totalSupply = safeAdd(totalSupply, amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } /* Allow havven to burn a certain number of * nomins from an account. */ function burn(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount)); totalSupply = safeSub(totalSupply, amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } /* ========== MODIFIERS ========== */ modifier onlyHavven() { require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action"); _; } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)"); function emitHavvenUpdated(address newHavven) internal { proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0); } event AccountFrozen(address indexed target, uint balance); bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)"); function emitAccountFrozen(address target, uint balance) internal { proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0); } event AccountUnfrozen(address indexed target); bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)"); function emitAccountUnfrozen(address target) internal { proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0); } event Issued(address indexed account, uint amount); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint amount); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: LimitedSetup.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract with a limited setup period. Any function modified with the setup modifier will cease to work after the conclusion of the configurable-length post-construction setup period. ----------------------------------------------------------------- */ /** * @title Any function decorated with the modifier this contract provides * deactivates after a specified setup period. */ contract LimitedSetup { uint setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: HavvenEscrow.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski Mike Spain date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows the foundation to apply unique vesting schedules to havven funds sold at various discounts in the token sale. HavvenEscrow gives users the ability to inspect their vested funds, their quantities and vesting dates, and to withdraw the fees that accrue on those funds. The fees are handled by withdrawing the entire fee allocation for all havvens inside the escrow contract, and then allowing the contract itself to subdivide that pool up proportionally within itself. Every time the fee period rolls over in the main Havven contract, the HavvenEscrow fee pool is remitted back into the main fee pool to be redistributed in the next fee period. ----------------------------------------------------------------- */ /** * @title A contract to hold escrowed havvens and free them at given schedules. */ contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) { /* The corresponding Havven contract. */ Havven public havven; /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. * These are the times at which each given quantity of havvens vests. */ mapping(address => uint[2][]) public vestingSchedules; /* An account&#39;s total vested havven balance to save recomputing this for fee extraction purposes. */ mapping(address => uint) public totalVestedAccountBalance; /* The total remaining vested balance, for verifying the actual havven balance of this contract against. */ uint public totalVestedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; /* Limit vesting entries to disallow unbounded iteration over vesting schedules. */ uint constant MAX_VESTING_ENTRIES = 20; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, Havven _havven) Owned(_owner) public { havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalVestedAccountBalance[account]; } /** * @notice The number of vesting dates in an account&#39;s schedule. */ function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } /** * @notice Get a particular schedule entry for an account. * @return A pair of uints: (timestamp, havven quantity). */ function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } /** * @notice Get the time at which a given schedule entry will vest. */ function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } /** * @notice Get the quantity of havvens associated with a given schedule entry. */ function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } /** * @notice Obtain the index of the next schedule entry that will vest for a given user. */ function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } /** * @notice Obtain the next schedule entry that will vest for a given user. * @return A pair of uints: (timestamp, havven quantity). */ function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } /** * @notice Obtain the time at which the next schedule entry will vest for a given user. */ function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } /** * @notice Obtain the quantity which the next schedule entry will vest for a given user. */ function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Withdraws a quantity of havvens back to the havven contract. * @dev This may only be called by the owner during the contract&#39;s setup period. */ function withdrawHavvens(uint quantity) external onlyOwner onlyDuringSetup { havven.transfer(havven, quantity); } /** * @notice Destroy the vesting information associated with an account. */ function purgeAccount(address account) external onlyOwner onlyDuringSetup { delete vestingSchedules[account]; totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]); delete totalVestedAccountBalance[account]; } /** * @notice Add a new vesting entry at a given time and quantity to an account&#39;s schedule. * @dev A call to this should be accompanied by either enough balance already available * in this contract, or a corresponding call to havven.endow(), to ensure that when * the funds are withdrawn, there is enough balance, as well as correctly calculating * the fees. * This may only be called by the owner during the contract&#39;s setup period. * Note; although this function could technically be used to produce unbounded * arrays, it&#39;s only in the foundation&#39;s command to add to these lists. * @param account The account to append a new vesting entry to. * @param time The absolute unix timestamp after which the vested quantity may be withdrawn. * @param quantity The quantity of havvens that will vest. */ function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup { /* No empty or already-passed vesting entries allowed. */ require(now < time, "Time must be in the future"); require(quantity != 0, "Quantity cannot be zero"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalVestedBalance = safeAdd(totalVestedBalance, quantity); require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry"); /* Disallow arbitrarily long vesting schedules in light of the gas limit. */ uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long"); if (scheduleLength == 0) { totalVestedAccountBalance[account] = quantity; } else { /* Disallow adding new vested havvens earlier than the last one. * Since entries are only appended, this means that no vesting date can be repeated. */ require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one"); totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity); } vestingSchedules[account].push([time, quantity]); } /** * @notice Construct a vesting schedule to release a quantities of havvens * over a series of intervals. * @dev Assumes that the quantities are nonzero * and that the sequence of timestamps is strictly increasing. * This may only be called by the owner during the contract&#39;s setup period. */ function addVestingSchedule(address account, uint[] times, uint[] quantities) external onlyOwner onlyDuringSetup { for (uint i = 0; i < times.length; i++) { appendVestingEntry(account, times[i], quantities[i]); } } /** * @notice Allow a user to withdraw any havvens in their schedule that have vested. */ function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = safeAdd(total, qty); } if (total != 0) { totalVestedBalance = safeSub(totalVestedBalance, total); totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total); havven.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); event Vested(address indexed beneficiary, uint time, uint value); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Havven.sol version: 1.2 author: Anton Jurisevic Dominic Romanowski date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven token contract. Havvens are transferable ERC20 tokens, and also give their holders the following privileges. An owner of havvens may participate in nomin confiscation votes, they may also have the right to issue nomins at the discretion of the foundation for this version of the contract. After a fee period terminates, the duration and fees collected for that period are computed, and the next period begins. Thus an account may only withdraw the fees owed to them for the previous period, and may only do so once per period. Any unclaimed fees roll over into the common pot for the next period. == Average Balance Calculations == The fee entitlement of a havven holder is proportional to their average issued nomin balance over the last fee period. This is computed by measuring the area under the graph of a user&#39;s issued nomin balance over time, and then when a new fee period begins, dividing through by the duration of the fee period. We need only update values when the balances of an account is modified. This occurs when issuing or burning for issued nomin balances, and when transferring for havven balances. This is for efficiency, and adds an implicit friction to interacting with havvens. A havven holder pays for his own recomputation whenever he wants to change his position, which saves the foundation having to maintain a pot dedicated to resourcing this. A hypothetical user&#39;s balance history over one fee period, pictorially: s ____ | | | |___ p |____|___|___ __ _ _ f t n Here, the balance was s between times f and t, at which time a transfer occurred, updating the balance to p, until n, when the present transfer occurs. When a new transfer occurs at time n, the balance being p, we must: - Add the area p * (n - t) to the total area recorded so far - Update the last transfer time to n So if this graph represents the entire current fee period, the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f). The complementary computations must be performed for both sender and recipient. Note that a transfer keeps global supply of havvens invariant. The sum of all balances is constant, and unmodified by any transfer. So the sum of all balances multiplied by the duration of a fee period is also constant, and this is equivalent to the sum of the area of every user&#39;s time/balance graph. Dividing through by that duration yields back the total havven supply. So, at the end of a fee period, we really do yield a user&#39;s average share in the havven supply over that period. A slight wrinkle is introduced if we consider the time r when the fee period rolls over. Then the previous fee period k-1 is before r, and the current fee period k is afterwards. If the last transfer took place before r, but the latest transfer occurred afterwards: k-1 | k s __|_ | | | | | |____ p |__|_|____|___ __ _ _ | f | t n r In this situation the area (r-f)*s contributes to fee period k-1, while the area (t-r)*s contributes to fee period k. We will implicitly consider a zero-value transfer to have occurred at time r. Their fee entitlement for the previous period will be finalised at the time of their first transfer during the current fee period, or when they query or withdraw their fee entitlement. In the implementation, the duration of different fee periods may be slightly irregular, as the check that they have rolled over occurs only when state-changing havven operations are performed. == Issuance and Burning == In this version of the havven contract, nomins can only be issued by those that have been nominated by the havven foundation. Nomins are assumed to be valued at $1, as they are a stable unit of account. All nomins issued require a proportional value of havvens to be locked, where the proportion is governed by the current issuance ratio. This means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued. i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up. To determine the value of some amount of havvens(H), an oracle is used to push the price of havvens (P_H) in dollars to the contract. The value of H would then be: H * P_H. Any havvens that are locked up by this issuance process cannot be transferred. The amount that is locked floats based on the price of havvens. If the price of havvens moves up, less havvens are locked, so they can be issued against, or transferred freely. If the price of havvens moves down, more havvens are locked, even going above the initial wallet balance. ----------------------------------------------------------------- */ /** * @title Havven ERC20 contract. * @notice The Havven contracts does not only facilitate transfers and track balances, * but it also computes the quantity of fees each havven holder is entitled to. */ contract Havven is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* A struct for handing values associated with average balance calculations */ struct IssuanceData { /* Sums of balances*duration in the current fee period. /* range: decimals; units: havven-seconds */ uint currentBalanceSum; /* The last period&#39;s average balance */ uint lastAverageBalance; /* The last time the data was calculated */ uint lastModified; } /* Issued nomin balances for individual fee entitlements */ mapping(address => IssuanceData) public issuanceData; /* The total number of issued nomins for determining fee entitlements */ IssuanceData public totalIssuanceData; /* The time the current fee period began */ uint public feePeriodStartTime; /* The time the last fee period began */ uint public lastFeePeriodStartTime; /* Fee periods will roll over in no shorter a time than this. * The fee period cannot actually roll over until a fee-relevant * operation such as withdrawal or a fee period duration update occurs, * so this is just a target, and the actual duration may be slightly longer. */ uint public feePeriodDuration = 4 weeks; /* ...and must target between 1 day and six months. */ uint constant MIN_FEE_PERIOD_DURATION = 1 days; uint constant MAX_FEE_PERIOD_DURATION = 26 weeks; /* The quantity of nomins that were in the fee pot at the time */ /* of the last fee rollover, at feePeriodStartTime. */ uint public lastFeesCollected; /* Whether a user has withdrawn their last fees */ mapping(address => bool) public hasWithdrawnFees; Nomin public nomin; HavvenEscrow public escrow; /* The address of the oracle which pushes the havven price to this contract */ address public oracle; /* The price of havvens written in UNIT */ uint public price; /* The time the havven price was last updated */ uint public lastPriceUpdateTime; /* How long will the contract assume the price of havvens is correct */ uint public priceStalePeriod = 3 hours; /* A quantity of nomins greater than this ratio * may not be issued against a given value of havvens. */ uint public issuanceRatio = UNIT / 5; /* No more nomins may be issued than the value of havvens backing them. */ uint constant MAX_ISSUANCE_RATIO = UNIT; /* Whether the address can issue nomins or not. */ mapping(address => bool) public isIssuer; /* The number of currently-outstanding nomins the user has issued. */ mapping(address => uint) public nominsIssued; uint constant HAVVEN_SUPPLY = 1e8 * UNIT; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; string constant TOKEN_NAME = "Havven"; string constant TOKEN_SYMBOL = "HAV"; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _tokenState A pre-populated contract containing token balances. * If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle, uint _price, address[] _issuers, Havven _oldHavven) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner) public { oracle = _oracle; price = _price; lastPriceUpdateTime = now; uint i; if (_oldHavven == address(0)) { feePeriodStartTime = now; lastFeePeriodStartTime = now - feePeriodDuration; for (i = 0; i < _issuers.length; i++) { isIssuer[_issuers[i]] = true; } } else { feePeriodStartTime = _oldHavven.feePeriodStartTime(); lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime(); uint cbs; uint lab; uint lm; (cbs, lab, lm) = _oldHavven.totalIssuanceData(); totalIssuanceData.currentBalanceSum = cbs; totalIssuanceData.lastAverageBalance = lab; totalIssuanceData.lastModified = lm; for (i = 0; i < _issuers.length; i++) { address issuer = _issuers[i]; isIssuer[issuer] = true; uint nomins = _oldHavven.nominsIssued(issuer); if (nomins == 0) { // It is not valid in general to skip those with no currently-issued nomins. // But for this release, issuers with nonzero issuanceData have current issuance. continue; } (cbs, lab, lm) = _oldHavven.issuanceData(issuer); nominsIssued[issuer] = nomins; issuanceData[issuer].currentBalanceSum = cbs; issuanceData[issuer].lastAverageBalance = lab; issuanceData[issuer].lastModified = lm; } } } /* ========== SETTERS ========== */ /** * @notice Set the associated Nomin contract to collect fees from. * @dev Only the contract owner may call this. */ function setNomin(Nomin _nomin) external optionalProxy_onlyOwner { nomin = _nomin; emitNominUpdated(_nomin); } /** * @notice Set the associated havven escrow contract. * @dev Only the contract owner may call this. */ function setEscrow(HavvenEscrow _escrow) external optionalProxy_onlyOwner { escrow = _escrow; emitEscrowUpdated(_escrow); } /** * @notice Set the targeted fee period duration. * @dev Only callable by the contract owner. The duration must fall within * acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period * may roll over if the target duration was shortened sufficiently. */ function setFeePeriodDuration(uint duration) external optionalProxy_onlyOwner { require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION, "Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION"); feePeriodDuration = duration; emitFeePeriodDurationUpdated(duration); rolloverFeePeriodIfElapsed(); } /** * @notice Set the Oracle that pushes the havven price to this contract */ function setOracle(address _oracle) external optionalProxy_onlyOwner { oracle = _oracle; emitOracleUpdated(_oracle); } /** * @notice Set the stale period on the updated havven price * @dev No max/minimum, as changing it wont influence anything but issuance by the foundation */ function setPriceStalePeriod(uint time) external optionalProxy_onlyOwner { priceStalePeriod = time; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external optionalProxy_onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emitIssuanceRatioUpdated(_issuanceRatio); } /** * @notice Set whether the specified can issue nomins or not. */ function setIssuer(address account, bool value) external optionalProxy_onlyOwner { isIssuer[account] = value; emitIssuersUpdated(account, value); } /* ========== VIEWS ========== */ function issuanceCurrentBalanceSum(address account) external view returns (uint) { return issuanceData[account].currentBalanceSum; } function issuanceLastAverageBalance(address account) external view returns (uint) { return issuanceData[account].lastAverageBalance; } function issuanceLastModified(address account) external view returns (uint) { return issuanceData[account].lastModified; } function totalIssuanceCurrentBalanceSum() external view returns (uint) { return totalIssuanceData.currentBalanceSum; } function totalIssuanceLastAverageBalance() external view returns (uint) { return totalIssuanceData.lastAverageBalance; } function totalIssuanceLastModified() external view returns (uint) { return totalIssuanceData.lastModified; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transfer_byProxy(sender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transferFrom_byProxy(sender, from, to, value); return true; } /** * @notice Compute the last period&#39;s fee entitlement for the message sender * and then deposit it into their nomin account. */ function withdrawFees() external optionalProxy { address sender = messageSender; rolloverFeePeriodIfElapsed(); /* Do not deposit fees into frozen accounts. */ require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts"); /* Check the period has rolled over first. */ updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply()); /* Only allow accounts to withdraw fees once per period. */ require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period"); uint feesOwed; uint lastTotalIssued = totalIssuanceData.lastAverageBalance; if (lastTotalIssued > 0) { /* Sender receives a share of last period&#39;s collected fees proportional * with their average fraction of the last period&#39;s issued nomins. */ feesOwed = safeDiv_dec( safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected), lastTotalIssued ); } hasWithdrawnFees[sender] = true; if (feesOwed != 0) { nomin.withdrawFees(sender, feesOwed); } emitFeesWithdrawn(messageSender, feesOwed); } /** * @notice Update the havven balance averages since the last transfer * or entitlement adjustment. * @dev Since this updates the last transfer timestamp, if invoked * consecutively, this function will do nothing after the first call. * Also, this will adjust the total issuance at the same time. */ function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply) internal { /* update the total balances first */ totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData); if (issuanceData[account].lastModified < feePeriodStartTime) { hasWithdrawnFees[account] = false; } issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]); } /** * @notice Compute the new IssuanceData on the old balance */ function computeIssuanceData(uint preBalance, IssuanceData preIssuance) internal view returns (IssuanceData) { uint currentBalanceSum = preIssuance.currentBalanceSum; uint lastAverageBalance = preIssuance.lastAverageBalance; uint lastModified = preIssuance.lastModified; if (lastModified < feePeriodStartTime) { if (lastModified < lastFeePeriodStartTime) { /* The balance was last updated before the previous fee period, so the average * balance in this period is their pre-transfer balance. */ lastAverageBalance = preBalance; } else { /* The balance was last updated during the previous fee period. */ /* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified. * implies these quantities are strictly positive. */ uint timeUpToRollover = feePeriodStartTime - lastModified; uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime; uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover)); lastAverageBalance = lastBalanceSum / lastFeePeriodDuration; } /* Roll over to the next fee period. */ currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime); } else { /* The balance was last updated during the current fee period. */ currentBalanceSum = safeAdd( currentBalanceSum, safeMul(preBalance, now - lastModified) ); } return IssuanceData(currentBalanceSum, lastAverageBalance, now); } /** * @notice Recompute and return the given account&#39;s last average balance. */ function recomputeLastAverageBalance(address account) external returns (uint) { updateIssuanceData(account, nominsIssued[account], nomin.totalSupply()); return issuanceData[account].lastAverageBalance; } /** * @notice Issue nomins against the sender&#39;s havvens. * @dev Issuance is only allowed if the havven price isn&#39;t stale and the sender is an issuer. */ function issueNomins(uint amount) public optionalProxy requireIssuer(messageSender) /* No need to check if price is stale, as it is checked in issuableNomins. */ { address sender = messageSender; require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins"); uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; nomin.issue(sender, amount); nominsIssued[sender] = safeAdd(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } function issueMaxNomins() external optionalProxy { issueNomins(remainingIssuableNomins(messageSender)); } /** * @notice Burn nomins to clear issued nomins/free havvens. */ function burnNomins(uint amount) /* it doesn&#39;t matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/ external optionalProxy { address sender = messageSender; uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; /* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */ nomin.burn(sender, amount); /* This safe sub ensures amount <= number issued */ nominsIssued[sender] = safeSub(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } /** * @notice Check if the fee period has rolled over. If it has, set the new fee period start * time, and record the fees collected in the nomin contract. */ function rolloverFeePeriodIfElapsed() public { /* If the fee period has rolled over... */ if (now >= feePeriodStartTime + feePeriodDuration) { lastFeesCollected = nomin.feePool(); lastFeePeriodStartTime = feePeriodStartTime; feePeriodStartTime = now; emitFeePeriodRollover(now); } } /* ========== Issuance/Burning ========== */ /** * @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any * already issued nomins. */ function maxIssuableNomins(address issuer) view public priceNotStale returns (uint) { if (!isIssuer[issuer]) { return 0; } if (escrow != HavvenEscrow(0)) { uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer)); return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio); } else { return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio); } } /** * @notice The remaining nomins an issuer can issue against their total havven quantity. */ function remainingIssuableNomins(address issuer) view public returns (uint) { uint issued = nominsIssued[issuer]; uint max = maxIssuableNomins(issuer); if (issued > max) { return 0; } else { return safeSub(max, issued); } } /** * @notice The total havvens owned by this account, both escrowed and unescrowed, * against which nomins can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint bal = tokenState.balanceOf(account); if (escrow != address(0)) { bal = safeAdd(bal, escrow.balanceOf(account)); } return bal; } /** * @notice The collateral that would be locked by issuance, which can exceed the account&#39;s actual collateral. */ function issuanceDraft(address account) public view returns (uint) { uint issued = nominsIssued[account]; if (issued == 0) { return 0; } return USDtoHAV(safeDiv_dec(issued, issuanceRatio)); } /** * @notice Collateral that has been locked due to issuance, and cannot be * transferred to other addresses. This is capped at the account&#39;s total collateral. */ function lockedCollateral(address account) public view returns (uint) { uint debt = issuanceDraft(account); uint collat = collateral(account); if (debt > collat) { return collat; } return debt; } /** * @notice Collateral that is not locked and available for issuance. */ function unlockedCollateral(address account) public view returns (uint) { uint locked = lockedCollateral(account); uint collat = collateral(account); return safeSub(collat, locked); } /** * @notice The number of havvens that are free to be transferred by an account. * @dev If they have enough available Havvens, it could be that * their havvens are escrowed, however the transfer would then * fail. This means that escrowed havvens are locked first, * and then the actual transferable ones. */ function transferableHavvens(address account) public view returns (uint) { uint draft = issuanceDraft(account); uint collat = collateral(account); // In the case where the issuanceDraft exceeds the collateral, nothing is free if (draft > collat) { return 0; } uint bal = balanceOf(account); // In the case where the draft exceeds the escrow, but not the whole collateral // return the fraction of the balance that remains free if (draft > safeSub(collat, bal)) { return safeSub(collat, draft); } // In the case where the draft doesn&#39;t exceed the escrow, return the entire balance return bal; } /** * @notice The value in USD for a given amount of HAV */ function HAVtoUSD(uint hav_dec) public view priceNotStale returns (uint) { return safeMul_dec(hav_dec, price); } /** * @notice The value in HAV for a given amount of USD */ function USDtoHAV(uint usd_dec) public view priceNotStale returns (uint) { return safeDiv_dec(usd_dec, price); } /** * @notice Access point for the oracle to update the price of havvens. */ function updatePrice(uint newPrice, uint timeSent) external onlyOracle /* Should be callable only by the oracle. */ { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); price = newPrice; lastPriceUpdateTime = timeSent; emitPriceUpdated(newPrice, timeSent); /* Check the fee period rollover within this as the price should be pushed every 15min. */ rolloverFeePeriodIfElapsed(); } /** * @notice Check if the price of havvens hasn&#39;t been updated for longer than the stale period. */ function priceIsStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /* ========== MODIFIERS ========== */ modifier requireIssuer(address account) { require(isIssuer[account], "Must be issuer to perform this action"); _; } modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier priceNotStale { require(!priceIsStale(), "Price must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event PriceUpdated(uint newPrice, uint timestamp); bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)"); function emitPriceUpdated(uint newPrice, uint timestamp) internal { proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0); } event IssuanceRatioUpdated(uint newRatio); bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)"); function emitIssuanceRatioUpdated(uint newRatio) internal { proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0); } event FeePeriodRollover(uint timestamp); bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)"); function emitFeePeriodRollover(uint timestamp) internal { proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0); } event FeePeriodDurationUpdated(uint duration); bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)"); function emitFeePeriodDurationUpdated(uint duration) internal { proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event OracleUpdated(address newOracle); bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)"); function emitOracleUpdated(address newOracle) internal { proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0); } event NominUpdated(address newNomin); bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)"); function emitNominUpdated(address newNomin) internal { proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0); } event EscrowUpdated(address newEscrow); bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)"); function emitEscrowUpdated(address newEscrow) internal { proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0); } event IssuersUpdated(address indexed account, bool indexed value); bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)"); function emitIssuersUpdated(address account, bool value) internal { proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: IssuanceController.sol version: 2.0 author: Kevin Brown date: 2018-07-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Issuance controller contract. The issuance controller provides a way for users to acquire nomins (Nomin.sol) and havvens (Havven.sol) by paying ETH and a way for users to acquire havvens (Havven.sol) by paying nomins. Users can also deposit their nomins and allow other users to purchase them with ETH. The ETH is sent to the user who offered their nomins for sale. This smart contract contains a balance of each currency, and allows the owner of the contract (the Havven Foundation) to manage the available balance of havven at their discretion, while users are allowed to deposit and withdraw their own nomin deposits if they have not yet been taken up by another user. ----------------------------------------------------------------- */ /** * @title Issuance Controller Contract. */ contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable { /* ========== STATE VARIABLES ========== */ Havven public havven; Nomin public nomin; // Address where the ether raised is transfered to address public fundsWallet; /* The address of the oracle which pushes the USD price havvens and ether to this contract */ address public oracle; /* Do not allow the oracle to submit times any further forward into the future than this constant. */ uint constant ORACLE_FUTURE_LIMIT = 10 minutes; /* How long will the contract assume the price of any asset is correct */ uint public priceStalePeriod = 3 hours; /* The time the prices were last updated */ uint public lastPriceUpdateTime; /* The USD price of havvens denominated in UNIT */ uint public usdToHavPrice; /* The USD price of ETH denominated in UNIT */ uint public usdToEthPrice; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _owner The owner of this contract. * @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging. * @param _havven The Havven contract we&#39;ll interact with for balances and sending. * @param _nomin The Nomin contract we&#39;ll interact with for balances and sending. * @param _oracle The address which is able to update price information. * @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT. * @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT. */ constructor( // Ownable address _owner, // Funds Wallet address _fundsWallet, // Other contracts needed Havven _havven, Nomin _nomin, // Oracle values - Allows for price updates address _oracle, uint _usdToEthPrice, uint _usdToHavPrice ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) Pausable(_owner) public { fundsWallet = _fundsWallet; havven = _havven; nomin = _nomin; oracle = _oracle; usdToEthPrice = _usdToEthPrice; usdToHavPrice = _usdToHavPrice; lastPriceUpdateTime = now; } /* ========== SETTERS ========== */ /** * @notice Set the funds wallet where ETH raised is held * @param _fundsWallet The new address to forward ETH and Nomins to */ function setFundsWallet(address _fundsWallet) external onlyOwner { fundsWallet = _fundsWallet; emit FundsWalletUpdated(fundsWallet); } /** * @notice Set the Oracle that pushes the havven price to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the Nomin contract that the issuance controller uses to issue Nomins. * @param _nomin The new nomin contract target */ function setNomin(Nomin _nomin) external onlyOwner { nomin = _nomin; emit NominUpdated(_nomin); } /** * @notice Set the Havven contract that the issuance controller uses to issue Havvens. * @param _havven The new havven contract target */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /** * @notice Set the stale period on the updated price variables * @param _time The new priceStalePeriod */ function setPriceStalePeriod(uint _time) external onlyOwner { priceStalePeriod = _time; emit PriceStalePeriodUpdated(priceStalePeriod); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Access point for the oracle to update the prices of havvens / eth. * @param newEthPrice The current price of ether in USD, specified to 18 decimal places. * @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places. * @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don&#39;t consider stale prices as current in times of heavy network congestion. */ function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent) external onlyOracle { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); usdToEthPrice = newEthPrice; usdToHavPrice = newHavvenPrice; lastPriceUpdateTime = timeSent; emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime); } /** * @notice Fallback function (exchanges ETH to nUSD) */ function () external payable { exchangeEtherForNomins(); } /** * @notice Exchange ETH to nUSD. */ function exchangeEtherForNomins() public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { // The multiplication works here because usdToEthPrice is specified in // 18 decimal places, just like our currency base. uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // Send the nomins. // Note: Fees are calculated by the Nomin contract, so when // we request a specific transfer here, the fee is // automatically deducted and sent to the fee pool. nomin.transfer(msg.sender, requestedToPurchase); emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase); return requestedToPurchase; } /** * @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert. */ function exchangeEtherForNominsAtRate(uint guaranteedRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { require(guaranteedRate == usdToEthPrice); return exchangeEtherForNomins(); } /** * @notice Exchange ETH to HAV. */ function exchangeEtherForHavvens() public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForEther(msg.value); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("ETH", msg.value, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rates. * @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert. * @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert. */ function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedEtherRate == usdToEthPrice); require(guaranteedHavvenRate == usdToHavPrice); return exchangeEtherForHavvens(); } /** * @notice Exchange nUSD for Havvens * @param nominAmount The amount of nomins the user wishes to exchange. */ function exchangeNominsForHavvens(uint nominAmount) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForNomins(nominAmount); // Ok, transfer the Nomins to our address. nomin.transferFrom(msg.sender, this, nominAmount); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("nUSD", nominAmount, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param nominAmount The amount of nomins the user wishes to exchange. * @param guaranteedRate A rate (havven price) the caller wishes to insist upon. */ function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedRate == usdToHavPrice); return exchangeNominsForHavvens(nominAmount); } /** * @notice Allows the owner to withdraw havvens from this contract if needed. * @param amount The amount of havvens to attempt to withdraw (in 18 decimal places). */ function withdrawHavvens(uint amount) external onlyOwner { havven.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /** * @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed. * @param amount The amount of nomins to attempt to withdraw (in 18 decimal places). */ function withdrawNomins(uint amount) external onlyOwner { nomin.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /* ========== VIEWS ========== */ /** * @notice Check if the prices haven&#39;t been updated for longer than the stale period. */ function pricesAreStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of nomins. * @param amount The amount of nomins (in 18 decimal places) you want to ask about */ function havvensReceivedForNomins(uint amount) public view returns (uint) { // How many nomins would we receive after the transfer fee? uint nominsReceived = nomin.amountReceived(amount); // And what would that be worth in havvens based on the current price? return safeDiv_dec(nominsReceived, usdToHavPrice); } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function havvensReceivedForEther(uint amount) public view returns (uint) { // How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)? uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice); // Now, how many HAV will that USD amount buy? return havvensReceivedForNomins(valueSentInNomins); } /** * @notice Calculate how many nomins you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function nominsReceivedForEther(uint amount) public view returns (uint) { // How many nomins would that amount of ether be worth? uint nominsTransferred = safeMul_dec(amount, usdToEthPrice); // And how many of those would you receive after a transfer (deducting the transfer fee) return nomin.amountReceived(nominsTransferred); } /* ========== MODIFIERS ========== */ modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier pricesNotStale { require(!pricesAreStale(), "Prices must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event FundsWalletUpdated(address newFundsWallet); event OracleUpdated(address newOracle); event NominUpdated(Nomin newNominContract); event HavvenUpdated(Havven newHavvenContract); event PriceStalePeriodUpdated(uint priceStalePeriod); event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent); event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount); }
The total havvens owned by this account, both escrowed and unescrowed, against which nomins can be issued. This includes those already being used as collateral (locked), and those available for further issuance (unlocked)./
function collateral(address account) public view returns (uint) { uint bal = tokenState.balanceOf(account); if (escrow != address(0)) { bal = safeAdd(bal, escrow.balanceOf(account)); } return bal; }
2,140,204
// SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.7.0; library TokenFlags { uint32 internal constant BIT_PAUSABLE = 0; uint32 internal constant BIT_MINTABLE = 1; uint32 internal constant BIT_BURNABLE = 2; uint32 internal constant BIT_ETH_REFUNDABLE = 3; uint32 internal constant BIT_ERC20_REFUNDABLE = 4; uint32 internal constant BIT_BLACKLISTABLE = 5; uint32 internal constant BIT_DIRECT_MODE = 6; function isPausable(uint32 flags) internal pure returns (bool) { return ((flags >> BIT_PAUSABLE) & 1) > 0; } function isMintable(uint32 flags) internal pure returns (bool) { return ((flags >> BIT_MINTABLE) & 1) > 0; } function isBurnable(uint32 flags) internal pure returns (bool) { return ((flags >> BIT_BURNABLE) & 1) > 0; } function isETHRefundable(uint32 flags) internal pure returns (bool) { return ((flags >> BIT_ETH_REFUNDABLE) & 1) > 0; } function isERC20Refundable(uint32 flags) internal pure returns (bool) { return ((flags >> BIT_ERC20_REFUNDABLE) & 1) > 0; } function isBlacklistable(uint32 flags) internal pure returns (bool) { return ((flags >> BIT_BLACKLISTABLE) & 1) > 0; } function isDirectMode(uint32 flags) internal pure returns (bool) { return ((flags >> BIT_DIRECT_MODE) & 1) > 0; } } pragma solidity >=0.5.16 <0.7.0; interface ICashier { function getPayee() external view returns (address payable); function calcFee(address addr, uint256 kind, bytes4 func) external view returns (uint256); } pragma solidity >=0.5.16 <0.7.0; contract Chargeable { function sendFee(uint256 kind) internal { sendFee(msg.sig, kind); } function sendFee(bytes4 func, uint256 kind) internal { address cashier = _getCashier(); if (address(cashier) == address(0x0)) { return; } address payable payee = ICashier(cashier).getPayee(); if (payee == address(0x0)) { return; } uint256 fee = ICashier(cashier).calcFee(address(this), kind, func); if (fee > 0) { require(address(this).balance >= fee, "Function fee is not enough."); payee.transfer(fee); } } /** * @dev Storage slot with the address of the cashier contract. * This is the keccak-256 hash of "x.cashier.contract" and is validated in the constructor. */ bytes32 internal constant _CASHIER_SLOT = 0xe4daccb11a797004e79d649410b00658e14f3296aae1b244a00c23be3d595cd4; /** * @dev Returns the current cashier contract address. */ function _getCashier() internal view returns (address cashier) { bytes32 slot = _CASHIER_SLOT; // solhint-disable-next-line no-inline-assembly assembly { cashier := sload(slot) } } /** * @dev Stores a new address in the cashier slot. */ function _setCashier(address addr) internal { // zero address is enabled, which means not chargeable bytes32 slot = _CASHIER_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, addr) } } } pragma solidity >=0.5.16 <0.7.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; } } pragma solidity >=0.5.16 <0.7.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.5.16 <0.7.0; contract BaseTokenV1 is IERC20, Chargeable { using SafeMath for uint256; uint256 internal constant CONTRACT_KIND = 1; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; string internal _name; string internal _symbol; uint256 internal _totalSupply; uint8 internal _decimals; uint8 internal _version; address internal _owner; uint32 internal _flags; bool internal _paused; mapping(address => bool) internal _blacklist; constructor() public {} function init( address cashier, address theOwner, string memory name, string memory symbol, uint8 decimals, uint256 initSupply, uint32 flags ) public { require(_version == 0, "I had been initialized already"); require(cashier != address(0x0), "Cashier address can not be zero"); _version = 1; _name = name; _symbol = symbol; _decimals = decimals; _flags = flags; _setOwner(theOwner); _setCashier(cashier); _mint(theOwner, initSupply); } function getCashier() public view returns (address) { return _getCashier(); } function version() public virtual view returns (uint8) { return _version; } function flags() public view returns (uint256) { return _flags; } function _setFlag(uint32 flagBit, bool b) internal { if (b) { _flags = _flags | (uint32(1) << flagBit); } else { _flags = _flags & (0xFFFFFFFF - (uint32(1) << flagBit)); } } function isPausable() public view returns (bool) { return TokenFlags.isPausable(_flags); } function isMintable() public view returns (bool) { return TokenFlags.isMintable(_flags); } function isBurnable() public view returns (bool) { return TokenFlags.isBurnable(_flags); } function isETHRefundable() public view returns (bool) { return TokenFlags.isETHRefundable(_flags); } function isERC20Refundable() public view returns (bool) { return TokenFlags.isERC20Refundable(_flags); } function isBlacklistable() public view returns (bool) { return TokenFlags.isBlacklistable(_flags); } function isDirectMode() public view returns (bool) { return TokenFlags.isDirectMode(_flags); } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "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 payable onlyOwner { sendFee(CONTRACT_KIND); emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual payable onlyOwner { sendFee(CONTRACT_KIND); _setOwner(newOwner); } function _setOwner(address newOwner) internal { require(newOwner != address(0), "Can not set owner to zero"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } event Paused(address account); event Unpaused(address account); function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused state"); _; } modifier whenPaused() { require(_paused, "Pausable: unpaused state"); _; } function pause() public payable whenNotPaused onlyOwner { require(isPausable(), "Contract is not pausable"); sendFee(CONTRACT_KIND); _paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public payable whenPaused onlyOwner { require(isPausable(), "Contract is not pausable"); sendFee(CONTRACT_KIND); _paused = false; emit Unpaused(msg.sender); } function stopPausable() public payable whenNotPaused onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_MINTABLE, false); } function mint(address to, uint256 value) public payable whenNotPaused onlyOwner returns (bool) { require(isMintable(), "Contract is not mintable"); sendFee(CONTRACT_KIND); _mint(to, value); return true; } function stopMintable() public payable onlyOwner { require(isMintable(), "Contract is not mintable"); sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_MINTABLE, false); } function burn(uint256 value) public whenNotPaused { require(isBurnable(), "Contract is not burnable"); _burn(msg.sender, value); } function setBurnable() public payable onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_BURNABLE, true); } function unsetBurnable() public payable onlyOwner { // require(isBurnable(), "Contract is not burnable"); sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_BURNABLE, false); } event RefundETH(address indexed payee, uint256 amount); event RefundERC20(address indexed payee, address indexed token, uint256 amount); function refundETH(address payee, uint256 amount) public payable onlyOwner { require(isETHRefundable(), "Not refundable for ETH"); require(payee != address(0), "Refund to address 0x0"); sendFee(CONTRACT_KIND); require(amount <= address(this).balance, "Balance not enough"); payable(payee).transfer(amount); emit RefundETH(payee, amount); } function refundETHAll(address payee) public payable onlyOwner { require(isETHRefundable(), "Not refundable for ETH"); require(payee != address(0), "Refund to address 0x0"); sendFee(CONTRACT_KIND); uint256 amount = address(this).balance; payable(payee).transfer(amount); emit RefundETH(payee, amount); } function setETHRefundable() public payable onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_ETH_REFUNDABLE, true); } function unsetETHRefundable() public payable onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_ETH_REFUNDABLE, false); } function refundERC20( address tokenContract, address payee, uint256 amount ) public payable onlyOwner { require(isERC20Refundable(), "Not refundable for ERC20"); require(payee != address(0), "Refund to address 0x0"); bool isContract; // solhint-disable-next-line no-inline-assembly assembly { isContract := gt(extcodesize(tokenContract), 0) } require(isContract, "contract address is required"); sendFee(CONTRACT_KIND); IERC20 token = IERC20(tokenContract); token.transfer(payee, amount); emit RefundERC20(payee, tokenContract, amount); } function refundERC20All(address tokenContract, address payee) public payable onlyOwner { uint256 balance = IERC20(tokenContract).balanceOf(address(this)); refundERC20(tokenContract, payee, balance); } function setERC20Refundable() public payable onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_ERC20_REFUNDABLE, true); } function unsetERC20Refundable() public payable onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_ERC20_REFUNDABLE, false); } event Blacklisted(address indexed account); event UnBlacklisted(address indexed account); function isInBlacklist(address account) public view returns (bool) { return _blacklist[account]; } function blacklist(address account) public payable onlyOwner { require(isBlacklistable(), "Contract is not blacklistable"); sendFee(CONTRACT_KIND); _blacklist[account] = true; emit Blacklisted(account); } function unBlacklist(address account) public payable onlyOwner { require(isBlacklistable(), "Contract is not blacklistable"); sendFee(CONTRACT_KIND); _blacklist[account] = false; emit UnBlacklisted(account); } function setBlacklistable() public payable onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_BLACKLISTABLE, true); } function unsetBlacklistable() public payable onlyOwner { sendFee(CONTRACT_KIND); _setFlag(TokenFlags.BIT_BLACKLISTABLE, false); } /** * @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 override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address from, address spender) public virtual override view returns (uint256) { return _allowances[from][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, 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, msg.sender, _allowances[sender][msg.sender].sub(amount, "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(msg.sender, spender, _allowances[msg.sender][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( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "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), "Transfer from the zero address"); require(recipient != address(0), "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), "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), "Burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "Burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `from` 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: * * - `from` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address from, address spender, uint256 amount ) internal virtual { require(from != address(0), "Approve from the zero address"); require(spender != address(0), "Approve to the zero address"); _allowances[from][spender] = amount; emit Approval(from, 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 view whenNotPaused { if (isBlacklistable()) { require(!isInBlacklist(from), "From is blacklisted"); require(!isInBlacklist(to), "To is blacklisted"); } } } pragma solidity >=0.5.16 <0.7.0; interface ITokenRegistry { function register( address token, address creator, address inviter ) external payable; } pragma solidity >=0.5.16 <0.7.0; contract TokenV1 is BaseTokenV1 { constructor( ITokenRegistry registry, uint256 fee, address cashier, string memory name, string memory symbol, uint8 decimals, uint256 initSupply, uint32 flags, address inviter, bytes32 h ) public payable { require(fee > 0 && msg.value >= fee, "Function fee is not enough"); require(TokenFlags.isDirectMode(flags), "Invalid flags"); bytes32 vh = keccak256(abi.encode(address(registry), fee, cashier, name, flags)); require(h == vh, "Invalid h"); registry.register{value: msg.value}(address(this), msg.sender, inviter); init(cashier, msg.sender, name, symbol, decimals, initSupply, flags); } receive() external payable {} fallback() external payable {} }
See {IERC20-allowance}./
function allowance(address from, address spender) public virtual override view returns (uint256) { return _allowances[from][spender]; }
13,669,156
pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../utils/BytesLib.sol"; import "../../cryptography/AltBn128.sol"; import "../../cryptography/BLS.sol"; import "../../TokenStaking.sol"; library Groups { using SafeMath for uint256; using BytesLib for bytes; struct Group { bytes groupPubKey; uint registrationBlockHeight; } struct Storage { // Time in blocks after which a group expires. uint256 groupActiveTime; // Duplicated constant from operator contract to avoid extra call. // The value is set when the operator contract is added. uint256 relayEntryTimeout; Group[] groups; uint256[] terminatedGroups; mapping (bytes => address[]) groupMembers; // Sum of all group member rewards earned so far. The value is the same for // all group members. Submitter reward and reimbursement is paid immediately // and is not included here. Each group member can withdraw no more than // this value. mapping (bytes => uint256) groupMemberRewards; // expiredGroupOffset is pointing to the first active group, it is also the // expired groups counter uint256 expiredGroupOffset; TokenStaking stakingContract; } /** * @dev Adds group. */ function addGroup( Storage storage self, bytes memory groupPubKey ) internal { self.groups.push(Group(groupPubKey, block.number)); } /** * @dev Sets addresses of members for the group with the given public key * eliminating members at positions pointed by the misbehaved array. * @param groupPubKey Group public key. * @param members Group member addresses as outputted by the group selection * protocol. * @param misbehaved Bytes array of misbehaved (disqualified or inactive) * group members indexes in ascending order; Indexes reflect positions of * members in the group as outputted by the group selection protocol - * member indexes start from 1. */ function setGroupMembers( Storage storage self, bytes memory groupPubKey, address[] memory members, bytes memory misbehaved ) internal { self.groupMembers[groupPubKey] = members; // Iterate misbehaved array backwards, replace misbehaved // member with the last element and reduce array length uint256 i = misbehaved.length; while (i > 0) { // group member indexes start from 1, so we need to -1 on misbehaved uint256 memberArrayPosition = misbehaved.toUint8(i - 1) - 1; self.groupMembers[groupPubKey][memberArrayPosition] = self.groupMembers[groupPubKey][self.groupMembers[groupPubKey].length - 1]; self.groupMembers[groupPubKey].length--; i--; } } /** * @dev Adds group member reward per group so the accumulated amount can be withdrawn later. */ function addGroupMemberReward( Storage storage self, bytes memory groupPubKey, uint256 amount ) internal { self.groupMemberRewards[groupPubKey] = self.groupMemberRewards[groupPubKey].add(amount); } /** * @dev Returns accumulated group member rewards for provided group. */ function getGroupMemberRewards( Storage storage self, bytes memory groupPubKey ) internal view returns (uint256) { return self.groupMemberRewards[groupPubKey]; } /** * @dev Gets group public key. */ function getGroupPublicKey( Storage storage self, uint256 groupIndex ) internal view returns (bytes memory) { return self.groups[groupIndex].groupPubKey; } /** * @dev Gets group member. */ function getGroupMember( Storage storage self, bytes memory groupPubKey, uint256 memberIndex ) internal view returns (address) { return self.groupMembers[groupPubKey][memberIndex]; } /** * @dev Gets all indices in the provided group for a member. */ function getGroupMemberIndices( Storage storage self, bytes memory groupPubKey, address member ) public view returns (uint256[] memory indices) { uint256 counter; for (uint i = 0; i < self.groupMembers[groupPubKey].length; i++) { if (self.groupMembers[groupPubKey][i] == member) { counter++; } } indices = new uint256[](counter); counter = 0; for (uint i = 0; i < self.groupMembers[groupPubKey].length; i++) { if (self.groupMembers[groupPubKey][i] == member) { indices[counter] = i; counter++; } } } /** * @dev Terminates group. */ function terminateGroup( Storage storage self, uint256 groupIndex ) internal { self.terminatedGroups.push(groupIndex); } /** * @dev Checks if group with the given index is terminated. */ function isGroupTerminated( Storage storage self, uint256 groupIndex ) internal view returns(bool) { for (uint i = 0; i < self.terminatedGroups.length; i++) { if (self.terminatedGroups[i] == groupIndex) { return true; } } return false; } /** * @dev Checks if group with the given public key is registered. */ function isGroupRegistered( Storage storage self, bytes memory groupPubKey ) internal view returns(bool) { for (uint i = 0; i < self.groups.length; i++) { if (self.groups[i].groupPubKey.equalStorage(groupPubKey)) { return true; } } return false; } /** * @dev Gets the cutoff time in blocks until which the given group is * considered as an active group assuming it hasn't been terminated before. */ function groupActiveTimeOf( Storage storage self, Group memory group ) internal view returns(uint256) { return group.registrationBlockHeight.add(self.groupActiveTime); } /** * @dev Gets the cutoff time in blocks after which the given group is * considered as stale. Stale group is an expired group which is no longer * performing any operations. */ function groupStaleTime( Storage storage self, Group memory group ) internal view returns(uint256) { return groupActiveTimeOf(self, group).add(self.relayEntryTimeout); } /** * @dev Checks if a group with the given public key is a stale group. * Stale group is an expired group which is no longer performing any * operations. It is important to understand that an expired group may * still perform some operations for which it was selected when it was still * active. We consider a group to be stale when it's expired and when its * expiration time and potentially executed operation timeout are both in * the past. */ function isStaleGroup( Storage storage self, bytes memory groupPubKey ) public view returns(bool) { for (uint i = 0; i < self.groups.length; i++) { if (self.groups[i].groupPubKey.equalStorage(groupPubKey)) { bool isExpired = self.expiredGroupOffset > i; bool isStale = groupStaleTime(self, self.groups[i]) < block.number; return isExpired && isStale; } } revert("Group does not exist"); } /** * @dev Checks if a group with the given index is a stale group. * Stale group is an expired group which is no longer performing any * operations. It is important to understand that an expired group may * still perform some operations for which it was selected when it was still * active. We consider a group to be stale when it's expired and when its * expiration time and potentially executed operation timeout are both in * the past. */ function isStaleGroup( Storage storage self, uint256 groupIndex ) public view returns(bool) { return groupStaleTime(self, self.groups[groupIndex]) < block.number; } /** * @dev Gets the number of active groups. Expired and terminated groups are * not counted as active. */ function numberOfGroups( Storage storage self ) internal view returns(uint256) { return self.groups.length.sub(self.expiredGroupOffset).sub(self.terminatedGroups.length); } /** * @dev Goes through groups starting from the oldest one that is still * active and checks if it hasn't expired. If so, updates the information * about expired groups so that all expired groups are marked as such. */ function expireOldGroups(Storage storage self) internal { // move expiredGroupOffset as long as there are some groups that should // be marked as expired while(groupActiveTimeOf(self, self.groups[self.expiredGroupOffset]) < block.number) { self.expiredGroupOffset++; } // Go through all terminatedGroups and if some of the terminated // groups are expired, remove them from terminatedGroups collection. // This is needed because we evaluate the shift of selected group index // based on how many non-expired groups has been terminated. for (uint i = 0; i < self.terminatedGroups.length; i++) { if (self.expiredGroupOffset > self.terminatedGroups[i]) { self.terminatedGroups[i] = self.terminatedGroups[self.terminatedGroups.length - 1]; self.terminatedGroups.length--; } } } /** * @dev Returns an index of a randomly selected active group. Terminated and * expired groups are not considered as active. * Before new group is selected, information about expired groups * is updated. At least one active group needs to be present for this * function to succeed. * @param seed Random number used as a group selection seed. */ function selectGroup( Storage storage self, uint256 seed ) public returns(uint256) { require(numberOfGroups(self) > 0, "At least one active group required"); expireOldGroups(self); uint256 selectedGroup = seed % numberOfGroups(self); return shiftByTerminatedGroups(self, shiftByExpiredGroups(self, selectedGroup)); } /** * @dev Evaluates the shift of selected group index based on the number of * expired groups. */ function shiftByExpiredGroups( Storage storage self, uint256 selectedIndex ) internal view returns(uint256) { return self.expiredGroupOffset.add(selectedIndex); } /** * @dev Evaluates the shift of selected group index based on the number of * non-expired, terminated groups. */ function shiftByTerminatedGroups( Storage storage self, uint256 selectedIndex ) internal view returns(uint256) { uint256 shiftedIndex = selectedIndex; for (uint i = 0; i < self.terminatedGroups.length; i++) { if (self.terminatedGroups[i] <= shiftedIndex) { shiftedIndex++; } } return shiftedIndex; } /** * @dev Withdraws accumulated group member rewards for operator * using the provided group index and member indices. Once the * accumulated reward is withdrawn from the selected group, member is * removed from it. Rewards can be withdrawn only from stale group. * @param operator Operator address. * @param groupIndex Group index. * @param groupMemberIndices Array of member indices for the group member. */ function withdrawFromGroup( Storage storage self, address operator, uint256 groupIndex, uint256[] memory groupMemberIndices ) public returns (uint256 rewards) { bool isExpired = self.expiredGroupOffset > groupIndex; bool isStale = isStaleGroup(self, groupIndex); require(isExpired && isStale, "Group must be expired and stale"); bytes memory groupPublicKey = getGroupPublicKey(self, groupIndex); for (uint i = 0; i < groupMemberIndices.length; i++) { if (operator == self.groupMembers[groupPublicKey][groupMemberIndices[i]]) { delete self.groupMembers[groupPublicKey][groupMemberIndices[i]]; rewards = rewards.add(self.groupMemberRewards[groupPublicKey]); } } } /** * @dev Returns addresses of all the members in the provided group. */ function membersOf( Storage storage self, bytes memory groupPubKey ) public view returns (address[] memory members) { return self.groupMembers[groupPubKey]; } /** * @dev Returns addresses of all the members in the provided group. */ function membersOf( Storage storage self, uint256 groupIndex ) public view returns (address[] memory members) { bytes memory groupPubKey = self.groups[groupIndex].groupPubKey; return self.groupMembers[groupPubKey]; } /** * @dev Reports unauthorized signing for the provided group. Must provide * a valid signature of the group address as a message. Successful signature * verification means the private key has been leaked and all group members * should be punished by seizing their tokens. The submitter of this proof is * rewarded with 5% of the total seized amount scaled by the reward adjustment * parameter and the rest 95% is burned. Group has to be active or expired. * Unauthorized signing cannot be reported for stale or terminated group. * In case of reporting unauthorized signing for stale group, * terminated group, or when the signature is inavlid, function reverts. */ function reportUnauthorizedSigning( Storage storage self, uint256 groupIndex, bytes memory signedMsgSender, uint256 minimumStake ) public { require(!isStaleGroup(self, groupIndex), "Group can not be stale"); bytes memory groupPubKey = getGroupPublicKey(self, groupIndex); bool isSignatureValid = BLS.verifyBytes(groupPubKey, abi.encodePacked(msg.sender), signedMsgSender); if (!isGroupTerminated(self, groupIndex) && isSignatureValid) { terminateGroup(self, groupIndex); self.stakingContract.seize(minimumStake, 100, msg.sender, self.groupMembers[groupPubKey]); } else { revert("Group is terminated or the signature is invalid"); } } function reportRelayEntryTimeout( Storage storage self, uint256 groupIndex, uint256 groupSize, uint256 minimumStake ) public { terminateGroup(self, groupIndex); // Reward is limited to min(1, 20 / group_size) of the maximum tattletale reward, see the Yellow Paper for more details. uint256 rewardAdjustment = uint256(20 * 100).div(groupSize); // Reward adjustment in percentage rewardAdjustment = rewardAdjustment > 100 ? 100:rewardAdjustment; // Reward adjustment can be 100% max self.stakingContract.seize(minimumStake, rewardAdjustment, msg.sender, membersOf(self, groupIndex)); } /** * @dev Returns members of the given group by group public key. * * @param groupPubKey Group public key. */ function getGroupMembers(Storage storage self, bytes memory groupPubKey) public view returns (address[] memory ) { return self.groupMembers[groupPubKey]; } }
Returns addresses of all the members in the provided group./
function membersOf( Storage storage self, bytes memory groupPubKey ) public view returns (address[] memory members) { return self.groupMembers[groupPubKey]; }
12,536,065
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./lib/ReEncryptionValidator.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./proxy/Upgradeable.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; /** * @title Adjudicator * @notice Supervises stakers' behavior and punishes when something's wrong. * @dev |v2.1.2| */ contract Adjudicator is Upgradeable { using SafeMath for uint256; using UmbralDeserializer for bytes; event CFragEvaluated( bytes32 indexed evaluationHash, address indexed investigator, bool correctness ); event IncorrectCFragVerdict( bytes32 indexed evaluationHash, address indexed worker, address indexed staker ); // used only for upgrading bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0); address constant RESERVED_ADDRESS = address(0); StakingEscrow public immutable escrow; SignatureVerifier.HashAlgorithm public immutable hashAlgorithm; uint256 public immutable basePenalty; uint256 public immutable penaltyHistoryCoefficient; uint256 public immutable percentagePenaltyCoefficient; uint256 public immutable rewardCoefficient; mapping (address => uint256) public penaltyHistory; mapping (bytes32 => bool) public evaluatedCFrags; /** * @param _escrow Escrow contract * @param _hashAlgorithm Hashing algorithm * @param _basePenalty Base for the penalty calculation * @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history * @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty * @param _rewardCoefficient Coefficient for calculating the reward */ constructor( StakingEscrow _escrow, SignatureVerifier.HashAlgorithm _hashAlgorithm, uint256 _basePenalty, uint256 _penaltyHistoryCoefficient, uint256 _percentagePenaltyCoefficient, uint256 _rewardCoefficient ) { // Sanity checks. require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address. // The reward and penalty coefficients are set. _percentagePenaltyCoefficient != 0 && _rewardCoefficient != 0); escrow = _escrow; hashAlgorithm = _hashAlgorithm; basePenalty = _basePenalty; percentagePenaltyCoefficient = _percentagePenaltyCoefficient; penaltyHistoryCoefficient = _penaltyHistoryCoefficient; rewardCoefficient = _rewardCoefficient; } /** * @notice Submit proof that a worker created wrong CFrag * @param _capsuleBytes Serialized capsule * @param _cFragBytes Serialized CFrag * @param _cFragSignature Signature of CFrag by worker * @param _taskSignature Signature of task specification by Bob * @param _requesterPublicKey Bob's signing public key, also known as "stamp" * @param _workerPublicKey Worker's signing public key, also known as "stamp" * @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key * @param _preComputedData Additional pre-computed data for CFrag correctness verification */ function evaluateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _cFragSignature, bytes memory _taskSignature, bytes memory _requesterPublicKey, bytes memory _workerPublicKey, bytes memory _workerIdentityEvidence, bytes memory _preComputedData ) public { // 1. Check that CFrag is not evaluated yet bytes32 evaluationHash = SignatureVerifier.hash( abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm); require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated."); evaluatedCFrags[evaluationHash] = true; // 2. Verify correctness of re-encryption bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData); emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect); // 3. Verify associated public keys and signatures require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey), "Staker's public key is invalid"); require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey), "Requester's public key is invalid"); UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData(); // Verify worker's signature of CFrag require(SignatureVerifier.verify( _cFragBytes, abi.encodePacked(_cFragSignature, precomp.lostBytes[1]), _workerPublicKey, hashAlgorithm), "CFrag signature is invalid" ); // Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag(); require(SignatureVerifier.verify( _taskSignature, abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]), _workerPublicKey, hashAlgorithm), "Task signature is invalid" ); // Verify that _taskSignature is bob's signature of the task specification. // A task specification is: capsule + ursula pubkey + alice address + blockhash bytes32 stampXCoord; assembly { stampXCoord := mload(add(_workerPublicKey, 32)) } bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord); require(SignatureVerifier.verify( abi.encodePacked(_capsuleBytes, stamp, _workerIdentityEvidence, precomp.alicesKeyAsAddress, bytes32(0)), abi.encodePacked(_taskSignature, precomp.lostBytes[3]), _requesterPublicKey, hashAlgorithm), "Specification signature is invalid" ); // 4. Extract worker address from stamp signature. address worker = SignatureVerifier.recover( SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures _workerIdentityEvidence); address staker = escrow.stakerFromWorker(worker); require(staker != address(0), "Worker must be related to a staker"); // 5. Check that staker can be slashed uint256 stakerValue = escrow.getAllTokens(staker); require(stakerValue > 0, "Staker has no tokens"); // 6. If CFrag was incorrect, slash staker if (!cFragIsCorrect) { (uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue); escrow.slashStaker(staker, penalty, msg.sender, reward); emit IncorrectCFragVerdict(evaluationHash, worker, staker); } } /** * @notice Calculate penalty to the staker and reward to the investigator * @param _staker Staker's address * @param _stakerValue Amount of tokens that belong to the staker */ function calculatePenaltyAndReward(address _staker, uint256 _stakerValue) internal returns (uint256 penalty, uint256 reward) { penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker])); penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient)); reward = penalty.div(rewardCoefficient); // TODO add maximum condition or other overflow protection or other penalty condition (#305?) penaltyHistory[_staker] = penaltyHistory[_staker].add(1); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) == (evaluatedCFrags[evaluationCFragHash] ? 1 : 0)); require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) == penaltyHistory[RESERVED_ADDRESS]); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // preparation for the verifyState method bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); evaluatedCFrags[evaluationCFragHash] = true; penaltyHistory[RESERVED_ADDRESS] = 123; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./UmbralDeserializer.sol"; import "./SignatureVerifier.sol"; /** * @notice Validates re-encryption correctness. */ library ReEncryptionValidator { using UmbralDeserializer for bytes; //------------------------------// // Umbral-specific constants // //------------------------------// // See parameter `u` of `UmbralParameters` class in pyUmbral // https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02; uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f; uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936; //------------------------------// // SECP256K1-specific constants // //------------------------------// // Base field order uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // -2 mod FIELD_ORDER uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d; // (-1/2) mod FIELD_ORDER uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17; // /** * @notice Check correctness of re-encryption * @param _capsuleBytes Capsule * @param _cFragBytes Capsule frag * @param _precomputedBytes Additional precomputed data */ function validateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _precomputedBytes ) internal pure returns (bool) { UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule(); UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag(); UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData(); // Extract Alice's address and check that it corresponds to the one provided address alicesAddress = SignatureVerifier.recover( _precomputed.hashedKFragValidityMessage, abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0]) ); require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature"); // Compute proof's challenge scalar h, used in all ZKP verification equations uint256 h = computeProofChallengeScalar(_capsule, _cFrag); ////// // Verifying 1st equation: z*E == h*E_1 + E_2 ////// // Input validation: E require(checkCompressedPoint( _capsule.pointE.sign, _capsule.pointE.xCoord, _precomputed.pointEyCoord), "Precomputed Y coordinate of E doesn't correspond to compressed E point" ); // Input validation: z*E require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord), "Point zE is not a valid EC point" ); require(ecmulVerify( _capsule.pointE.xCoord, // E_x _precomputed.pointEyCoord, // E_y _cFrag.proof.bnSig, // z _precomputed.pointEZxCoord, // zE_x _precomputed.pointEZyCoord), // zE_y "Precomputed z*E value is incorrect" ); // Input validation: E1 require(checkCompressedPoint( _cFrag.pointE1.sign, // E1_sign _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord), // E1_y "Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point" ); // Input validation: h*E1 require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord), "Point h*E1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord, // E1_y h, _precomputed.pointE1HxCoord, // hE1_x _precomputed.pointE1HyCoord), // hE1_y "Precomputed h*E1 value is incorrect" ); // Input validation: E2 require(checkCompressedPoint( _cFrag.proof.pointE2.sign, // E2_sign _cFrag.proof.pointE2.xCoord, // E2_x _precomputed.pointE2yCoord), // E2_y "Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point" ); bool equation_holds = eqAffineJacobian( [_precomputed.pointEZxCoord, _precomputed.pointEZyCoord], addAffineJacobian( [_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord], [_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 2nd equation: z*V == h*V_1 + V_2 ////// // Input validation: V require(checkCompressedPoint( _capsule.pointV.sign, _capsule.pointV.xCoord, _precomputed.pointVyCoord), "Precomputed Y coordinate of V doesn't correspond to compressed V point" ); // Input validation: z*V require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord), "Point zV is not a valid EC point" ); require(ecmulVerify( _capsule.pointV.xCoord, // V_x _precomputed.pointVyCoord, // V_y _cFrag.proof.bnSig, // z _precomputed.pointVZxCoord, // zV_x _precomputed.pointVZyCoord), // zV_y "Precomputed z*V value is incorrect" ); // Input validation: V1 require(checkCompressedPoint( _cFrag.pointV1.sign, // V1_sign _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord), // V1_y "Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point" ); // Input validation: h*V1 require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord), "Point h*V1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord, // V1_y h, _precomputed.pointV1HxCoord, // h*V1_x _precomputed.pointV1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: V2 require(checkCompressedPoint( _cFrag.proof.pointV2.sign, // V2_sign _cFrag.proof.pointV2.xCoord, // V2_x _precomputed.pointV2yCoord), // V2_y "Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointVZxCoord, _precomputed.pointVZyCoord], addAffineJacobian( [_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord], [_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 3rd equation: z*U == h*U_1 + U_2 ////// // We don't have to validate U since it's fixed and hard-coded // Input validation: z*U require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord), "Point z*U is not a valid EC point" ); require(ecmulVerify( UMBRAL_PARAMETER_U_XCOORD, // U_x UMBRAL_PARAMETER_U_YCOORD, // U_y _cFrag.proof.bnSig, // z _precomputed.pointUZxCoord, // zU_x _precomputed.pointUZyCoord), // zU_y "Precomputed z*U value is incorrect" ); // Input validation: U1 (a.k.a. KFragCommitment) require(checkCompressedPoint( _cFrag.proof.pointKFragCommitment.sign, // U1_sign _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord), // U1_y "Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point" ); // Input validation: h*U1 require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord), "Point h*U1 is not a valid EC point" ); require(ecmulVerify( _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord, // U1_y h, _precomputed.pointU1HxCoord, // h*V1_x _precomputed.pointU1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: U2 (a.k.a. KFragPok ("proof of knowledge")) require(checkCompressedPoint( _cFrag.proof.pointKFragPok.sign, // U2_sign _cFrag.proof.pointKFragPok.xCoord, // U2_x _precomputed.pointU2yCoord), // U2_y "Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointUZxCoord, _precomputed.pointUZyCoord], addAffineJacobian( [_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord], [_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord] ) ); return equation_holds; } function computeProofChallengeScalar( UmbralDeserializer.Capsule memory _capsule, UmbralDeserializer.CapsuleFrag memory _cFrag ) internal pure returns (uint256) { // Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata) bytes memory hashInput = abi.encodePacked( // Point E _capsule.pointE.sign, _capsule.pointE.xCoord, // Point E1 _cFrag.pointE1.sign, _cFrag.pointE1.xCoord, // Point E2 _cFrag.proof.pointE2.sign, _cFrag.proof.pointE2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point V _capsule.pointV.sign, _capsule.pointV.xCoord, // Point V1 _cFrag.pointV1.sign, _cFrag.pointV1.xCoord, // Point V2 _cFrag.proof.pointV2.sign, _cFrag.proof.pointV2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point U bytes1(UMBRAL_PARAMETER_U_SIGN), bytes32(UMBRAL_PARAMETER_U_XCOORD), // Point U1 _cFrag.proof.pointKFragCommitment.sign, _cFrag.proof.pointKFragCommitment.xCoord, // Point U2 _cFrag.proof.pointKFragPok.sign, _cFrag.proof.pointKFragPok.xCoord, // Re-encryption metadata _cFrag.proof.metadata ); uint256 h = extendedKeccakToBN(hashInput); return h; } function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) { bytes32 upper; bytes32 lower; // Umbral prepends to the data a customization string of 64-bytes. // In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes. bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data); (upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)), keccak256(abi.encodePacked(uint8(0x01), input))); // Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1) // n_minus_1 = n - 1 // delta = 2^256 mod n_minus_1 uint256 delta = 0x14551231950b75fc4402da1732fc9bec0; uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140; uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1); return 1 + addmod(upper_half, uint256(lower), n_minus_1); } /// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate /// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise /// @param _pointX The X coordinate of an EC point in affine representation /// @param _pointY The Y coordinate of an EC point in affine representation /// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY) function checkCompressedPoint( uint8 _pointSign, uint256 _pointX, uint256 _pointY ) internal pure returns(bool) { bool correct_sign = _pointY % 2 == _pointSign - 2; return correct_sign && isOnCurve(_pointX, _pointY); } /// @notice Tests if the given serialized coordinates represent a valid EC point /// @param _coords The concatenation of serialized X and Y coordinates /// @return true iff coordinates X and Y are a valid point function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) { require(_coords.length == 64, "Serialized coordinates should be 64 B"); uint256 coordX; uint256 coordY; assembly { coordX := mload(add(_coords, 32)) coordY := mload(add(_coords, 64)) } return isOnCurve(coordX, coordY); } /// @notice Tests if a point is on the secp256k1 curve /// @param Px The X coordinate of an EC point in affine representation /// @param Py The Y coordinate of an EC point in affine representation /// @return true if (Px, Py) is a valid secp256k1 point; false otherwise function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) { uint256 p = FIELD_ORDER; if (Px >= p || Py >= p){ return false; } uint256 y2 = mulmod(Py, Py, p); uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p); return y2 == x3_plus_7; } // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4 function ecmulVerify( uint256 x1, uint256 y1, uint256 scalar, uint256 qx, uint256 qy ) internal pure returns(bool) { uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order))); address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return xyAddress == signer; } /// @notice Equality test of two points, in affine and Jacobian coordinates respectively /// @param P An EC point in affine coordinates /// @param Q An EC point in Jacobian coordinates /// @return true if P and Q represent the same point in affine coordinates; false otherwise function eqAffineJacobian( uint256[2] memory P, uint256[3] memory Q ) internal pure returns(bool){ uint256 Qz = Q[2]; if(Qz == 0){ return false; // Q is zero but P isn't. } uint256 p = FIELD_ORDER; uint256 Q_z_squared = mulmod(Qz, Qz, p); return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1]; } /// @notice Adds two points in affine coordinates, with the result in Jacobian /// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3 /// @param P An EC point in affine coordinates /// @param Q An EC point in affine coordinates /// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256 function addAffineJacobian( uint[2] memory P, uint[2] memory Q ) internal pure returns (uint[3] memory R) { uint256 p = FIELD_ORDER; uint256 a = P[0]; uint256 c = P[1]; uint256 t0 = Q[0]; uint256 t1 = Q[1]; if ((a == t0) && (c == t1)){ return doubleJacobian([a, c, 1]); } uint256 d = addmod(t1, p-c, p); // d = t1 - c uint256 b = addmod(t0, p-a, p); // b = t0 - a uint256 e = mulmod(b, b, p); // e = b^2 uint256 f = mulmod(e, b, p); // f = b^3 uint256 g = mulmod(a, e, p); R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p); R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p); R[2] = b; } /// @notice Point doubling in Jacobian coordinates /// @param P An EC point in Jacobian coordinates. /// @return Q An EC point in Jacobian coordinates function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) { uint256 z = P[2]; if (z == 0) return Q; uint256 p = FIELD_ORDER; uint256 x = P[0]; uint256 _2y = mulmod(2, P[1], p); uint256 _4yy = mulmod(_2y, _2y, p); uint256 s = mulmod(_4yy, x, p); uint256 m = mulmod(3, mulmod(x, x, p), p); uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p); Q[0] = t; Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p); Q[2] = mulmod(_2y, z, p); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Deserialization library for Umbral objects */ library UmbralDeserializer { struct Point { uint8 sign; uint256 xCoord; } struct Capsule { Point pointE; Point pointV; uint256 bnSig; } struct CorrectnessProof { Point pointE2; Point pointV2; Point pointKFragCommitment; Point pointKFragPok; uint256 bnSig; bytes kFragSignature; // 64 bytes bytes metadata; // any length } struct CapsuleFrag { Point pointE1; Point pointV1; bytes32 kFragId; Point pointPrecursor; CorrectnessProof proof; } struct PreComputedData { uint256 pointEyCoord; uint256 pointEZxCoord; uint256 pointEZyCoord; uint256 pointE1yCoord; uint256 pointE1HxCoord; uint256 pointE1HyCoord; uint256 pointE2yCoord; uint256 pointVyCoord; uint256 pointVZxCoord; uint256 pointVZyCoord; uint256 pointV1yCoord; uint256 pointV1HxCoord; uint256 pointV1HyCoord; uint256 pointV2yCoord; uint256 pointUZxCoord; uint256 pointUZyCoord; uint256 pointU1yCoord; uint256 pointU1HxCoord; uint256 pointU1HyCoord; uint256 pointU2yCoord; bytes32 hashedKFragValidityMessage; address alicesKeyAsAddress; bytes5 lostBytes; } uint256 constant BIGNUM_SIZE = 32; uint256 constant POINT_SIZE = 33; uint256 constant SIGNATURE_SIZE = 64; uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE; uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE; uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE; uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE; uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5; /** * @notice Deserialize to capsule (not activated) */ function toCapsule(bytes memory _capsuleBytes) internal pure returns (Capsule memory capsule) { require(_capsuleBytes.length == CAPSULE_SIZE); uint256 pointer = getPointer(_capsuleBytes); pointer = copyPoint(pointer, capsule.pointE); pointer = copyPoint(pointer, capsule.pointV); capsule.bnSig = uint256(getBytes32(pointer)); } /** * @notice Deserialize to correctness proof * @param _pointer Proof bytes memory pointer * @param _proofBytesLength Proof bytes length */ function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength) internal pure returns (CorrectnessProof memory proof) { require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE); _pointer = copyPoint(_pointer, proof.pointE2); _pointer = copyPoint(_pointer, proof.pointV2); _pointer = copyPoint(_pointer, proof.pointKFragCommitment); _pointer = copyPoint(_pointer, proof.pointKFragPok); proof.bnSig = uint256(getBytes32(_pointer)); _pointer += BIGNUM_SIZE; proof.kFragSignature = new bytes(SIGNATURE_SIZE); // TODO optimize, just two mload->mstore (#1500) _pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE); if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) { proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE); copyBytes(_pointer, proof.metadata, proof.metadata.length); } } /** * @notice Deserialize to correctness proof */ function toCorrectnessProof(bytes memory _proofBytes) internal pure returns (CorrectnessProof memory proof) { uint256 pointer = getPointer(_proofBytes); return toCorrectnessProof(pointer, _proofBytes.length); } /** * @notice Deserialize to CapsuleFrag */ function toCapsuleFrag(bytes memory _cFragBytes) internal pure returns (CapsuleFrag memory cFrag) { uint256 cFragBytesLength = _cFragBytes.length; require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE); uint256 pointer = getPointer(_cFragBytes); pointer = copyPoint(pointer, cFrag.pointE1); pointer = copyPoint(pointer, cFrag.pointV1); cFrag.kFragId = getBytes32(pointer); pointer += BIGNUM_SIZE; pointer = copyPoint(pointer, cFrag.pointPrecursor); cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE); } /** * @notice Deserialize to precomputed data */ function toPreComputedData(bytes memory _preComputedData) internal pure returns (PreComputedData memory data) { require(_preComputedData.length == PRECOMPUTED_DATA_SIZE); uint256 initial_pointer = getPointer(_preComputedData); uint256 pointer = initial_pointer; data.pointEyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.hashedKFragValidityMessage = getBytes32(pointer); pointer += 32; data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer))); pointer += 20; // Lost bytes: a bytes5 variable holding the following byte values: // 0: kfrag signature recovery value v // 1: cfrag signature recovery value v // 2: metadata signature recovery value v // 3: specification signature recovery value v // 4: ursula pubkey sign byte data.lostBytes = bytes5(getBytes32(pointer)); pointer += 5; require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE); } // TODO extract to external library if needed (#1500) /** * @notice Get the memory pointer for start of array */ function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) { assembly { pointer := add(_bytes, 32) // skip array length } } /** * @notice Copy point data from memory in the pointer position */ function copyPoint(uint256 _pointer, Point memory _point) internal pure returns (uint256 resultPointer) { // TODO optimize, copy to point memory directly (#1500) uint8 temp; uint256 xCoord; assembly { temp := byte(0, mload(_pointer)) xCoord := mload(add(_pointer, 1)) } _point.sign = temp; _point.xCoord = xCoord; resultPointer = _pointer + POINT_SIZE; } /** * @notice Read 1 byte from memory in the pointer position */ function getByte(uint256 _pointer) internal pure returns (byte result) { bytes32 word; assembly { word := mload(_pointer) } result = word[0]; return result; } /** * @notice Read 32 bytes from memory in the pointer position */ function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) { assembly { result := mload(_pointer) } } /** * @notice Copy bytes from the source pointer to the target array * @dev Assumes that enough memory has been allocated to store in target. * Also assumes that '_target' was the last thing that was allocated * @param _bytesPointer Source memory pointer * @param _target Target array * @param _bytesLength Number of bytes to copy */ function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength) internal pure returns (uint256 resultPointer) { // Exploiting the fact that '_target' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { // evm operations on words let words := div(add(_bytesLength, 31), 32) let source := _bytesPointer let destination := add(_target, 32) for { let i := 0 } // start at arr + 32 -> first byte corresponds to length lt(i, words) { i := add(i, 1) } { let offset := mul(i, 32) mstore(add(destination, offset), mload(add(source, offset))) } mstore(add(_target, add(32, mload(_target))), 0) } resultPointer = _bytesPointer + _bytesLength; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Library to recover address and verify signatures * @dev Simple wrapper for `ecrecover` */ library SignatureVerifier { enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160} // Header for Version E as defined by EIP191. First byte ('E') is also the version bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n"; /** * @notice Recover signer address from hash and signature * @param _hash 32 bytes message hash * @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28) */ function recover(bytes32 _hash, bytes memory _signature) internal pure returns (address) { require(_signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); return ecrecover(_hash, v, r, s); } /** * @notice Transform public key to address * @param _publicKey secp256k1 public key */ function toAddress(bytes memory _publicKey) internal pure returns (address) { return address(uint160(uint256(keccak256(_publicKey)))); } /** * @notice Hash using one of pre built hashing algorithm * @param _message Signed message * @param _algorithm Hashing algorithm */ function hash(bytes memory _message, HashAlgorithm _algorithm) internal pure returns (bytes32 result) { if (_algorithm == HashAlgorithm.KECCAK256) { result = keccak256(_message); } else if (_algorithm == HashAlgorithm.SHA256) { result = sha256(_message); } else { result = ripemd160(_message); } } /** * @notice Verify ECDSA signature * @dev Uses one of pre built hashing algorithm * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _algorithm Hashing algorithm */ function verify( bytes memory _message, bytes memory _signature, bytes memory _publicKey, HashAlgorithm _algorithm ) internal pure returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature); } /** * @notice Hash message according to EIP191 signature specification * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Message to sign * @param _version EIP191 version to use */ function hashEIP191( bytes memory _message, byte _version ) internal view returns (bytes32 result) { if(_version == byte(0x00)){ // Version 0: Data with intended validator address validator = address(this); return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message)); } else if (_version == byte(0x45)){ // Version E: personal_sign messages uint256 length = _message.length; require(length > 0, "Empty message not allowed for version E"); // Compute text-encoded length of message uint256 digits = 0; while (length != 0) { digits++; length /= 10; } bytes memory lengthAsText = new bytes(digits); length = _message.length; uint256 index = digits - 1; while (length != 0) { lengthAsText[index--] = byte(uint8(48 + length % 10)); length /= 10; } return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message)); } else { revert("Unsupported EIP191 version"); } } /** * @notice Verify EIP191 signature * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _version EIP191 version to use */ function verifyEIP191( bytes memory _message, bytes memory _signature, bytes memory _publicKey, byte _version ) internal view returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../aragon/interfaces/IERC900History.sol"; import "./Issuer.sol"; import "./lib/Bits.sol"; import "./lib/Snapshot.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @notice PolicyManager interface */ interface PolicyManagerInterface { function secondsPerPeriod() external view returns (uint32); function register(address _node, uint16 _period) external; function migrate(address _node) external; function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external; } /** * @notice Adjudicator interface */ interface AdjudicatorInterface { function rewardCoefficient() external view returns (uint32); } /** * @notice WorkLock interface */ interface WorkLockInterface { function token() external view returns (NuCypherToken); } /** * @title StakingEscrowStub * @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable * @dev |v1.0.0| */ contract StakingEscrowStub is Upgradeable { using AdditionalMath for uint32; NuCypherToken public immutable token; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; uint16 public immutable minLockedPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; /** * @notice Predefines some variables for use when deploying other contracts * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens ) { require(_token.totalSupply() > 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); // we have to use real values even though this is a stub require(address(delegateGet(_testTarget, this.token.selector)) == address(token)); // TODO uncomment after merging this PR #2579 // require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod); require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod); require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods); require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens); require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens); } } /** * @title StakingEscrow * @notice Contract holds and locks stakers tokens. * Each staker that locks their tokens will receive some compensation * @dev |v5.7.1| */ contract StakingEscrow is Issuer, IERC900History { using AdditionalMath for uint256; using AdditionalMath for uint16; using Bits for uint256; using SafeMath for uint256; using Snapshot for uint128[]; using SafeERC20 for NuCypherToken; /** * @notice Signals that tokens were deposited * @param staker Staker address * @param value Amount deposited (in NuNits) * @param periods Number of periods tokens will be locked */ event Deposited(address indexed staker, uint256 value, uint16 periods); /** * @notice Signals that tokens were stake locked * @param staker Staker address * @param value Amount locked (in NuNits) * @param firstPeriod Starting lock period * @param periods Number of periods tokens will be locked */ event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); /** * @notice Signals that a sub-stake was divided * @param staker Staker address * @param oldValue Old sub-stake value (in NuNits) * @param lastPeriod Final locked period of old sub-stake * @param newValue New sub-stake value (in NuNits) * @param periods Number of periods to extend sub-stake */ event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); /** * @notice Signals that two sub-stakes were merged * @param staker Staker address * @param value1 Value of first sub-stake (in NuNits) * @param value2 Value of second sub-stake (in NuNits) * @param lastPeriod Final locked period of merged sub-stake */ event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); /** * @notice Signals that a sub-stake was prolonged * @param staker Staker address * @param value Value of sub-stake * @param lastPeriod Final locked period of old sub-stake * @param periods Number of periods sub-stake was extended */ event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); /** * @notice Signals that tokens were withdrawn to the staker * @param staker Staker address * @param value Amount withdraws (in NuNits) */ event Withdrawn(address indexed staker, uint256 value); /** * @notice Signals that the worker associated with the staker made a commitment to next period * @param staker Staker address * @param period Period committed to * @param value Amount of tokens staked for the committed period */ event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that tokens were minted for previous periods * @param staker Staker address * @param period Previous period tokens minted for * @param value Amount minted (in NuNits) */ event Minted(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that the staker was slashed * @param staker Staker address * @param penalty Slashing penalty * @param investigator Investigator address * @param reward Value of reward provided to investigator (in NuNits) */ event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); /** * @notice Signals that the restake parameter was activated/deactivated * @param staker Staker address * @param reStake Updated parameter value */ event ReStakeSet(address indexed staker, bool reStake); /** * @notice Signals that a worker was bonded to the staker * @param staker Staker address * @param worker Worker address * @param startPeriod Period bonding occurred */ event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); /** * @notice Signals that the winddown parameter was activated/deactivated * @param staker Staker address * @param windDown Updated parameter value */ event WindDownSet(address indexed staker, bool windDown); /** * @notice Signals that the snapshot parameter was activated/deactivated * @param staker Staker address * @param snapshotsEnabled Updated parameter value */ event SnapshotSet(address indexed staker, bool snapshotsEnabled); /** * @notice Signals that the staker migrated their stake to the new period length * @param staker Staker address * @param period Period when migration happened */ event Migrated(address indexed staker, uint16 indexed period); /// internal event event WorkMeasurementSet(address indexed staker, bool measureWork); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 unlockingDuration; uint128 lockedValue; } struct Downtime { uint16 startPeriod; uint16 endPeriod; } struct StakerInfo { uint256 value; /* * Stores periods that are committed but not yet rewarded. * In order to optimize storage, only two values are used instead of an array. * commitToNextPeriod() method invokes mint() method so there can only be two committed * periods that are not yet rewarded: the current and the next periods. */ uint16 currentCommittedPeriod; uint16 nextCommittedPeriod; uint16 lastCommittedPeriod; uint16 stub1; // former slot for lockReStakeUntilPeriod uint256 completedWork; uint16 workerStartPeriod; // period when worker was bonded address worker; uint256 flags; // uint256 to acquire whole slot and minimize operations on it uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; Downtime[] pastDowntime; SubStakeInfo[] subStakes; uint128[] history; } // used only for upgrading uint16 internal constant RESERVED_PERIOD = 0; uint16 internal constant MAX_CHECKED_VALUES = 5; // to prevent high gas consumption in loops for slashing uint16 public constant MAX_SUB_STAKES = 30; uint16 internal constant MAX_UINT16 = 65535; // indices for flags uint8 internal constant RE_STAKE_DISABLED_INDEX = 0; uint8 internal constant WIND_DOWN_INDEX = 1; uint8 internal constant MEASURE_WORK_INDEX = 2; uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3; uint8 internal constant MIGRATED_INDEX = 4; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; PolicyManagerInterface public immutable policyManager; AdjudicatorInterface public immutable adjudicator; WorkLockInterface public immutable workLock; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod uint128[] public balanceHistory; address stub1; // former slot for PolicyManager address stub2; // former slot for Adjudicator address stub3; // former slot for WorkLock mapping (uint16 => uint256) _lockedPerPeriod; // only to make verifyState from previous version work, temporary // TODO remove after upgrade #2579 function lockedPerPeriod(uint16 _period) public view returns (uint256) { return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111; } /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @param _policyManager Policy Manager contract * @param _adjudicator Adjudicator contract * @param _workLock WorkLock contract. Zero address if there is no WorkLock * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked * @param _minWorkerPeriods Min amount of periods while a worker can't be changed */ constructor( NuCypherToken _token, PolicyManagerInterface _policyManager, AdjudicatorInterface _adjudicator, WorkLockInterface _workLock, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods ) Issuer( _token, _genesisHoursPerPeriod, _hoursPerPeriod, _issuanceDecayCoefficient, _lockDurationCoefficient1, _lockDurationCoefficient2, _maximumRewardedPeriods, _firstPhaseTotalSupply, _firstPhaseMaxIssuance ) { // constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; minWorkerPeriods = _minWorkerPeriods; require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) || _policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) && _adjudicator.rewardCoefficient() != 0 && (address(_workLock) == address(0) || _workLock.token() == _token)); policyManager = _policyManager; adjudicator = _adjudicator; workLock = _workLock; } /** * @dev Checks the existence of a staker in the contract */ modifier onlyStaker() { StakerInfo storage info = stakerInfo[msg.sender]; require((info.value > 0 || info.nextCommittedPeriod != 0) && info.flags.bitSet(MIGRATED_INDEX)); _; } //------------------------Main getters------------------------ /** * @notice Get all tokens belonging to the staker */ function getAllTokens(address _staker) external view returns (uint256) { return stakerInfo[_staker].value; } /** * @notice Get all flags for the staker */ function getFlags(address _staker) external view returns ( bool windDown, bool reStake, bool measureWork, bool snapshots, bool migrated ) { StakerInfo storage info = stakerInfo[_staker]; windDown = info.flags.bitSet(WIND_DOWN_INDEX); reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); measureWork = info.flags.bitSet(MEASURE_WORK_INDEX); snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX); migrated = info.flags.bitSet(MIGRATED_INDEX); } /** * @notice Get the start period. Use in the calculation of the last period of the sub stake * @param _info Staker structure * @param _currentPeriod Current period */ function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod) internal view returns (uint16) { // if the next period (after current) is committed if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) { return _currentPeriod + 1; } return _currentPeriod; } /** * @notice Get the last period of the sub stake * @param _subStake Sub stake structure * @param _startPeriod Pre-calculated start period */ function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod) internal view returns (uint16) { if (_subStake.lastPeriod != 0) { return _subStake.lastPeriod; } uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration; if (lastPeriod > uint32(MAX_UINT16)) { return MAX_UINT16; } return uint16(lastPeriod); } /** * @notice Get the last period of the sub stake * @param _staker Staker * @param _index Stake index */ function getLastPeriodOfSubStake(address _staker, uint256 _index) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; SubStakeInfo storage subStake = info.subStakes[_index]; uint16 startPeriod = getStartPeriod(info, getCurrentPeriod()); return getLastPeriodOfSubStake(subStake, startPeriod); } /** * @notice Get the value of locked tokens for a staker in a specified period * @dev Information may be incorrect for rewarded or not committed surpassed period * @param _info Staker structure * @param _currentPeriod Current period * @param _period Next period */ function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period) internal view returns (uint256 lockedValue) { lockedValue = 0; uint16 startPeriod = getStartPeriod(_info, _currentPeriod); for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.firstPeriod <= _period && getLastPeriodOfSubStake(subStake, startPeriod) >= _period) { lockedValue += subStake.lockedValue; } } } /** * @notice Get the value of locked tokens for a staker in a future period * @dev This function is used by PreallocationEscrow so its signature can't be updated. * @param _staker Staker * @param _offsetPeriods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _offsetPeriods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); return getLockedTokens(info, currentPeriod, nextPeriod); } /** * @notice Get the last committed staker's period * @param _staker Staker */ function getLastCommittedPeriod(address _staker) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod; } /** * @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period * as well as stakers and their locked tokens * @param _offsetPeriods Amount of periods for locked tokens calculation * @param _startIndex Start index for looking in stakers array * @param _maxStakers Max stakers for looking, if set 0 then all will be used * @return allLockedTokens Sum of locked tokens for active stakers * @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256 * @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly! */ function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_offsetPeriods > 0); uint256 endIndex = stakers.length; require(_startIndex < endIndex); if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) { endIndex = _startIndex + _maxStakers; } activeStakers = new uint256[2][](endIndex - _startIndex); allLockedTokens = 0; uint256 resultIndex = 0; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); for (uint256 i = _startIndex; i < endIndex; i++) { address staker = stakers[i]; StakerInfo storage info = stakerInfo[staker]; if (info.currentCommittedPeriod != currentPeriod && info.nextCommittedPeriod != currentPeriod) { continue; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); if (lockedTokens != 0) { activeStakers[resultIndex][0] = uint256(staker); activeStakers[resultIndex++][1] = lockedTokens; allLockedTokens += lockedTokens; } } assembly { mstore(activeStakers, resultIndex) } } /** * @notice Get worker using staker's address */ function getWorkerFromStaker(address _staker) external view returns (address) { return stakerInfo[_staker].worker; } /** * @notice Get work that completed by the staker */ function getCompletedWork(address _staker) external view returns (uint256) { return stakerInfo[_staker].completedWork; } /** * @notice Find index of downtime structure that includes specified period * @dev If specified period is outside all downtime periods, the length of the array will be returned * @param _staker Staker * @param _period Specified period number */ function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) { StakerInfo storage info = stakerInfo[_staker]; for (index = 0; index < info.pastDowntime.length; index++) { if (_period <= info.pastDowntime[index].endPeriod) { return index; } } } //------------------------Main methods------------------------ /** * @notice Start or stop measuring the work of a staker * @param _staker Staker * @param _measureWork Value for `measureWork` parameter * @return Work that was previously done */ function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) { return info.completedWork; } info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX); emit WorkMeasurementSet(_staker, _measureWork); return info.completedWork; } /** * @notice Bond worker * @param _worker Worker address. Must be a real address, not a contract */ function bondWorker(address _worker) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Specified worker is already bonded with this staker require(_worker != info.worker); uint16 currentPeriod = getCurrentPeriod(); if (info.worker != address(0)) { // If this staker had a worker ... // Check that enough time has passed to change it require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods)); // Remove the old relation "worker->staker" stakerFromWorker[info.worker] = address(0); } if (_worker != address(0)) { // Specified worker is already in use require(stakerFromWorker[_worker] == address(0)); // Specified worker is a staker require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender); // Set new worker->staker relation stakerFromWorker[_worker] = msg.sender; } // Bond new worker (or unbond if _worker == address(0)) info.worker = _worker; info.workerStartPeriod = currentPeriod; emit WorkerBonded(msg.sender, _worker, currentPeriod); } /** * @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) { return; } info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _unlockingDuration ) external { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) { info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(_staker, true); } // WorkLock still uses the genesis period length (24h) _unlockingDuration = recalculatePeriod(_unlockingDuration); deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Set `windDown` parameter. * If true then stake's duration will be decreasing in each period with `commitToNextPeriod()` * @param _windDown Value for parameter */ function setWindDown(bool _windDown) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed uint16 nextPeriod = getCurrentPeriod() + 1; if (info.nextCommittedPeriod != nextPeriod) { return; } // adjust sub-stakes duration for the new value of winding down parameter for (uint256 index = 0; index < info.subStakes.length; index++) { SubStakeInfo storage subStake = info.subStakes[index]; // sub-stake does not have fixed last period when winding down is disabled if (!_windDown && subStake.lastPeriod == nextPeriod) { subStake.lastPeriod = 0; subStake.unlockingDuration = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = nextPeriod; } } } /** * @notice Activate/deactivate taking snapshots of balances * @param _enableSnapshots True to activate snapshots, False to deactivate */ function setSnapshots(bool _enableSnapshots) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) { return; } uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); if(_enableSnapshots){ info.history.addSnapshot(info.value); balanceHistory.addSnapshot(lastGlobalBalance + info.value); } else { info.history.addSnapshot(0); balanceHistory.addSnapshot(lastGlobalBalance - info.value); } info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Adds a new snapshot to both the staker and global balance histories, * assuming the staker's balance was already changed * @param _info Reference to affected staker's struct * @param _addition Variance in balance. It can be positive or negative. */ function addSnapshot(StakerInfo storage _info, int256 _addition) internal { if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){ _info.history.addSnapshot(_info.value); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition)); } } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Deposit all tokens that were approved to transfer * @param _from Staker * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload)); } /** * @notice Deposit tokens and create new sub-stake. Use this method to become a staker * @param _staker Staker * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Deposit tokens and increase lock amount of an existing sub-stake * @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); deposit(msg.sender, msg.sender, _index, _value, 0); } /** * @notice Deposit tokens * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _payer Owner of tokens * @param _index Index of the sub stake * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { require(_value != 0); StakerInfo storage info = stakerInfo[_staker]; // A staker can't be a worker for another staker require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker); // initial stake of the staker if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); info.flags = info.flags.toggleBit(MIGRATED_INDEX); } require(info.flags.bitSet(MIGRATED_INDEX)); token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _unlockingDuration); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _unlockingDuration); } else { uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index); emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod()); } } /** * @notice Lock some tokens as a new sub-stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); lock(msg.sender, _index, _value, 0); } /** * @notice Lock some tokens as a stake * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods); } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[_staker]; uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); uint256 requestedLockedTokens = _value.add(lockedTokens); require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens); // next period is committed if (info.nextCommittedPeriod == nextPeriod) { _lockedPerPeriod[nextPeriod] += _value; emit CommitmentMade(_staker, nextPeriod, _value); } // if index was provided then increase existing sub-stake if (_index < MAX_SUB_STAKES) { lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value); // otherwise create new } else { lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration); } } /** * @notice Lock some tokens as a new sub-stake * @param _info Staker structure * @param _nextPeriod Next period * @param _staker Staker * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _unlockingDuration ) internal { uint16 duration = _unlockingDuration; // if winding down is enabled and next period is committed // then sub-stakes duration were decreased if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) { duration -= 1; } saveSubStake(_info, _nextPeriod, 0, duration, _value); emit Locked(_staker, _value, _nextPeriod, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @dev Probably will be created a new sub-stake but it will be active only one period * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _staker Staker * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, address _staker, uint256 _index, uint256 _value ) internal { SubStakeInfo storage subStake = _info.subStakes[_index]; (, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod); // create temporary sub-stake for current or previous committed periods // to leave locked amount in this period unchanged if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); } subStake.lockedValue += uint128(_value); // all new locks should start from the next period subStake.firstPeriod = _nextPeriod; emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod); } /** * @notice Checks that last period of sub-stake is greater than the current period * @param _info Staker structure * @param _subStake Sub-stake structure * @param _currentPeriod Current period * @return startPeriod Start period. Use in the calculation of the last period of the sub stake * @return lastPeriod Last period of the sub stake */ function checkLastPeriodOfSubStake( StakerInfo storage _info, SubStakeInfo storage _subStake, uint16 _currentPeriod ) internal view returns (uint16 startPeriod, uint16 lastPeriod) { startPeriod = getStartPeriod(_info, _currentPeriod); lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod); // The sub stake must be active at least in the next period require(lastPeriod > _currentPeriod); } /** * @notice Save sub stake. First tries to override inactive sub stake * @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded * @param _info Staker structure * @param _firstPeriod First period of the sub stake * @param _lastPeriod Last period of the sub stake * @param _unlockingDuration Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _unlockingDuration, uint256 _lockedValue ) internal { for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod != 0 && (_info.currentCommittedPeriod == 0 || subStake.lastPeriod < _info.currentCommittedPeriod) && (_info.nextCommittedPeriod == 0 || subStake.lastPeriod < _info.nextCommittedPeriod)) { subStake.firstPeriod = _firstPeriod; subStake.lastPeriod = _lastPeriod; subStake.unlockingDuration = _unlockingDuration; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _additionalDuration Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); uint256 oldValue = subStake.lockedValue; subStake.lockedValue = uint128(oldValue.sub(_newValue)); require(subStake.lockedValue >= minAllowableLockedTokens); uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _additionalDuration Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration); // if the sub stake ends in the next committed period then reset the `lastPeriod` field if (lastPeriod == startPeriod) { subStake.lastPeriod = 0; } // The extended sub stake must not be less than the minimum value require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration); } /** * @notice Merge two sub-stakes into one if their last periods are equal * @dev It's possible that both sub-stakes will be active after this transaction. * But only one of them will be active until next call `commitToNextPeriod` (in the next period) * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker { require(_index1 != _index2); // must be different sub-stakes StakerInfo storage info = stakerInfo[msg.sender]; SubStakeInfo storage subStake1 = info.subStakes[_index1]; SubStakeInfo storage subStake2 = info.subStakes[_index2]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod); (, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod); // both sub-stakes must have equal last period to be mergeable require(lastPeriod1 == lastPeriod2); emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1); if (subStake1.firstPeriod == subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = 1; subStake2.unlockingDuration = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.unlockingDuration = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.unlockingDuration = 0; } } /** * @notice Remove unused sub-stake to decrease gas cost for several methods */ function removeUnusedSubStake(uint16 _index) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; uint256 lastIndex = info.subStakes.length - 1; SubStakeInfo storage subStake = info.subStakes[_index]; require(subStake.lastPeriod != 0 && (info.currentCommittedPeriod == 0 || subStake.lastPeriod < info.currentCommittedPeriod) && (info.nextCommittedPeriod == 0 || subStake.lastPeriod < info.nextCommittedPeriod)); if (_index != lastIndex) { SubStakeInfo storage lastSubStake = info.subStakes[lastIndex]; subStake.firstPeriod = lastSubStake.firstPeriod; subStake.lastPeriod = lastSubStake.lastPeriod; subStake.unlockingDuration = lastSubStake.unlockingDuration; subStake.lockedValue = lastSubStake.lockedValue; } info.subStakes.pop(); } /** * @notice Withdraw available amount of tokens to staker * @param _value Amount of tokens to withdraw */ function withdraw(uint256 _value) external onlyStaker { uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[msg.sender]; // the max locked tokens in most cases will be in the current period // but when the staker locks more then we should use the next period uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod), getLockedTokens(info, currentPeriod, currentPeriod)); require(_value <= info.value.sub(lockedTokens)); info.value -= _value; addSnapshot(info, - int256(_value)); token.safeTransfer(msg.sender, _value); emit Withdrawn(msg.sender, _value); // unbond worker if staker withdraws last portion of NU if (info.value == 0 && info.nextCommittedPeriod == 0 && info.worker != address(0)) { stakerFromWorker[info.worker] = address(0); info.worker = address(0); emit WorkerBonded(msg.sender, address(0), currentPeriod); } } /** * @notice Make a commitment to the next period and mint for the previous period */ function commitToNextPeriod() external isInitialized { address staker = stakerFromWorker[msg.sender]; StakerInfo storage info = stakerInfo[staker]; // Staker must have a stake to make a commitment require(info.value > 0); // Only worker with real address can make a commitment require(msg.sender == tx.origin); migrate(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed require(info.nextCommittedPeriod != nextPeriod); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); (uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker); uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); require(lockedTokens > 0); _lockedPerPeriod[nextPeriod] += lockedTokens; info.currentCommittedPeriod = info.nextCommittedPeriod; info.nextCommittedPeriod = nextPeriod; decreaseSubStakesDuration(info, nextPeriod); // staker was inactive for several periods if (lastCommittedPeriod < currentPeriod) { info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod)); } policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @notice Migrate from the old period length to the new one. Can be done only once * @param _staker Staker */ function migrate(address _staker) public { StakerInfo storage info = stakerInfo[_staker]; // check that provided address is/was a staker require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0); if (info.flags.bitSet(MIGRATED_INDEX)) { return; } // reset state info.currentCommittedPeriod = 0; info.nextCommittedPeriod = 0; // maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit info.lastCommittedPeriod = 1; info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod); delete info.pastDowntime; // recalculate all sub-stakes uint16 currentPeriod = getCurrentPeriod(); for (uint256 i = 0; i < info.subStakes.length; i++) { SubStakeInfo storage subStake = info.subStakes[i]; subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod); // sub-stake has fixed last period if (subStake.lastPeriod != 0) { subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod); if (subStake.lastPeriod == 0) { subStake.lastPeriod = 1; } subStake.unlockingDuration = 0; // sub-stake has no fixed ending but possible that with new period length will have } else { uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod); uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration); subStake.unlockingDuration = lastPeriod - currentPeriod; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = lastPeriod; } } } policyManager.migrate(_staker); info.flags = info.flags.toggleBit(MIGRATED_INDEX); emit Migrated(_staker, currentPeriod); } /** * @notice Decrease sub-stakes duration if `windDown` is enabled */ function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal { if (!_info.flags.bitSet(WIND_DOWN_INDEX)) { return; } for (uint256 index = 0; index < _info.subStakes.length; index++) { SubStakeInfo storage subStake = _info.subStakes[index]; if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration--; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = _nextPeriod; } } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment */ function mint() external onlyStaker { // save last committed period to the storage if both periods will be empty after minting // because we won't be able to calculate last committed period // see getLastCommittedPeriod(address) StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } (uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender); if (processedPeriod1 != 0 || processedPeriod2 != 0) { policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0); } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker * @return processedPeriod1 Processed period: currentCommittedPeriod or zero * @return processedPeriod2 Processed period: nextCommittedPeriod or zero */ function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) { uint16 currentPeriod = getCurrentPeriod(); uint16 previousPeriod = currentPeriod - 1; StakerInfo storage info = stakerInfo[_staker]; if (info.nextCommittedPeriod == 0 || info.currentCommittedPeriod == 0 && info.nextCommittedPeriod > previousPeriod || info.currentCommittedPeriod > previousPeriod) { return (0, 0); } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod1 = info.currentCommittedPeriod; info.currentCommittedPeriod = 0; if (reStake) { _lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod2 = info.nextCommittedPeriod; info.nextCommittedPeriod = 0; } info.value += reward; if (info.flags.bitSet(MEASURE_WORK_INDEX)) { info.completedWork += reward; } addSnapshot(info, int256(reward)); emit Minted(_staker, previousPeriod, reward); } /** * @notice Calculate reward for one period * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( StakerInfo storage _info, uint16 _mintingPeriod, uint16 _currentPeriod, uint16 _startPeriod, bool _reStake ) internal returns (uint256 reward) { reward = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) { uint256 subStakeReward = mint( _currentPeriod, subStake.lockedValue, _lockedPerPeriod[_mintingPeriod], lastPeriod.sub16(_mintingPeriod)); reward += subStakeReward; if (_reStake) { subStake.lockedValue += uint128(subStakeReward); } } } return reward; } //-------------------------Slashing------------------------- /** * @notice Slash the staker's stake and reward the investigator * @param _staker Staker's address * @param _penalty Penalty * @param _investigator Investigator * @param _reward Reward for the investigator */ function slashStaker( address _staker, uint256 _penalty, address _investigator, uint256 _reward ) public isInitialized { require(msg.sender == address(adjudicator)); require(_penalty > 0); StakerInfo storage info = stakerInfo[_staker]; require(info.flags.bitSet(MIGRATED_INDEX)); if (info.value <= _penalty) { _penalty = info.value; } info.value -= _penalty; if (_reward > _penalty) { _reward = _penalty; } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; uint16 startPeriod = getStartPeriod(info, currentPeriod); (uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) = getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod); // Decrease the stake if amount of locked tokens in the current period more than staker has uint256 lockedTokens = currentLock + currentAndNextLock; if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex); } // Decrease the stake if amount of locked tokens in the next period more than staker has if (nextLock > 0) { lockedTokens = nextLock + currentAndNextLock - (currentAndNextLock > info.value ? currentAndNextLock - info.value : 0); if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES); } } emit Slashed(_staker, _penalty, _investigator, _reward); if (_penalty > _reward) { unMint(_penalty - _reward); } // TODO change to withdrawal pattern (#1499) if (_reward > 0) { token.safeTransfer(_investigator, _reward); } addSnapshot(info, - int256(_penalty)); } /** * @notice Get the value of locked tokens for a staker in the current and the next period * and find the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _startPeriod Pre-calculated start period * @return currentLock Amount of tokens that locked in the current period and unlocked in the next period * @return nextLock Amount of tokens that locked in the next period and not locked in the current period * @return currentAndNextLock Amount of tokens that locked in the current period and in the next period * @return shortestSubStakeIndex Index of the shortest sub stake */ function getLockedTokensAndShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, uint16 _startPeriod ) internal view returns ( uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex ) { uint16 minDuration = MAX_UINT16; uint16 minLastPeriod = MAX_UINT16; shortestSubStakeIndex = MAX_SUB_STAKES; currentLock = 0; nextLock = 0; currentAndNextLock = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _nextPeriod) { currentAndNextLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod) { currentLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _nextPeriod && lastPeriod >= _nextPeriod) { nextLock += subStake.lockedValue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minLastPeriod || lastPeriod == minLastPeriod && duration < minDuration)) { shortestSubStakeIndex = i; minDuration = duration; minLastPeriod = lastPeriod; } } } /** * @notice Decrease short sub stakes * @param _info Staker structure * @param _penalty Penalty rate * @param _decreasePeriod The period when the decrease begins * @param _startPeriod Pre-calculated start period * @param _shortestSubStakeIndex Index of the shortest period */ function decreaseSubStakes( StakerInfo storage _info, uint256 _penalty, uint16 _decreasePeriod, uint16 _startPeriod, uint256 _shortestSubStakeIndex ) internal { SubStakeInfo storage shortestSubStake = _info.subStakes[0]; uint16 minSubStakeLastPeriod = MAX_UINT16; uint16 minSubStakeDuration = MAX_UINT16; while(_penalty > 0) { if (_shortestSubStakeIndex < MAX_SUB_STAKES) { shortestSubStake = _info.subStakes[_shortestSubStakeIndex]; minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod); minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod; _shortestSubStakeIndex = MAX_SUB_STAKES; } else { (shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) = getShortestSubStake(_info, _decreasePeriod, _startPeriod); } if (minSubStakeDuration == MAX_UINT16) { break; } uint256 appliedPenalty = _penalty; if (_penalty < shortestSubStake.lockedValue) { shortestSubStake.lockedValue -= uint128(_penalty); saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod); _penalty = 0; } else { shortestSubStake.lastPeriod = _decreasePeriod - 1; _penalty -= shortestSubStake.lockedValue; appliedPenalty = shortestSubStake.lockedValue; } if (_info.currentCommittedPeriod >= _decreasePeriod && _info.currentCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty; } if (_info.nextCommittedPeriod >= _decreasePeriod && _info.nextCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty; } } } /** * @notice Get the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period * @return shortestSubStake The shortest sub stake * @return minSubStakeDuration Duration of the shortest sub stake * @return minSubStakeLastPeriod Last period of the shortest sub stake */ function getShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _startPeriod ) internal view returns ( SubStakeInfo storage shortestSubStake, uint16 minSubStakeDuration, uint16 minSubStakeLastPeriod ) { shortestSubStake = shortestSubStake; minSubStakeDuration = MAX_UINT16; minSubStakeLastPeriod = MAX_UINT16; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minSubStakeLastPeriod || lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration)) { shortestSubStake = subStake; minSubStakeDuration = duration; minSubStakeLastPeriod = lastPeriod; } } } /** * @notice Save the old sub stake values to prevent decreasing reward for the previous period * @dev Saving happens only if the previous period is committed * @param _info Staker structure * @param _firstPeriod First period of the old sub stake * @param _lockedValue Locked value of the old sub stake * @param _currentPeriod Current period, when the old sub stake is already unlocked */ function saveOldSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint256 _lockedValue, uint16 _currentPeriod ) internal { // Check that the old sub stake should be saved bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod < _currentPeriod; bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod < _currentPeriod; bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod; bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod; if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) { return; } // Try to find already existent proper old sub stake uint16 previousPeriod = _currentPeriod - 1; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod == previousPeriod && ((crosscurrentCommittedPeriod == (oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) && (crossnextCommittedPeriod == (oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod)))) { subStake.lockedValue += uint128(_lockedValue); return; } } saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue); } //-------------Additional getters for stakers info------------- /** * @notice Return the length of the array of stakers */ function getStakersLength() external view returns (uint256) { return stakers.length; } /** * @notice Return the length of the array of sub stakes */ function getSubStakesLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].subStakes.length; } /** * @notice Return the information about sub stake */ function getSubStakeInfo(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (SubStakeInfo) // TODO "virtual" only for tests, probably will be removed after #1512 external view virtual returns ( uint16 firstPeriod, uint16 lastPeriod, uint16 unlockingDuration, uint128 lockedValue ) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; unlockingDuration = info.unlockingDuration; lockedValue = info.lockedValue; } /** * @notice Return the length of the array of past downtime */ function getPastDowntimeLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].pastDowntime.length; } /** * @notice Return the information about past downtime */ function getPastDowntime(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (Downtime) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; } //------------------ ERC900 connectors ---------------------- function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){ return stakerInfo[_owner].history.getValueAt(_blockNumber); } function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){ return balanceHistory.getValueAt(_blockNumber); } function supportsHistory() external pure override returns (bool){ return true; } //------------------------Upgradeable------------------------ /** * @dev Get StakerInfo structure by delegatecall */ function delegateGetStakerInfo(address _target, bytes32 _staker) internal returns (StakerInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0); assembly { result := memoryAddress } } /** * @dev Get SubStakeInfo structure by delegatecall */ function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index) internal returns (SubStakeInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get Downtime structure by delegatecall */ function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index) internal returns (Downtime memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getPastDowntime.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(delegateGet(_testTarget, this.lockedPerPeriod.selector, bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD)); require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) == stakerFromWorker[address(0)]); require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length); if (stakers.length == 0) { return; } address stakerAddress = stakers[0]; require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress); StakerInfo storage info = stakerInfo[stakerAddress]; bytes32 staker = bytes32(uint256(stakerAddress)); StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker); require(infoToCheck.value == info.value && infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod && infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod && infoToCheck.flags == info.flags && infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod && infoToCheck.completedWork == info.completedWork && infoToCheck.worker == info.worker && infoToCheck.workerStartPeriod == info.workerStartPeriod); require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) == info.pastDowntime.length); for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) { Downtime storage downtime = info.pastDowntime[i]; Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i); require(downtimeToCheck.startPeriod == downtime.startPeriod && downtimeToCheck.endPeriod == downtime.endPeriod); } require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length); for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) { SubStakeInfo storage subStakeInfo = info.subStakes[i]; SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i); require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod && subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod && subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration && subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue); } // it's not perfect because checks not only slot value but also decoding // at least without additional functions require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) == totalStakedForAt(stakerAddress, block.number)); require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) == totalStakedAt(block.number)); if (info.worker != address(0)) { require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) == stakerFromWorker[info.worker]); } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // Create fake period _lockedPerPeriod[RESERVED_PERIOD] = 111; // Create fake worker stakerFromWorker[address(0)] = address(this); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; // Minimum interface to interact with Aragon's Aggregator interface IERC900History { function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); function totalStakedAt(uint256 blockNumber) external view returns (uint256); function supportsHistory() external pure returns (bool); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./NuCypherToken.sol"; import "../zeppelin/math/Math.sol"; import "./proxy/Upgradeable.sol"; import "./lib/AdditionalMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @title Issuer * @notice Contract for calculation of issued tokens * @dev |v3.4.1| */ abstract contract Issuer is Upgradeable { using SafeERC20 for NuCypherToken; using AdditionalMath for uint32; event Donated(address indexed sender, uint256 value); /// Issuer is initialized with a reserved reward event Initialized(uint256 reservedReward); uint128 constant MAX_UINT128 = uint128(0) - 1; NuCypherToken public immutable token; uint128 public immutable totalSupply; // d * k2 uint256 public immutable mintingCoefficient; // k1 uint256 public immutable lockDurationCoefficient1; // k2 uint256 public immutable lockDurationCoefficient2; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; // kmax uint16 public immutable maximumRewardedPeriods; uint256 public immutable firstPhaseMaxIssuance; uint256 public immutable firstPhaseTotalSupply; /** * Current supply is used in the minting formula and is stored to prevent different calculation * for stakers which get reward in the same period. There are two values - * supply for previous period (used in formula) and supply for current period which accumulates value * before end of period. */ uint128 public previousPeriodSupply; uint128 public currentPeriodSupply; uint16 public currentMintingPeriod; /** * @notice Constructor sets address of token contract and coefficients for minting * @dev Minting formula for one sub-stake in one period for the first phase firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 * @dev Minting formula for one sub-stake in one period for the second phase (totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _lockDurationCoefficient1 != 0 && _lockDurationCoefficient2 != 0 && _maximumRewardedPeriods != 0); require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported"); uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1; uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2; require(maxLockDurationCoefficient > _maximumRewardedPeriods && localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 && // worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient && // worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`, // when currentSupply == 0, lockedValue == totalSupply localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply == maxLockDurationCoefficient, "Specified parameters cause overflow"); require(maxLockDurationCoefficient <= _lockDurationCoefficient2, "Resulting locking duration coefficient must be less than 1"); require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase"); require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high"); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); lockDurationCoefficient1 = _lockDurationCoefficient1; lockDurationCoefficient2 = _lockDurationCoefficient2; maximumRewardedPeriods = _maximumRewardedPeriods; firstPhaseTotalSupply = _firstPhaseTotalSupply; firstPhaseMaxIssuance = _firstPhaseMaxIssuance; totalSupply = uint128(localTotalSupply); mintingCoefficient = localMintingCoefficient; } /** * @dev Checks contract initialization */ modifier isInitialized() { require(currentMintingPeriod != 0); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Initialize reserved tokens for reward */ function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner { require(currentMintingPeriod == 0); // Reserved reward must be sufficient for at least one period of the first phase require(firstPhaseMaxIssuance <= _reservedReward); currentMintingPeriod = getCurrentPeriod(); currentPeriodSupply = totalSupply - uint128(_reservedReward); previousPeriodSupply = currentPeriodSupply; token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward); emit Initialized(_reservedReward); } /** * @notice Function to mint tokens for one period. * @param _currentPeriod Current period number. * @param _lockedValue The amount of tokens that were locked by user in specified period. * @param _totalLockedValue The amount of tokens that were locked by all users in specified period. * @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period. * @return amount Amount of minted tokens. */ function mint( uint16 _currentPeriod, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) internal returns (uint256 amount) { if (currentPeriodSupply == totalSupply) { return 0; } if (_currentPeriod > currentMintingPeriod) { previousPeriodSupply = currentPeriodSupply; currentMintingPeriod = _currentPeriod; } uint256 currentReward; uint256 coefficient; // first phase // firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2) if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) { currentReward = firstPhaseMaxIssuance; coefficient = lockDurationCoefficient2; // second phase // (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2) } else { currentReward = totalSupply - previousPeriodSupply; coefficient = mintingCoefficient; } uint256 allLockedPeriods = AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1; amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) / (_totalLockedValue * coefficient); // rounding the last reward uint256 maxReward = getReservedReward(); if (amount == 0) { amount = 1; } else if (amount > maxReward) { amount = maxReward; } currentPeriodSupply += uint128(amount); } /** * @notice Return tokens for future minting * @param _amount Amount of tokens */ function unMint(uint256 _amount) internal { previousPeriodSupply -= uint128(_amount); currentPeriodSupply -= uint128(_amount); } /** * @notice Donate sender's tokens. Amount of tokens will be returned for future minting * @param _value Amount to donate */ function donate(uint256 _value) external isInitialized { token.safeTransferFrom(msg.sender, address(this), _value); unMint(_value); emit Donated(msg.sender, _value); } /** * @notice Returns the number of tokens that can be minted */ function getReservedReward() public view returns (uint256) { return totalSupply - currentPeriodSupply; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod); require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply); require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // recalculate currentMintingPeriod if needed if (currentMintingPeriod > getCurrentPeriod()) { currentMintingPeriod = recalculatePeriod(currentMintingPeriod); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/ERC20.sol"; import "../zeppelin/token/ERC20/ERC20Detailed.sol"; /** * @title NuCypherToken * @notice ERC20 token * @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred. */ contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) { /** * @notice Set amount of tokens * @param _totalSupplyOfTokens Total number of tokens */ constructor (uint256 _totalSupplyOfTokens) { _mint(msg.sender, _totalSupplyOfTokens); } /** * @notice Approves and then calls the receiving contract * * @dev call the receiveApproval function on the contract you want to be notified. * receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) */ function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { approve(_spender, _value); TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * @dev Interface to use the receiveApproval method */ interface TokenRecipient { /** * @notice Receives a notification of approval of the transfer * @param _from Sender of approval * @param _value The amount of tokens to be spent * @param _tokenContract Address of the token contract * @param _extraData Extra data */ function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.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 ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override 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 override returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override 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 override returns (bool) { // 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); _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 override 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_[_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_[_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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; /** * @notice Base contract for upgradeable contract * @dev Inherited contract should implement verifyState(address) method by checking storage variables * (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address) * if it is using constructor parameters by coping this parameters to the dispatcher storage */ abstract contract Upgradeable is Ownable { event StateVerified(address indexed testTarget, address sender); event UpgradeFinished(address indexed target, address sender); /** * @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher * Stored data actually lives in the Dispatcher * However the storage layout is specified here in the implementing contracts */ address public target; /** * @dev Previous contract address (if available). Used for rollback */ address public previousTarget; /** * @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value */ uint8 public isUpgrade; /** * @dev Guarantees that next slot will be separated from the previous */ uint256 stubSlot; /** * @dev Constants for `isUpgrade` field */ uint8 constant UPGRADE_FALSE = 1; uint8 constant UPGRADE_TRUE = 2; /** * @dev Checks that function executed while upgrading * Recommended to add to `verifyState` and `finishUpgrade` methods */ modifier onlyWhileUpgrading() { require(isUpgrade == UPGRADE_TRUE); _; } /** * @dev Method for verifying storage state. * Should check that new target contract returns right storage value */ function verifyState(address _testTarget) public virtual onlyWhileUpgrading { emit StateVerified(_testTarget, msg.sender); } /** * @dev Copy values from the new target to the current storage * @param _target New target contract address */ function finishUpgrade(address _target) public virtual onlyWhileUpgrading { emit UpgradeFinished(_target, msg.sender); } /** * @dev Base method to get data * @param _target Target to call * @param _selector Method selector * @param _numberOfArguments Number of used arguments * @param _argument1 First method argument * @param _argument2 Second method argument * @return memoryAddress Address in memory where the data is located */ function delegateGetData( address _target, bytes4 _selector, uint8 _numberOfArguments, bytes32 _argument1, bytes32 _argument2 ) internal returns (bytes32 memoryAddress) { assembly { memoryAddress := mload(0x40) mstore(memoryAddress, _selector) if gt(_numberOfArguments, 0) { mstore(add(memoryAddress, 0x04), _argument1) } if gt(_numberOfArguments, 1) { mstore(add(memoryAddress, 0x24), _argument2) } switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0) case 0 { revert(memoryAddress, 0) } default { returndatacopy(memoryAddress, 0x0, returndatasize()) } } } /** * @dev Call "getter" without parameters. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with one parameter. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector, bytes32 _argument) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with two parameters. * Result should not exceed 32 bytes */ function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public virtual 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; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/math/SafeMath.sol"; /** * @notice Additional math operations */ library AdditionalMath { using SafeMath for uint256; function max16(uint16 a, uint16 b) internal pure returns (uint16) { return a >= b ? a : b; } function min16(uint16 a, uint16 b) internal pure returns (uint16) { return a < b ? a : b; } /** * @notice Division and ceil */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return (a.add(b) - 1) / b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.add(uint256(b)); } else { return a.sub(uint256(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.sub(uint256(b)); } else { return a.add(uint256(-b)); } } /** * @dev Multiplies two numbers, throws on overflow. */ function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add16(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return add16(a, uint16(b)); } else { return sub16(a, uint16(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return sub16(a, uint16(b)); } else { return add16(a, uint16(-b)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.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 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(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' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol */ library Bits { uint256 internal constant ONE = uint256(1); /** * @notice Sets the bit at the given 'index' in 'self' to: * '1' - if the bit is '0' * '0' - if the bit is '1' * @return The modified value */ function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ ONE << index; } /** * @notice Get the value of the bit at the given 'index' in 'self'. */ function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } /** * @notice Check if the bit at the given 'index' in 'self' is set. * @return 'true' - if the value of the bit is '1', * 'false' - if the value of the bit is '0' */ function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Snapshot * @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value) * 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers * @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately. * Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol) * On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing */ library Snapshot { function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) { return uint128(uint256(_time) << 96 | uint256(_value)); } function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){ time = uint32(bytes4(bytes16(_snapshot))); value = uint96(_snapshot); } function addSnapshot(uint128[] storage _self, uint256 _value) internal { addSnapshot(_self, block.number, _value); } function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal { uint256 length = _self.length; if (length != 0) { (uint32 currentTime, ) = decodeSnapshot(_self[length - 1]); if (uint32(_time) == currentTime) { _self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value)); return; } else if (uint32(_time) < currentTime){ revert(); } } _self.push(encodeSnapshot(uint32(_time), uint96(_value))); } function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) { uint256 length = _self.length; if (length > 0) { return decodeSnapshot(_self[length - 1]); } return (0, 0); } function lastValue(uint128[] storage _self) internal view returns (uint96) { (, uint96 value) = lastSnapshot(_self); return value; } function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) { uint32 _time = uint32(_time256); uint256 length = _self.length; // Short circuit if there's no checkpoints yet // Note that this also lets us avoid using SafeMath later on, as we've established that // there must be at least one checkpoint if (length == 0) { return 0; } // Check last checkpoint uint256 lastIndex = length - 1; (uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]); if (_time >= snapshotTime) { return snapshotValue; } // Check first checkpoint (if not already checked with the above check on last) (snapshotTime, snapshotValue) = decodeSnapshot(_self[0]); if (length == 1 || _time < snapshotTime) { return 0; } // Do binary search // As we've already checked both ends, we don't need to check the last checkpoint again uint256 low = 0; uint256 high = lastIndex - 1; uint32 midTime; uint96 midValue; while (high > low) { uint256 mid = (high + low + 1) / 2; // average, ceil round (midTime, midValue) = decodeSnapshot(_self[mid]); if (_time > midTime) { low = mid; } else if (_time < midTime) { // Note that we don't need SafeMath here because mid must always be greater than 0 // from the while condition high = mid - 1; } else { // _time == midTime return midValue; } } (, snapshotValue) = decodeSnapshot(_self[low]); return snapshotValue; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface IForwarder { function isForwarder() external pure returns (bool); function canForward(address sender, bytes calldata evmCallScript) external view returns (bool); function forward(bytes calldata evmCallScript) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface TokenManager { function mint(address _receiver, uint256 _amount) external; function issue(uint256 _amount) external; function assign(address _receiver, uint256 _amount) external; function burn(address _holder, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; import "./IForwarder.sol"; // Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol interface Voting is IForwarder{ enum VoterState { Absent, Yea, Nay } // Public getters function token() external returns (address); function supportRequiredPct() external returns (uint64); function minAcceptQuorumPct() external returns (uint64); function voteTime() external returns (uint64); function votesLength() external returns (uint256); // Setters function changeSupportRequiredPct(uint64 _supportRequiredPct) external; function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external; // Creating new votes function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId); function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId); // Voting function canVote(uint256 _voteId, address _voter) external view returns (bool); function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external; // Executing a passed vote function canExecute(uint256 _voteId) external view returns (bool); function executeVote(uint256 _voteId) external; // Additional info function getVote(uint256 _voteId) external view returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes memory script ); function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; /** * @notice Multi-signature contract with off-chain signing */ contract MultiSig { using SafeMath for uint256; event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value); event OwnerAdded(address indexed owner); event OwnerRemoved(address indexed owner); event RequirementChanged(uint16 required); uint256 constant public MAX_OWNER_COUNT = 50; uint256 public nonce; uint8 public required; mapping (address => bool) public isOwner; address[] public owners; /** * @notice Only this contract can call method */ modifier onlyThisContract() { require(msg.sender == address(this)); _; } receive() external payable {} /** * @param _required Number of required signings * @param _owners List of initial owners. */ constructor (uint8 _required, address[] memory _owners) { require(_owners.length <= MAX_OWNER_COUNT && _required <= _owners.length && _required > 0); for (uint256 i = 0; i < _owners.length; i++) { address owner = _owners[i]; require(!isOwner[owner] && owner != address(0)); isOwner[owner] = true; } owners = _owners; required = _required; } /** * @notice Get unsigned hash for transaction parameters * @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 * @param _sender Trustee who will execute the transaction * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data * @param _nonce Nonce */ function getUnsignedTransactionHash( address _sender, address _destination, uint256 _value, bytes memory _data, uint256 _nonce ) public view returns (bytes32) { return keccak256( abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce)); } /** * @dev Note that address recovered from signatures must be strictly increasing * @param _sigV Array of signatures values V * @param _sigR Array of signatures values R * @param _sigS Array of signatures values S * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data */ function execute( uint8[] calldata _sigV, bytes32[] calldata _sigR, bytes32[] calldata _sigS, address _destination, uint256 _value, bytes calldata _data ) external { require(_sigR.length >= required && _sigR.length == _sigS.length && _sigR.length == _sigV.length); bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce); address lastAdd = address(0); for (uint256 i = 0; i < _sigR.length; i++) { address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]); require(recovered > lastAdd && isOwner[recovered]); lastAdd = recovered; } emit Executed(msg.sender, nonce, _destination, _value); nonce = nonce.add(1); (bool callSuccess,) = _destination.call{value: _value}(_data); require(callSuccess); } /** * @notice Allows to add a new owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of new owner */ function addOwner(address _owner) external onlyThisContract { require(owners.length < MAX_OWNER_COUNT && _owner != address(0) && !isOwner[_owner]); isOwner[_owner] = true; owners.push(_owner); emit OwnerAdded(_owner); } /** * @notice Allows to remove an owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of owner */ function removeOwner(address _owner) external onlyThisContract { require(owners.length > required && isOwner[_owner]); isOwner[_owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } } owners.pop(); emit OwnerRemoved(_owner); } /** * @notice Returns the number of owners of this MultiSig */ function getNumberOfOwners() external view returns (uint256) { return owners.length; } /** * @notice Allows to change the number of required signatures * @dev Transaction has to be sent by `execute` method * @param _required Number of required signatures */ function changeRequirement(uint8 _required) external onlyThisContract { require(_required <= owners.length && _required > 0); required = _required; emit RequirementChanged(_required); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; import "../zeppelin/utils/Address.sol"; import "./lib/AdditionalMath.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./NuCypherToken.sol"; import "./proxy/Upgradeable.sol"; /** * @title PolicyManager * @notice Contract holds policy data and locks accrued policy fees * @dev |v6.3.1| */ contract PolicyManager is Upgradeable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using AdditionalMath for int256; using AdditionalMath for uint16; using Address for address payable; event PolicyCreated( bytes16 indexed policyId, address indexed sponsor, address indexed owner, uint256 feeRate, uint64 startTimestamp, uint64 endTimestamp, uint256 numberOfNodes ); event ArrangementRevoked( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event RefundForArrangement( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value); event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value); event MinFeeRateSet(address indexed node, uint256 value); // TODO #1501 // Range range event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max); event Withdrawn(address indexed node, address indexed recipient, uint256 value); struct ArrangementInfo { address node; uint256 indexOfDowntimePeriods; uint16 lastRefundedPeriod; } struct Policy { bool disabled; address payable sponsor; address owner; uint128 feeRate; uint64 startTimestamp; uint64 endTimestamp; uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; ArrangementInfo[] arrangements; } struct NodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; mapping (uint16 => int256) stub; // former slot for feeDelta mapping (uint16 => int256) feeDelta; } // TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512 struct MemoryNodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; } struct Range { uint128 min; uint128 defaultValue; uint128 max; } bytes16 internal constant RESERVED_POLICY_ID = bytes16(0); address internal constant RESERVED_NODE = address(0); uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1); // controlled overflow to get max int256 int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1); StakingEscrow public immutable escrow; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; mapping (bytes16 => Policy) public policies; mapping (address => NodeInfo) public nodes; Range public feeRateRange; uint64 public resetTimestamp; /** * @notice Constructor sets address of the escrow contract * @dev Put same address in both inputs variables except when migration is happening * @param _escrowDispatcher Address of escrow dispatcher * @param _escrowImplementation Address of escrow implementation */ constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) { escrow = _escrowDispatcher; // if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod(); require(localSecondsPerPeriod > 0); secondsPerPeriod = localSecondsPerPeriod; uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod(); require(localgenesisSecondsPerPeriod > 0); genesisSecondsPerPeriod = localgenesisSecondsPerPeriod; // handle case when we deployed new StakingEscrow but not yet upgraded if (_escrowDispatcher != _escrowImplementation) { require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod || _escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod); } } /** * @dev Checks that sender is the StakingEscrow contract */ modifier onlyEscrowContract() { require(msg.sender == address(escrow)); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Register a node * @param _node Node address * @param _period Initial period */ function register(address _node, uint16 _period) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod == 0 && _period < getCurrentPeriod()); nodeInfo.previousFeePeriod = _period; } /** * @notice Migrate from the old period length to the new one * @param _node Node address */ function migrate(address _node) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; // with previous period length any previousFeePeriod will be greater than current period // this is a sign of not migrated node require(nodeInfo.previousFeePeriod >= getCurrentPeriod()); nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod); nodeInfo.feeRate = 0; } /** * @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range') */ // TODO # 1501 // function setFeeRateRange(Range calldata _range) external onlyOwner { function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner { require(_min <= _default && _default <= _max); feeRateRange = Range(_min, _default, _max); emit FeeRateRangeSet(msg.sender, _min, _default, _max); } /** * @notice Set the minimum acceptable fee rate (set by staker for their associated worker) * @dev Input value must fall within `feeRateRange` (global fee range) */ function setMinFeeRate(uint256 _minFeeRate) external { require(_minFeeRate >= feeRateRange.min && _minFeeRate <= feeRateRange.max, "The staker's min fee rate must fall within the global fee range"); NodeInfo storage nodeInfo = nodes[msg.sender]; if (nodeInfo.minFeeRate == _minFeeRate) { return; } nodeInfo.minFeeRate = _minFeeRate; emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) { // if minFeeRate has not been set or chosen value falls outside the global fee range // a default value is returned instead if (_nodeInfo.minFeeRate == 0 || _nodeInfo.minFeeRate < feeRateRange.min || _nodeInfo.minFeeRate > feeRateRange.max) { return feeRateRange.defaultValue; } else { return _nodeInfo.minFeeRate; } } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(address _node) public view returns (uint256) { NodeInfo storage nodeInfo = nodes[_node]; return getMinFeeRate(nodeInfo); } /** * @notice Create policy * @dev Generate policy id before creation * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _nodes Nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value); Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate)); policy.arrangements.push(ArrangementInfo(node, 0, 0)); } } /** * @notice Create multiple policies with the same owner, nodes and length * @dev Generate policy ids before creation * @param _policyIds Policy ids * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of all policies in seconds * @param _nodes Nodes that will handle all policies */ function createPolicies( bytes16[] calldata _policyIds, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 && _policyIds.length > 1 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value); for (uint256 i = 0; i < _policyIds.length; i++) { Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 j = 0; j < _nodes.length; j++) { policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0)); } } int256 fee = int256(_policyIds.length * feeRate); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee); } } /** * @notice Create policy * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _feeRate Fee rate for policy * @param _nodesLength Number of nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, uint128 _feeRate, uint256 _nodesLength ) internal returns (Policy storage policy) { policy = policies[_policyId]; require( _policyId != RESERVED_POLICY_ID && policy.feeRate == 0 && !policy.disabled ); policy.sponsor = msg.sender; policy.startTimestamp = uint64(block.timestamp); policy.endTimestamp = _endTimestamp; policy.feeRate = _feeRate; if (_policyOwner != msg.sender && _policyOwner != address(0)) { policy.owner = _policyOwner; } emit PolicyCreated( _policyId, msg.sender, _policyOwner == address(0) ? msg.sender : _policyOwner, _feeRate, policy.startTimestamp, policy.endTimestamp, _nodesLength ); } /** * @notice Increase fee rate for specified node * @param _currentPeriod Current period * @param _endPeriod End period of policy * @param _node Node that will handle policy * @param _feeRate Fee rate for one policy * @param _overallFeeRate Fee rate for all policies */ function addFeeToNode( uint16 _currentPeriod, uint16 _endPeriod, address _node, uint128 _feeRate, int256 _overallFeeRate ) internal { require(_node != RESERVED_NODE); NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod != 0 && nodeInfo.previousFeePeriod < _currentPeriod && _feeRate >= getMinFeeRate(nodeInfo)); // Check default value for feeDelta if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate; } else { // Overflow protection removed, because ETH total supply less than uint255/int256 nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate; } if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate; } else { nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate; } // Reset to default value if needed if (nodeInfo.feeDelta[_currentPeriod] == 0) { nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[_endPeriod] == 0) { nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA; } } /** * @notice Get policy owner */ function getPolicyOwner(bytes16 _policyId) public view returns (address) { Policy storage policy = policies[_policyId]; return policy.owner == address(0) ? policy.sponsor : policy.owner; } /** * @notice Call from StakingEscrow to update node info once per period. * Set default `feeDelta` value for specified period and update node fee * @param _node Node address * @param _processedPeriod1 Processed period * @param _processedPeriod2 Processed period * @param _periodToSetDefault Period to set */ function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external onlyEscrowContract { NodeInfo storage node = nodes[_node]; // protection from calling not migrated node, see migrate() require(node.previousFeePeriod <= getCurrentPeriod()); if (_processedPeriod1 != 0) { updateFee(node, _processedPeriod1); } if (_processedPeriod2 != 0) { updateFee(node, _processedPeriod2); } // This code increases gas cost for node in trade of decreasing cost for policy sponsor if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) { node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA; } } /** * @notice Update node fee * @param _info Node info structure * @param _period Processed period */ function updateFee(NodeInfo storage _info, uint16 _period) internal { if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) { return; } for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) { int256 delta = _info.feeDelta[i]; if (delta == DEFAULT_FEE_DELTA) { // gas refund _info.feeDelta[i] = 0; continue; } _info.feeRate = _info.feeRate.addSigned(delta); // gas refund _info.feeDelta[i] = 0; } _info.previousFeePeriod = _period; _info.fee += uint128(_info.feeRate); } /** * @notice Withdraw fee by node */ function withdraw() external returns (uint256) { return withdraw(msg.sender); } /** * @notice Withdraw fee by node * @param _recipient Recipient of the fee */ function withdraw(address payable _recipient) public returns (uint256) { NodeInfo storage node = nodes[msg.sender]; uint256 fee = node.fee; require(fee != 0); node.fee = 0; _recipient.sendValue(fee); emit Withdrawn(msg.sender, _recipient, fee); return fee; } /** * @notice Calculate amount of refund * @param _policy Policy * @param _arrangement Arrangement */ function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement) internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { uint16 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod); uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod)); uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod); uint16 downtimePeriods = 0; uint256 length = escrow.getPastDowntimeLength(_arrangement.node); uint256 initialIndexOfDowntimePeriods; if (_arrangement.lastRefundedPeriod == 0) { initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod); } else { initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods; } for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods; indexOfDowntimePeriods < length; indexOfDowntimePeriods++) { (uint16 startPeriod, uint16 endPeriod) = escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods); if (startPeriod > maxPeriod) { break; } else if (endPeriod < minPeriod) { continue; } downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod) .sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1; if (maxPeriod <= endPeriod) { break; } } uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node); if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) { // Overflow protection removed: // lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1 downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod); } refundValue = _policy.feeRate * downtimePeriods; lastRefundedPeriod = maxPeriod + 1; } /** * @notice Revoke/refund arrangement/policy by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded or RESERVED_NODE if full policy should be used ( @param _forceRevoke Force revoke arrangement/policy */ function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke) internal returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require(!policy.disabled && policy.startTimestamp >= resetTimestamp); uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1; uint256 numberOfActive = policy.arrangements.length; uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; address node = arrangement.node; if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) { numberOfActive--; continue; } uint256 nodeRefundValue; (nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) = calculateRefundValue(policy, arrangement); if (_forceRevoke) { NodeInfo storage nodeInfo = nodes[node]; // Check default value for feeDelta uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod; if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate); } else { nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate); } if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate); } else { nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate); } // Reset to default value if needed if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) { nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[endPeriod] == 0) { nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA; } nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate; } if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) { arrangement.node = RESERVED_NODE; arrangement.indexOfDowntimePeriods = 0; arrangement.lastRefundedPeriod = 0; numberOfActive--; emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue); } else { emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue); } refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } address payable policySponsor = policy.sponsor; if (_node == RESERVED_NODE) { if (numberOfActive == 0) { policy.disabled = true; // gas refund policy.sponsor = address(0); policy.owner = address(0); policy.feeRate = 0; policy.startTimestamp = 0; policy.endTimestamp = 0; emit PolicyRevoked(_policyId, msg.sender, refundValue); } else { emit RefundForPolicy(_policyId, msg.sender, refundValue); } } else { // arrangement not found require(i < policy.arrangements.length); } if (refundValue > 0) { policySponsor.sendValue(refundValue); } } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node or RESERVED_NODE if all nodes should be used */ function calculateRefundValueInternal(bytes16 _policyId, address _node) internal view returns (uint256 refundValue) { refundValue = 0; Policy storage policy = policies[_policyId]; require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled); uint256 i = 0; for (; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) { continue; } (uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement); refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } if (_node != RESERVED_NODE) { // arrangement not found require(i < policy.arrangements.length); } } /** * @notice Revoke policy by the sponsor * @param _policyId Policy id */ function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) { require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, RESERVED_NODE, true); } /** * @notice Revoke arrangement by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded */ function revokeArrangement(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, _node, true); } /** * @notice Get unsigned hash for revocation * @param _policyId Policy id * @param _node Node that will be excluded * @return Revocation hash, EIP191 version 0x45 ('E') */ function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) { return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45)); } /** * @notice Check correctness of signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner */ function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view { bytes32 hash = getRevocationHash(_policyId, _node); address recovered = SignatureVerifier.recover(hash, _signature); require(getPolicyOwner(_policyId) == recovered); } /** * @notice Revoke policy or arrangement using owner's signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner, EIP191 version 0x45 ('E') */ function revoke(bytes16 _policyId, address _node, bytes calldata _signature) external returns (uint256 refundValue) { checkOwnerSignature(_policyId, _node, _signature); return refundInternal(_policyId, _node, true); } /** * @notice Refund part of fee by the sponsor * @param _policyId Policy id */ function refund(bytes16 _policyId) external { Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); refundInternal(_policyId, RESERVED_NODE, false); } /** * @notice Refund part of one node's fee by the sponsor * @param _policyId Policy id * @param _node Node address */ function refund(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); return refundInternal(_policyId, _node, false); } /** * @notice Calculate amount of refund * @param _policyId Policy id */ function calculateRefundValue(bytes16 _policyId) external view returns (uint256 refundValue) { return calculateRefundValueInternal(_policyId, RESERVED_NODE); } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node */ function calculateRefundValue(bytes16 _policyId, address _node) external view returns (uint256 refundValue) { require(_node != RESERVED_NODE); return calculateRefundValueInternal(_policyId, _node); } /** * @notice Get number of arrangements in the policy * @param _policyId Policy id */ function getArrangementsLength(bytes16 _policyId) external view returns (uint256) { return policies[_policyId].arrangements.length; } /** * @notice Get information about staker's fee rate * @param _node Address of staker * @param _period Period to get fee delta */ function getNodeFeeDelta(address _node, uint16 _period) // TODO "virtual" only for tests, probably will be removed after #1512 public view virtual returns (int256) { // TODO remove after upgrade #2579 if (_node == RESERVED_NODE && _period == 11) { return 55; } return nodes[_node].feeDelta[_period]; } /** * @notice Return the information about arrangement */ function getArrangementInfo(bytes16 _policyId, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (ArrangementInfo) external view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { ArrangementInfo storage info = policies[_policyId].arrangements[_index]; node = info.node; indexOfDowntimePeriods = info.indexOfDowntimePeriods; lastRefundedPeriod = info.lastRefundedPeriod; } /** * @dev Get Policy structure by delegatecall */ function delegateGetPolicy(address _target, bytes16 _policyId) internal returns (Policy memory result) { bytes32 memoryAddress = delegateGetData(_target, this.policies.selector, 1, bytes32(_policyId), 0); assembly { result := memoryAddress } } /** * @dev Get ArrangementInfo structure by delegatecall */ function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index) internal returns (ArrangementInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get NodeInfo structure by delegatecall */ function delegateGetNodeInfo(address _target, address _node) internal returns (MemoryNodeInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0); assembly { result := memoryAddress } } /** * @dev Get feeRateRange structure by delegatecall */ function delegateGetFeeRateRange(address _target) internal returns (Range memory result) { bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp); Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget); require(feeRateRange.min == rangeToCheck.min && feeRateRange.defaultValue == rangeToCheck.defaultValue && feeRateRange.max == rangeToCheck.max); Policy storage policy = policies[RESERVED_POLICY_ID]; Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID); require(policyToCheck.sponsor == policy.sponsor && policyToCheck.owner == policy.owner && policyToCheck.feeRate == policy.feeRate && policyToCheck.startTimestamp == policy.startTimestamp && policyToCheck.endTimestamp == policy.endTimestamp && policyToCheck.disabled == policy.disabled); require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) == policy.arrangements.length); if (policy.arrangements.length > 0) { ArrangementInfo storage arrangement = policy.arrangements[0]; ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo( _testTarget, RESERVED_POLICY_ID, 0); require(arrangementToCheck.node == arrangement.node && arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods && arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod); } NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE); require(nodeInfoToCheck.fee == nodeInfo.fee && nodeInfoToCheck.feeRate == nodeInfo.feeRate && nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod && nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate); require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector, bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11)); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); if (resetTimestamp == 0) { resetTimestamp = uint64(block.timestamp); } // Create fake Policy and NodeInfo to use them in verifyState(address) Policy storage policy = policies[RESERVED_POLICY_ID]; policy.sponsor = msg.sender; policy.owner = address(this); policy.startTimestamp = 1; policy.endTimestamp = 2; policy.feeRate = 3; policy.disabled = true; policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22)); NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; nodeInfo.fee = 100; nodeInfo.feeRate = 33; nodeInfo.previousFeePeriod = 44; nodeInfo.feeDelta[11] = 55; nodeInfo.minFeeRate = 777; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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) { // 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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./Upgradeable.sol"; import "../../zeppelin/utils/Address.sol"; /** * @notice ERC897 - ERC DelegateProxy */ interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); } /** * @notice Proxying requests to other contracts. * Client should use ABI of real contract and address of this contract */ contract Dispatcher is Upgradeable, ERCProxy { using Address for address; event Upgraded(address indexed from, address indexed to, address owner); event RolledBack(address indexed from, address indexed to, address owner); /** * @dev Set upgrading status before and after operations */ modifier upgrading() { isUpgrade = UPGRADE_TRUE; _; isUpgrade = UPGRADE_FALSE; } /** * @param _target Target contract address */ constructor(address _target) upgrading { require(_target.isContract()); // Checks that target contract inherits Dispatcher state verifyState(_target); // `verifyState` must work with its contract verifyUpgradeableState(_target, _target); target = _target; finishUpgrade(); emit Upgraded(address(0), _target, msg.sender); } //------------------------ERC897------------------------ /** * @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() external pure override returns (uint256) { return 2; } /** * @notice ERC897, gets the address of the implementation where every call will be delegated */ function implementation() external view override returns (address) { return target; } //------------------------------------------------------------ /** * @notice Verify new contract storage and upgrade target * @param _target New target contract address */ function upgrade(address _target) public onlyOwner upgrading { require(_target.isContract()); // Checks that target contract has "correct" (as much as possible) state layout verifyState(_target); //`verifyState` must work with its contract verifyUpgradeableState(_target, _target); if (target.isContract()) { verifyUpgradeableState(target, _target); } previousTarget = target; target = _target; finishUpgrade(); emit Upgraded(previousTarget, _target, msg.sender); } /** * @notice Rollback to previous target * @dev Test storage carefully before upgrade again after rollback */ function rollback() public onlyOwner upgrading { require(previousTarget.isContract()); emit RolledBack(target, previousTarget, msg.sender); // should be always true because layout previousTarget -> target was already checked // but `verifyState` is not 100% accurate so check again verifyState(previousTarget); if (target.isContract()) { verifyUpgradeableState(previousTarget, target); } target = previousTarget; previousTarget = address(0); finishUpgrade(); } /** * @dev Call verifyState method for Upgradeable contract */ function verifyUpgradeableState(address _from, address _to) private { (bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to)); require(callSuccess); } /** * @dev Call finishUpgrade method from the Upgradeable contract */ function finishUpgrade() private { (bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target)); require(callSuccess); } function verifyState(address _testTarget) public override onlyWhileUpgrading { //checks equivalence accessing state through new contract and current storage require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner()); require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target); require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget); require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade); } /** * @dev Override function using empty code because no reason to call this function in Dispatcher */ function finishUpgrade(address) public override {} /** * @dev Receive function sends empty request to the target contract */ receive() external payable { assert(target.isContract()); // execute receive function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(""); if (!callSuccess) { revert(); } } /** * @dev Fallback function sends all requests to the target contract */ fallback() external payable { assert(target.isContract()); // execute requested function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/utils/Address.sol"; import "../../zeppelin/token/ERC20/SafeERC20.sol"; import "./StakingInterface.sol"; import "../../zeppelin/proxy/Initializable.sol"; /** * @notice Router for accessing interface contract */ contract StakingInterfaceRouter is Ownable { BaseStakingInterface public target; /** * @param _target Address of the interface contract */ constructor(BaseStakingInterface _target) { require(address(_target.token()) != address(0)); target = _target; } /** * @notice Upgrade interface * @param _target New contract address */ function upgrade(BaseStakingInterface _target) external onlyOwner { require(address(_target.token()) != address(0)); target = _target; } } /** * @notice Internal base class for AbstractStakingContract and InitializableStakingContract */ abstract contract RawStakingContract { using Address for address; /** * @dev Returns address of StakingInterfaceRouter */ function router() public view virtual returns (StakingInterfaceRouter); /** * @dev Checks permission for calling fallback function */ function isFallbackAllowed() public virtual returns (bool); /** * @dev Withdraw tokens from staking contract */ function withdrawTokens(uint256 _value) public virtual; /** * @dev Withdraw ETH from staking contract */ function withdrawETH() public virtual; receive() external payable {} /** * @dev Function sends all requests to the target contract */ fallback() external payable { require(isFallbackAllowed()); address target = address(router().target()); require(target.isContract()); // execute requested function from target contract (bool callSuccess, ) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } /** * @notice Base class for any staking contract (not usable with openzeppelin proxy) * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract AbstractStakingContract is RawStakingContract { StakingInterfaceRouter immutable router_; NuCypherToken public immutable token; /** * @param _router Interface router contract address */ constructor(StakingInterfaceRouter _router) { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } /** * @notice Base class for any staking contract usable with openzeppelin proxy * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract InitializableStakingContract is Initializable, RawStakingContract { StakingInterfaceRouter router_; NuCypherToken public token; /** * @param _router Interface router contract address */ function initialize(StakingInterfaceRouter _router) public initializer { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./AbstractStakingContract.sol"; import "../NuCypherToken.sol"; import "../StakingEscrow.sol"; import "../PolicyManager.sol"; import "../WorkLock.sol"; /** * @notice Base StakingInterface */ contract BaseStakingInterface { address public immutable stakingInterfaceAddress; NuCypherToken public immutable token; StakingEscrow public immutable escrow; PolicyManager public immutable policyManager; WorkLock public immutable workLock; /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) { require(_token.totalSupply() > 0 && _escrow.secondsPerPeriod() > 0 && _policyManager.secondsPerPeriod() > 0 && // in case there is no worklock contract (address(_workLock) == address(0) || _workLock.boostingRefund() > 0)); token = _token; escrow = _escrow; policyManager = _policyManager; workLock = _workLock; stakingInterfaceAddress = address(this); } /** * @dev Checks executing through delegate call */ modifier onlyDelegateCall() { require(stakingInterfaceAddress != address(this)); _; } /** * @dev Checks the existence of the worklock contract */ modifier workLockSet() { require(address(workLock) != address(0)); _; } } /** * @notice Interface for accessing main contracts from a staking contract * @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields. * @dev |v1.7.1| */ contract StakingInterface is BaseStakingInterface { event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods); event WithdrawnAsStaker(address indexed sender, uint256 value); event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value); event LockedAndCreated(address indexed sender, uint256 value, uint16 periods); event LockedAndIncreased(address indexed sender, uint256 index, uint256 value); event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods); event Merged(address indexed sender, uint256 index1, uint256 index2); event Minted(address indexed sender); event PolicyFeeWithdrawn(address indexed sender, uint256 value); event MinFeeRateSet(address indexed sender, uint256 value); event ReStakeSet(address indexed sender, bool reStake); event WorkerBonded(address indexed sender, address worker); event Prolonged(address indexed sender, uint256 index, uint16 periods); event WindDownSet(address indexed sender, bool windDown); event SnapshotSet(address indexed sender, bool snapshotsEnabled); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); event BidCanceled(address indexed sender); event CompensationWithdrawn(address indexed sender); /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) BaseStakingInterface(_token, _escrow, _policyManager, _workLock) { } /** * @notice Bond worker in the staking escrow * @param _worker Worker address */ function bondWorker(address _worker) public onlyDelegateCall { escrow.bondWorker(_worker); emit WorkerBonded(msg.sender, _worker); } /** * @notice Set `reStake` parameter in the staking escrow * @param _reStake Value for parameter */ function setReStake(bool _reStake) public onlyDelegateCall { escrow.setReStake(_reStake); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens to the staking escrow * @param _value Amount of token to deposit * @param _periods Amount of periods during which tokens will be locked */ function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.deposit(address(this), _value, _periods); emit DepositedAsStaker(msg.sender, _value, _periods); } /** * @notice Deposit tokens to the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.depositAndIncrease(_index, _value); emit DepositedAndIncreased(msg.sender, _index, _value); } /** * @notice Withdraw available amount of tokens from the staking escrow to the staking contract * @param _value Amount of token to withdraw */ function withdrawAsStaker(uint256 _value) public onlyDelegateCall { escrow.withdraw(_value); emit WithdrawnAsStaker(msg.sender, _value); } /** * @notice Lock some tokens in the staking escrow * @param _value Amount of tokens which should lock * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall { escrow.lockAndCreate(_value, _periods); emit LockedAndCreated(msg.sender, _value, _periods); } /** * @notice Lock some tokens in the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { escrow.lockAndIncrease(_index, _value); emit LockedAndIncreased(msg.sender, _index, _value); } /** * @notice Divide stake into two parts * @param _index Index of stake * @param _newValue New stake value * @param _periods Amount of periods for extending stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall { escrow.divideStake(_index, _newValue, _periods); emit Divided(msg.sender, _index, _newValue, _periods); } /** * @notice Merge two sub-stakes into one * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall { escrow.mergeStake(_index1, _index2); emit Merged(msg.sender, _index1, _index2); } /** * @notice Mint tokens in the staking escrow */ function mint() public onlyDelegateCall { escrow.mint(); emit Minted(msg.sender); } /** * @notice Withdraw available policy fees from the policy manager to the staking contract */ function withdrawPolicyFee() public onlyDelegateCall { uint256 value = policyManager.withdraw(); emit PolicyFeeWithdrawn(msg.sender, value); } /** * @notice Set the minimum fee that the staker will accept in the policy manager contract */ function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall { policyManager.setMinFeeRate(_minFeeRate); emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _periods Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall { escrow.prolongStake(_index, _periods); emit Prolonged(msg.sender, _index, _periods); } /** * @notice Set `windDown` parameter in the staking escrow * @param _windDown Value for parameter */ function setWindDown(bool _windDown) public onlyDelegateCall { escrow.setWindDown(_windDown); emit WindDownSet(msg.sender, _windDown); } /** * @notice Set `snapshots` parameter in the staking escrow * @param _enableSnapshots Value for parameter */ function setSnapshots(bool _enableSnapshots) public onlyDelegateCall { escrow.setSnapshots(_enableSnapshots); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Bid for tokens by transferring ETH */ function bid(uint256 _value) public payable onlyDelegateCall workLockSet { workLock.bid{value: _value}(); emit Bid(msg.sender, _value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() public onlyDelegateCall workLockSet { workLock.cancelBid(); emit BidCanceled(msg.sender); } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() public onlyDelegateCall workLockSet { workLock.withdrawCompensation(); emit CompensationWithdrawn(msg.sender); } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract */ function claim() public onlyDelegateCall workLockSet { uint256 claimedTokens = workLock.claim(); emit Claimed(msg.sender, claimedTokens); } /** * @notice Refund ETH for the completed work */ function refund() public onlyDelegateCall workLockSet { uint256 refundETH = workLock.refund(); emit Refund(msg.sender, refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/utils/Address.sol"; import "../zeppelin/ownership/Ownable.sol"; import "./NuCypherToken.sol"; import "./StakingEscrow.sol"; import "./lib/AdditionalMath.sol"; /** * @notice The WorkLock distribution contract */ contract WorkLock is Ownable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using Address for address payable; using Address for address; event Deposited(address indexed sender, uint256 value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH, uint256 completedWork); event Canceled(address indexed sender, uint256 value); event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex); event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH); event CompensationWithdrawn(address indexed sender, uint256 value); event Shutdown(address indexed sender); struct WorkInfo { uint256 depositedETH; uint256 completedWork; bool claimed; uint128 index; } uint16 public constant SLOWING_REFUND = 100; uint256 private constant MAX_ETH_SUPPLY = 2e10 ether; NuCypherToken public immutable token; StakingEscrow public immutable escrow; /* * @dev WorkLock calculations: * bid = minBid + bonusETHPart * bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens * bonusDepositRate = bonusTokenSupply / bonusETHSupply * claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate * bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund * refundETH = completedWork / refundRate */ uint256 public immutable boostingRefund; uint256 public immutable minAllowedBid; uint16 public immutable stakingPeriods; // copy from the escrow contract uint256 public immutable maxAllowableLockedTokens; uint256 public immutable minAllowableLockedTokens; uint256 public tokenSupply; uint256 public startBidDate; uint256 public endBidDate; uint256 public endCancellationDate; uint256 public bonusETHSupply; mapping(address => WorkInfo) public workInfo; mapping(address => uint256) public compensation; address[] public bidders; // if value == bidders.length then WorkLock is fully checked uint256 public nextBidderToCheck; /** * @dev Checks timestamp regarding cancellation window */ modifier afterCancellationWindow() { require(block.timestamp >= endCancellationDate, "Operation is allowed when cancellation phase is over"); _; } /** * @param _token Token contract * @param _escrow Escrow contract * @param _startBidDate Timestamp when bidding starts * @param _endBidDate Timestamp when bidding will end * @param _endCancellationDate Timestamp when cancellation will ends * @param _boostingRefund Coefficient to boost refund ETH * @param _stakingPeriods Amount of periods during which tokens will be locked after claiming * @param _minAllowedBid Minimum allowed ETH amount for bidding */ constructor( NuCypherToken _token, StakingEscrow _escrow, uint256 _startBidDate, uint256 _endBidDate, uint256 _endCancellationDate, uint256 _boostingRefund, uint16 _stakingPeriods, uint256 _minAllowedBid ) { uint256 totalSupply = _token.totalSupply(); require(totalSupply > 0 && // token contract is deployed and accessible _escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible _escrow.token() == _token && // same token address for worklock and escrow _endBidDate > _startBidDate && // bidding period lasts some time _endBidDate > block.timestamp && // there is time to make a bid _endCancellationDate >= _endBidDate && // cancellation window includes bidding _minAllowedBid > 0 && // min allowed bid was set _boostingRefund > 0 && // boosting coefficient was set _stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract // worst case for `ethToWork()` and `workToETH()`, // when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND && MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund); token = _token; escrow = _escrow; startBidDate = _startBidDate; endBidDate = _endBidDate; endCancellationDate = _endCancellationDate; boostingRefund = _boostingRefund; stakingPeriods = _stakingPeriods; minAllowedBid = _minAllowedBid; maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens(); minAllowableLockedTokens = _escrow.minAllowableLockedTokens(); } /** * @notice Deposit tokens to contract * @param _value Amount of tokens to transfer */ function tokenDeposit(uint256 _value) external { require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding"); token.safeTransferFrom(msg.sender, address(this), _value); tokenSupply += _value; emit Deposited(msg.sender, _value); } /** * @notice Calculate amount of tokens that will be get for specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToTokens(uint256 _ethAmount) public view returns (uint256) { if (_ethAmount < minAllowedBid) { return 0; } // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return tokenSupply / bidders.length; } uint256 bonusETH = _ethAmount - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH */ function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply) internal view returns (uint256) { return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund)); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding * @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work * @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted * @dev _ethToReclaim + _restOfDepositedETH = depositedETH */ function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply); } uint256 baseETH = 0; uint256 bonusETH = 0; // If the staker's total remaining deposit (including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then only the base part is used to calculate the work required to reclaim ETH if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) { baseETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is still greater than the minimum bid size, // then only the bonus part is used to calculate the work required to reclaim ETH } else if (_restOfDepositedETH >= minAllowedBid) { bonusETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then both the base and bonus parts must be used to calculate the work required to reclaim ETH } else { bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid; baseETH = _ethToReclaim - bonusETH; } uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; uint256 work = 0; if (baseETH > 0) { work = ethToWork(baseETH, baseTokenSupply, baseETHSupply); } if (bonusETH > 0) { uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); } return work; } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToWork(uint256 _ethAmount) public view returns (uint256) { return ethToWork(_ethAmount, 0); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work */ function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply) internal view returns (uint256) { return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND)); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work * @dev This value will be fixed only after end of bidding */ function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return workToETH(_completedWork, baseETHSupply, tokenSupply); } uint256 bonusWork = 0; uint256 bonusETH = 0; uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; if (_depositedETH > minAllowedBid) { bonusETH = _depositedETH - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); if (_completedWork <= bonusWork) { return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply); } } _completedWork -= bonusWork; return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply); } /** * @notice Get remaining work to full refund */ function getRemainingWork(address _bidder) external view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork); uint256 remainingWork = ethToWork(info.depositedETH); if (remainingWork <= completedWork) { return 0; } return remainingWork - completedWork; } /** * @notice Get length of bidders array */ function getBiddersLength() external view returns (uint256) { return bidders.length; } /** * @notice Bid for tokens by transferring ETH */ function bid() external payable { require(block.timestamp >= startBidDate, "Bidding is not open yet"); require(block.timestamp < endBidDate, "Bidding is already finished"); WorkInfo storage info = workInfo[msg.sender]; // first bid if (info.depositedETH == 0) { require(msg.value >= minAllowedBid, "Bid must be at least minimum"); require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders"); info.index = uint128(bidders.length); bidders.push(msg.sender); bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid); } else { bonusETHSupply = bonusETHSupply.add(msg.value); } info.depositedETH = info.depositedETH.add(msg.value); emit Bid(msg.sender, msg.value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() external { require(block.timestamp < endCancellationDate, "Cancellation allowed only during cancellation window"); WorkInfo storage info = workInfo[msg.sender]; require(info.depositedETH > 0, "No bid to cancel"); require(!info.claimed, "Tokens are already claimed"); uint256 refundETH = info.depositedETH; info.depositedETH = 0; // remove from bidders array, move last bidder to the empty place uint256 lastIndex = bidders.length - 1; if (info.index != lastIndex) { address lastBidder = bidders[lastIndex]; bidders[info.index] = lastBidder; workInfo[lastBidder].index = info.index; } bidders.pop(); if (refundETH > minAllowedBid) { bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid); } msg.sender.sendValue(refundETH); emit Canceled(msg.sender, refundETH); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function shutdown() external onlyOwner { require(!isClaimingAvailable(), "Claiming has already been enabled"); internalShutdown(); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function internalShutdown() internal { startBidDate = 0; endBidDate = 0; endCancellationDate = uint256(0) - 1; // "infinite" cancellation window token.safeTransfer(owner(), tokenSupply); emit Shutdown(msg.sender); } /** * @notice Make force refund to bidders who can get tokens more than maximum allowed * @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund */ function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); uint256 length = _biddersForRefund.length; require(length > 0, "Must be at least one bidder for a refund"); uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens); if (bidders.length < minNumberOfBidders) { internalShutdown(); return; } address previousBidder = _biddersForRefund[0]; uint256 minBid = workInfo[previousBidder].depositedETH; uint256 maxBid = minBid; // get minimum and maximum bids for (uint256 i = 1; i < length; i++) { address bidder = _biddersForRefund[i]; uint256 depositedETH = workInfo[bidder].depositedETH; require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders"); if (minBid > depositedETH) { minBid = depositedETH; } else if (maxBid < depositedETH) { maxBid = depositedETH; } previousBidder = bidder; } uint256[] memory refunds = new uint256[](length); // first step - align at a minimum bid if (minBid != maxBid) { for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; if (info.depositedETH > minBid) { refunds[i] = info.depositedETH - minBid; info.depositedETH = minBid; bonusETHSupply -= refunds[i]; } } } require(ethToTokens(minBid) > maxAllowableLockedTokens, "At least one of bidders has allowable bid"); // final bids adjustment (only for bonus part) // (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales) uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 minBonusETH = minBid - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 refundETH = minBonusETH.mul(bonusTokenSupply) .sub(maxBonusTokens.mul(bonusETHSupply)) .divCeil(bonusTokenSupply - maxBonusTokens.mul(length)); uint256 resultBid = minBid.sub(refundETH); bonusETHSupply -= length * refundETH; for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; refunds[i] += refundETH; info.depositedETH = resultBid; } // reset verification nextBidderToCheck = 0; // save a refund for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; compensation[bidder] += refunds[i]; emit ForceRefund(msg.sender, bidder, refunds[i]); } } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() external { uint256 refund = compensation[msg.sender]; require(refund > 0, "There is no compensation"); compensation[msg.sender] = 0; msg.sender.sendValue(refund); emit CompensationWithdrawn(msg.sender, refund); } /** * @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants, * starting from the last point `nextBidderToCheck` * @dev Method stops working when the remaining gas is less than `_gasToSaveState` * and saves the state in `nextBidderToCheck`. * If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array */ function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); // all participants bid with the same minimum amount of eth uint256 index = nextBidderToCheck; if (bonusETHSupply == 0) { require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders"); index = bidders.length; } uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply); while (index < bidders.length && gasleft() > _gasToSaveState) { address bidder = bidders[index]; require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid"); index++; } if (index != nextBidderToCheck) { emit BiddersChecked(msg.sender, nextBidderToCheck, index); nextBidderToCheck = index; } return nextBidderToCheck; } /** * @notice Checks if claiming available */ function isClaimingAvailable() public view returns (bool) { return block.timestamp >= endCancellationDate && nextBidderToCheck == bidders.length; } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract. */ function claim() external returns (uint256 claimedTokens) { require(isClaimingAvailable(), "Claiming has not been enabled yet"); WorkInfo storage info = workInfo[msg.sender]; require(!info.claimed, "Tokens are already claimed"); claimedTokens = ethToTokens(info.depositedETH); require(claimedTokens > 0, "Nothing to claim"); info.claimed = true; token.approve(address(escrow), claimedTokens); escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods); info.completedWork = escrow.setWorkMeasurement(msg.sender, true); emit Claimed(msg.sender, claimedTokens); } /** * @notice Get available refund for bidder */ function getAvailableRefund(address _bidder) public view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; // nothing to refund if (info.depositedETH == 0) { return 0; } uint256 currentWork = escrow.getCompletedWork(_bidder); uint256 completedWork = currentWork.sub(info.completedWork); // no work that has been completed since last refund if (completedWork == 0) { return 0; } uint256 refundETH = workToETH(completedWork, info.depositedETH); if (refundETH > info.depositedETH) { refundETH = info.depositedETH; } return refundETH; } /** * @notice Refund ETH for the completed work */ function refund() external returns (uint256 refundETH) { WorkInfo storage info = workInfo[msg.sender]; require(info.claimed, "Tokens must be claimed before refund"); refundETH = getAvailableRefund(msg.sender); require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work"); if (refundETH == info.depositedETH) { escrow.setWorkMeasurement(msg.sender, false); } info.depositedETH = info.depositedETH.sub(refundETH); // convert refund back to work to eliminate potential rounding errors uint256 completedWork = ethToWork(refundETH, info.depositedETH); info.completedWork = info.completedWork.add(completedWork); emit Refund(msg.sender, refundETH, completedWork); msg.sender.sendValue(refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^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; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner **/ contract PoolingStakingContract is AbstractStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens); event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } StakingEscrow public immutable escrow; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public ownerFraction; uint256 public ownerWithdrawnReward; uint256 public ownerWithdrawnETH; mapping (address => Delegator) public delegators; bool depositIsEnabled = true; /** * @param _router Address of the StakingInterfaceRouter contract * @param _ownerFraction Base owner's portion of reward */ constructor( StakingInterfaceRouter _router, uint256 _ownerFraction ) AbstractStakingContract(_router) { escrow = _router.target().escrow(); ownerFraction = _ownerFraction; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens += _value; token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens + freeTokens - totalDepositedTokens; if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for pool owner */ function getAvailableOwnerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); } else { maxAllowableReward = reward; } return maxAllowableReward.sub(ownerWithdrawnReward); } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableReward = reward.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to owner */ function withdrawOwnerReward() public onlyOwner { uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableOwnerReward(); if (availableReward > balance) { availableReward = balance; } require(availableReward > 0, "There is no available reward to withdraw"); ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw amount of tokens to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); uint256 availableReward = getAvailableReward(msg.sender); Delegator storage delegator = delegators[msg.sender]; require(_value <= availableReward + delegator.depositedTokens, "Requested amount of tokens exceeded allowed portion"); if (_value <= availableReward) { delegator.withdrawnReward += _value; totalWithdrawnReward += _value; } else { delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); uint256 depositToWithdraw = _value - availableReward; uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw; uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens); uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens); totalDepositedTokens -= depositToWithdraw; totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward); totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH); delegator.depositedTokens = newDepositedTokens; delegator.withdrawnReward = newWithdrawnReward; delegator.withdrawnETH = newWithdrawnETH; } token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available ether for owner */ function getAvailableOwnerETH() public view returns (uint256) { // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to pool owner */ function withdrawOwnerETH() public onlyOwner { uint256 availableETH = getAvailableOwnerETH(); require(availableETH > 0, "There is no available ETH to withdraw"); ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner **/ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers **/ contract PoolingStakingContractV2 is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event WorkerOwnerSet(address indexed sender, address indexed workerOwner); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } /** * Defines base fraction and precision of worker fraction. * E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000) */ uint256 public constant BASIS_FRACTION = 10000; StakingEscrow public escrow; address public workerOwner; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission. * For example, 100 worker fraction is 1% of reward * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) external initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workerFraction = _workerFraction; workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice withdrawAll() is allowed */ function isWithdrawAllAllowed() public view returns (bool) { // no tokens in StakingEscrow contract which belong to pool return escrow.getAllTokens(address(this)) == 0; } /** * @notice deposit() is allowed */ function isDepositAllowed() public view returns (bool) { // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // no sub-stakes and no earned reward return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens; } /** * @notice Set worker owner address */ function setWorkerOwner(address _workerOwner) external onlyOwner { workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice Calculate worker's fraction depending on deposited tokens * Override to implement dynamic worker fraction. */ function getWorkerFraction() public view virtual returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(isDepositAllowed(), "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { // locked + unlocked tokens in StakingEscrow contract which belong to pool uint256 stakedTokens = escrow.getAllTokens(address(this)); // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // tokens in excess of the initially deposited uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); // check how many of reward tokens belong directly to pool if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward. * Available and withdrawn reward together to use in delegator/owner reward calculations */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { // total current and historical reward uint256 reward = getCumulativeReward(); // calculate total reward for worker including historical reward uint256 maxAllowableReward; // usual case if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); // special case when there are no delegators } else { maxAllowableReward = reward; } // check that worker has any new reward if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableDelegatorReward(address _delegator) public view returns (uint256) { // special case when there are no delegators if (totalDepositedTokens == 0) { return 0; } // total current and historical reward uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); // calculate total reward for delegator including historical reward // excluding worker share uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); // check that worker has any new reward if (maxAllowableReward > delegator.withdrawnReward) { return maxAllowableReward - delegator.withdrawnReward; } return 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled"); uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableDelegatorETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableDelegatorETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; uint256 availableETH = getAvailableDelegatorETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract holds tokens for vesting. * Also tokens can be used as a stake in the staking escrow contract */ contract PreallocationEscrow is AbstractStakingContract, Ownable { using SafeMath for uint256; using SafeERC20 for NuCypherToken; using Address for address payable; event TokensDeposited(address indexed sender, uint256 value, uint256 duration); event TokensWithdrawn(address indexed owner, uint256 value); event ETHWithdrawn(address indexed owner, uint256 value); StakingEscrow public immutable stakingEscrow; uint256 public lockedValue; uint256 public endLockTimestamp; /** * @param _router Address of the StakingInterfaceRouter contract */ constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) { stakingEscrow = _router.target().escrow(); } /** * @notice Initial tokens deposit * @param _sender Token sender * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal { require(lockedValue == 0 && _value > 0); endLockTimestamp = block.timestamp.add(_duration); lockedValue = _value; token.safeTransferFrom(_sender, address(this), _value); emit TokensDeposited(_sender, _value, _duration); } /** * @notice Initial tokens deposit * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(uint256 _value, uint256 _duration) external { initialDeposit(msg.sender, _value, _duration); } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Initial tokens deposit * @param _from Sender * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of seconds during which tokens will be locked */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); initialDeposit(_from, _value, payload); } /** * @notice Get locked tokens value */ function getLockedTokens() public view returns (uint256) { if (endLockTimestamp <= block.timestamp) { return 0; } return lockedValue; } /** * @notice Withdraw available amount of tokens to owner * @param _value Amount of token to withdraw */ function withdrawTokens(uint256 _value) public override onlyOwner { uint256 balance = token.balanceOf(address(this)); require(balance >= _value); // Withdrawal invariant for PreallocationEscrow: // After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens()); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value); } /** * @notice Withdraw available ETH to the owner */ function withdrawETH() public override onlyOwner { uint256 balance = address(this).balance; require(balance != 0); msg.sender.sendValue(balance); emit ETHWithdrawn(msg.sender, balance); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner * @author @vzotova and @roma_k **/ contract WorkLockPoolingContract is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; uint256 depositedETHWorkLock; uint256 refundedETHWorkLock; bool claimedWorkLockTokens; } uint256 public constant BASIS_FRACTION = 100; StakingEscrow public escrow; WorkLock public workLock; address public workerOwner; uint256 public totalDepositedTokens; uint256 public workLockClaimedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public totalWorkLockETHReceived; uint256 public totalWorkLockETHRefunded; uint256 public totalWorkLockETHWithdrawn; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; bool depositIsEnabled = true; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) public initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workLock = _router.target().workLock(); workerFraction = _workerFraction; workerOwner = _workerOwner; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Calculate worker's fraction depending on deposited tokens */ function getWorkerFraction() public view returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Delegator can transfer ETH directly to workLock */ function escrowETH() external payable { Delegator storage delegator = delegators[msg.sender]; delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value); totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value); workLock.bid{value: msg.value}(); emit Bid(msg.sender, msg.value); } /** * @dev Hide method from StakingInterface */ function bid(uint256) public payable { revert(); } /** * @dev Hide method from StakingInterface */ function withdrawCompensation() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function cancelBid() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function claim() public pure { revert(); } /** * @notice Claim tokens in WorkLock and save number of claimed tokens */ function claimTokensFromWorkLock() public { workLockClaimedTokens = workLock.claim(); totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens); emit Claimed(address(this), workLockClaimedTokens); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount() external { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount(Delegator storage _delegator) internal { if (workLockClaimedTokens == 0 || _delegator.depositedETHWorkLock == 0 || _delegator.claimedWorkLockTokens) { return; } uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens) .div(totalWorkLockETHReceived); _delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare); _delegator.claimedWorkLockTokens = true; emit Claimed(msg.sender, delegatorTokensShare); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); } else { maxAllowableReward = reward; } if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn - (refunded - refundWithdrawn) balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw compensation and refund from WorkLock and save these numbers */ function refund() public { uint256 balance = address(this).balance; if (workLock.compensation(address(this)) > 0) { workLock.withdrawCompensation(); } workLock.refund(); uint256 refundETH = address(this).balance - balance; totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH); emit Refund(address(this), refundETH); } /** * @notice Get available refund for delegator */ function getAvailableRefund(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock) .div(totalWorkLockETHReceived); uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock); uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn); if (availableETH > balance) { availableETH = balance; } return availableETH; } /* * @notice Withdraw available amount of ETH to delegator */ function withdrawRefund() external { uint256 availableETH = getAvailableRefund(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH); totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH); msg.sender.sendValue(availableETH); emit Refund(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } }
Call "getter" with two parameters. Result should not exceed 32 bytes/
function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } }
1,393,257
./full_match/1/0x99a9B7c1116f9ceEB1652de04d5969CcE509B069/sources/contracts/GenArt721CoreV3.sol
Updates artist name for project `_projectId` to be `_projectArtistName`. _projectId Project ID. _projectArtistName New artist name./
function updateProjectArtistName( uint256 _projectId, string memory _projectArtistName ) external onlyUnlocked(_projectId) onlyArtistOrAdminACL(_projectId, this.updateProjectArtistName.selector) onlyNonEmptyString(_projectArtistName) { projects[_projectId].artist = _projectArtistName; emit ProjectUpdated(_projectId, FIELD_PROJECT_ARTIST_NAME); }
17,012,441
pragma solidity ^0.4.15; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes data) private returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
Allows to remove an owner. Transaction has to be sent by wallet. owner Address of owner.
function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); }
10,044,326
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol"; import "../interface/IOracle.sol"; import "../libraries/OrderData.sol"; import "../libraries/SafeMathExt.sol"; import "../libraries/Utils.sol"; import "./AMMModule.sol"; import "./LiquidityPoolModule.sol"; import "./MarginAccountModule.sol"; import "./PerpetualModule.sol"; import "../Type.sol"; library TradeModule { using SafeMathExt for int256; using SignedSafeMathUpgradeable for int256; using OrderData for uint32; using AMMModule for LiquidityPoolStorage; using LiquidityPoolModule for LiquidityPoolStorage; using MarginAccountModule for PerpetualStorage; using PerpetualModule for PerpetualStorage; using MarginAccountModule for MarginAccount; event Trade( uint256 perpetualIndex, address indexed trader, int256 position, int256 price, int256 fee, int256 lpFee ); event Liquidate( uint256 perpetualIndex, address indexed liquidator, address indexed trader, int256 amount, int256 price, int256 penalty, int256 penaltyToLP ); event TransferFeeToOperator(address indexed operator, int256 operatorFee); event TransferFeeToReferrer( uint256 perpetualIndex, address indexed trader, address indexed referrer, int256 referralRebate ); /** * @dev See `trade` in Perpetual.sol for details. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param trader The address of trader. * @param amount The amount of position to trader, positive for buying and negative for selling. * @param limitPrice The worst price the trader accepts. * @param referrer The address of referrer who will get rebate in the deal. * @param flags The flags of the trade, contains extra config for trading. * @return tradeAmount The amount of positions actually traded in the transaction. */ function trade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount, int256 limitPrice, address referrer, uint32 flags ) public returns (int256 tradeAmount) { (int256 deltaCash, int256 deltaPosition) = preTrade( liquidityPool, perpetualIndex, trader, amount, limitPrice, flags ); doTrade(liquidityPool, perpetualIndex, trader, deltaCash, deltaPosition); (int256 lpFee, int256 totalFee) = postTrade( liquidityPool, perpetualIndex, trader, referrer, deltaCash, deltaPosition, flags ); emit Trade( perpetualIndex, trader, deltaPosition.neg(), deltaCash.wdiv(deltaPosition).abs(), totalFee, lpFee ); tradeAmount = deltaPosition.neg(); require( liquidityPool.isTraderMarginSafe(perpetualIndex, trader, tradeAmount), "trader margin unsafe" ); } function preTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount, int256 limitPrice, uint32 flags ) internal returns (int256 deltaCash, int256 deltaPosition) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; require(!IOracle(perpetual.oracle).isMarketClosed(), "market is closed now"); // handle close only flag if (flags.isCloseOnly()) { amount = getMaxPositionToClose(perpetual.getPosition(trader), amount); require(amount != 0, "no amount to close"); } // query price from AMM (deltaCash, deltaPosition) = liquidityPool.queryTradeWithAMM( perpetualIndex, amount.neg(), false ); // check price if (!flags.isMarketOrder()) { int256 tradePrice = deltaCash.wdiv(deltaPosition).abs(); validatePrice(amount >= 0, tradePrice, limitPrice); } } function doTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 deltaCash, int256 deltaPosition ) internal { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; int256 deltaOpenInterest1 = perpetual.updateMargin(address(this), deltaPosition, deltaCash); int256 deltaOpenInterest2 = perpetual.updateMargin( trader, deltaPosition.neg(), deltaCash.neg() ); require(perpetual.openInterest >= 0, "negative open interest"); if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) { // open interest will increase, check limit (int256 poolMargin, ) = liquidityPool.getPoolMargin(); require( perpetual.openInterest <= perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()), "open interest exceeds limit" ); } } /** * @dev Execute the trade. If the trader has opened position in the trade, his account should be * initial margin safe after the trade. If not, his account should be margin safe * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of pereptual storage. * @param trader The address of trader. * @param referrer The address of referrer who will get rebate from the deal. * @param deltaCash The amount of cash changes in a trade. * @param deltaPosition The amount of position changes in a trade. * @return lpFee The amount of fee for lp provider. * @return totalFee The total fee collected from the trader after the trade. */ function postTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, address referrer, int256 deltaCash, int256 deltaPosition, uint32 flags ) internal returns (int256 lpFee, int256 totalFee) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; // fees int256 operatorFee; int256 vaultFee; int256 referralRebate; { bool hasOpened = Utils.hasOpenedPosition( perpetual.getPosition(trader), deltaPosition.neg() ); (lpFee, operatorFee, vaultFee, referralRebate) = getFees( liquidityPool, perpetual, trader, referrer, deltaCash.abs(), hasOpened ); } totalFee = lpFee.add(operatorFee).add(vaultFee).add(referralRebate); perpetual.updateCash(trader, totalFee.neg()); // trader deposit/withdraw if (flags.useTargetLeverage()) { liquidityPool.adjustMarginLeverage( perpetualIndex, trader, deltaPosition.neg(), deltaCash.neg(), totalFee ); } // send fee transferFee( liquidityPool, perpetualIndex, trader, referrer, lpFee, operatorFee, vaultFee, referralRebate ); } /** * @dev Get the fees of the trade. If the margin of the trader is not enough for fee: * 1. If trader open position, the trade will be reverted. * 2. If trader close position, the fee will be decreasing in proportion according to * the margin left in the trader's account * The rebate of referral will only calculate the lpFee and operatorFee. * The vault fee will not be counted in. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetual The reference of pereptual storage. * @param trader The address of trader. * @param referrer The address of referrer who will get rebate from the deal. * @param tradeValue The amount of trading value, measured by collateral, abs of deltaCash. * @return lpFee The amount of fee to the Liquidity provider. * @return operatorFee The amount of fee to the operator. * @return vaultFee The amount of fee to the vault. * @return referralRebate The amount of rebate of the refferral. */ function getFees( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, address trader, address referrer, int256 tradeValue, bool hasOpened ) public view returns ( int256 lpFee, int256 operatorFee, int256 vaultFee, int256 referralRebate ) { require(tradeValue >= 0, "trade value is negative"); vaultFee = tradeValue.wmul(liquidityPool.getVaultFeeRate()); lpFee = tradeValue.wmul(perpetual.lpFeeRate); if (liquidityPool.getOperator() != address(0)) { operatorFee = tradeValue.wmul(perpetual.operatorFeeRate); } int256 totalFee = lpFee.add(operatorFee).add(vaultFee); int256 availableMargin = perpetual.getAvailableMargin(trader, perpetual.getMarkPrice()); if (!hasOpened) { if (availableMargin <= 0) { lpFee = 0; operatorFee = 0; vaultFee = 0; referralRebate = 0; } else if (totalFee > availableMargin) { // make sure the sum of fees < available margin int256 rate = availableMargin.wdiv(totalFee, Round.FLOOR); operatorFee = operatorFee.wmul(rate, Round.FLOOR); vaultFee = vaultFee.wmul(rate, Round.FLOOR); lpFee = availableMargin.sub(operatorFee).sub(vaultFee); } } if ( referrer != address(0) && perpetual.referralRebateRate > 0 && lpFee.add(operatorFee) > 0 ) { int256 lpFeeRebate = lpFee.wmul(perpetual.referralRebateRate); int256 operatorFeeRabate = operatorFee.wmul(perpetual.referralRebateRate); referralRebate = lpFeeRebate.add(operatorFeeRabate); lpFee = lpFee.sub(lpFeeRebate); operatorFee = operatorFee.sub(operatorFeeRabate); } } function transferFee( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, address referrer, int256 lpFee, int256 operatorFee, int256 vaultFee, int256 referralRebate ) internal { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.updateCash(address(this), lpFee); liquidityPool.transferFromPerpetualToUser(perpetual.id, referrer, referralRebate); liquidityPool.transferFromPerpetualToUser(perpetual.id, liquidityPool.getVault(), vaultFee); address operator = liquidityPool.getOperator(); liquidityPool.transferFromPerpetualToUser(perpetual.id, operator, operatorFee); emit TransferFeeToOperator(operator, operatorFee); emit TransferFeeToReferrer(perpetual.id, trader, referrer, referralRebate); } /** * @dev See `liquidateByAMM` in Perpetual.sol for details. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param liquidator The address of the account calling the liquidation method. * @param trader The address of the liquidated account. * @return liquidatedAmount The amount of positions actually liquidated in the transaction. */ function liquidateByAMM( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address liquidator, address trader ) public returns (int256 liquidatedAmount) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; require( !perpetual.isMaintenanceMarginSafe(trader, perpetual.getMarkPrice()), "trader is safe" ); int256 position = perpetual.getPosition(trader); // 0. price / amount (int256 deltaCash, int256 deltaPosition) = liquidityPool.queryTradeWithAMM( perpetualIndex, position, true ); require(deltaPosition != 0, "insufficient liquidity"); // 2. trade int256 liquidatePrice = deltaCash.wdiv(deltaPosition).abs(); perpetual.updateMargin(address(this), deltaPosition, deltaCash); perpetual.updateMargin( trader, deltaPosition.neg(), deltaCash.add(perpetual.keeperGasReward).neg() ); require(perpetual.openInterest >= 0, "negative open interest"); liquidityPool.transferFromPerpetualToUser( perpetual.id, liquidator, perpetual.keeperGasReward ); // 3. penalty min(markPrice * liquidationPenaltyRate, margin / position) * deltaPosition (int256 penalty, int256 penaltyToLiquidator) = postLiquidate( liquidityPool, perpetual, address(this), trader, position, deltaPosition.neg() ); emit Liquidate( perpetualIndex, address(this), trader, deltaPosition.neg(), liquidatePrice, penalty, penaltyToLiquidator ); liquidatedAmount = deltaPosition.neg(); } /** * @dev See `liquidateByTrader` in Perpetual.sol for details. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param liquidator The address of the account calling the liquidation method. * @param trader The address of the liquidated account. * @param amount The amount of position to be taken from liquidated trader. * @param limitPrice The worst price liquidator accepts. * @return liquidatedAmount The amount of positions actually liquidated in the transaction. */ function liquidateByTrader( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address liquidator, address trader, int256 amount, int256 limitPrice ) public returns (int256 liquidatedAmount) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; int256 markPrice = perpetual.getMarkPrice(); require(!perpetual.isMaintenanceMarginSafe(trader, markPrice), "trader is safe"); // 0. price / amount validatePrice(amount >= 0, markPrice, limitPrice); int256 position = perpetual.getPosition(trader); int256 deltaPosition = getMaxPositionToClose(position, amount.neg()).neg(); int256 deltaCash = markPrice.wmul(deltaPosition).neg(); // 1. execute perpetual.updateMargin(liquidator, deltaPosition, deltaCash); perpetual.updateMargin(trader, deltaPosition.neg(), deltaCash.neg()); require(perpetual.openInterest >= 0, "negative open interest"); // 2. penalty min(markPrice * liquidationPenaltyRate, margin / position) * deltaPosition (int256 penalty, ) = postLiquidate( liquidityPool, perpetual, liquidator, trader, position, deltaPosition.neg() ); liquidatedAmount = deltaPosition.neg(); require( liquidityPool.isTraderMarginSafe(perpetualIndex, liquidator, liquidatedAmount), "liquidator margin unsafe" ); emit Liquidate(perpetualIndex, liquidator, trader, liquidatedAmount, markPrice, penalty, 0); } /** * @dev Handle liquidate penalty / fee. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetual The reference of perpetual storage. * @param liquidator The address of the account calling the liquidation method. * @param trader The address of the liquidated account. * @param position The amount of position owned by trader before liquidation. * @param deltaPosition The amount of position to be taken from liquidated trader. * @return penalty The amount of positions actually liquidated in the transaction. * @return penaltyToLiquidator The amount of positions actually liquidated in the transaction. */ function postLiquidate( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, address liquidator, address trader, int256 position, int256 deltaPosition ) public returns (int256 penalty, int256 penaltyToLiquidator) { int256 vaultFee = 0; { int256 markPrice = perpetual.getMarkPrice(); int256 remainingMargin = perpetual.getMargin(trader, markPrice); int256 liquidationValue = markPrice.wmul(deltaPosition).abs(); penalty = liquidationValue.wmul(perpetual.liquidationPenaltyRate).min( remainingMargin.wfrac(deltaPosition.abs(), position.abs()) ); remainingMargin = remainingMargin.sub(penalty); if (remainingMargin > 0) { vaultFee = liquidationValue.wmul(liquidityPool.getVaultFeeRate()).min( remainingMargin ); liquidityPool.transferFromPerpetualToUser( perpetual.id, liquidityPool.getVault(), vaultFee ); } } int256 penaltyToFund; bool isEmergency; if (penalty > 0) { penaltyToFund = penalty.wmul(perpetual.insuranceFundRate); penaltyToLiquidator = penalty.sub(penaltyToFund); } else { int256 totalInsuranceFund = liquidityPool.insuranceFund.add( liquidityPool.donatedInsuranceFund ); if (totalInsuranceFund.add(penalty) < 0) { // ensure donatedInsuranceFund >= 0 penalty = totalInsuranceFund.neg(); isEmergency = true; } penaltyToFund = penalty; penaltyToLiquidator = 0; } int256 penaltyToLP = liquidityPool.updateInsuranceFund(penaltyToFund); perpetual.updateCash(address(this), penaltyToLP); perpetual.updateCash(liquidator, penaltyToLiquidator); perpetual.updateCash(trader, penalty.add(vaultFee).neg()); if (penaltyToFund >= 0) { perpetual.decreaseTotalCollateral(penaltyToFund.sub(penaltyToLP)); } else { // penaltyToLP = 0 when penaltyToFund < 0 perpetual.increaseTotalCollateral(penaltyToFund.neg()); } if (isEmergency) { liquidityPool.setEmergencyState(perpetual.id); } } /** * @dev Get the max position amount of trader will be closed in the trade. * @param position Current position of trader. * @param amount The trading amount of position. * @return maxPositionToClose The max position amount of trader will be closed in the trade. */ function getMaxPositionToClose(int256 position, int256 amount) internal pure returns (int256 maxPositionToClose) { require(position != 0, "trader has no position to close"); require(!Utils.hasTheSameSign(position, amount), "trader must be close only"); maxPositionToClose = amount.abs() > position.abs() ? position.neg() : amount; } /** * @dev Check if the price is better than the limit price. * @param isLong True if the side is long. * @param price The price to be validate. * @param priceLimit The limit price. */ function validatePrice( bool isLong, int256 price, int256 priceLimit ) internal pure { require(price > 0, "price must be positive"); bool isPriceSatisfied = isLong ? price <= priceLimit : price >= priceLimit; require(isPriceSatisfied, "price exceeds limit"); } /** * @dev A readonly version of trade * * This function was written post-audit. So there's a lot of repeated logic here. * NOTE: max openInterest is NOT exact the same as trade(). In this function, poolMargin * will be smaller, so that the openInterst limit is also smaller (more strict). * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param trader The address of trader. * @param amount The amount of position to trader, positive for buying and negative for selling. * @param flags The flags of the trade, contains extra config for trading. * @return tradePrice The average fill price. * @return totalFee The total fee collected from the trader after the trade. * @return cost Deposit or withdraw to let effective leverage == targetLeverage if flags contain USE_TARGET_LEVERAGE. > 0 if deposit, < 0 if withdraw. */ function queryTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount, address referrer, uint32 flags ) public returns ( int256 tradePrice, int256 totalFee, int256 cost ) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; MarginAccount memory account = perpetual.marginAccounts[trader]; // clone (int256 deltaCash, int256 deltaPosition) = preTrade( liquidityPool, perpetualIndex, trader, amount, amount > 0 ? type(int256).max : 0, flags ); tradePrice = deltaCash.wdiv(deltaPosition).abs(); readonlyDoTrade(liquidityPool, perpetual, account, deltaCash, deltaPosition); (totalFee, cost) = readonlyPostTrade( liquidityPool, perpetual, account, referrer, deltaCash, deltaPosition, flags ); } // A readonly version of doTrade. This function was written post-audit. So there's a lot of repeated logic here. // NOTE: max openInterest is NOT exact the same as trade(). In this function, poolMargin // will be smaller, so that the openInterst limit is also smaller (more strict). function readonlyDoTrade( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, MarginAccount memory account, int256 deltaCash, int256 deltaPosition ) internal view { int256 deltaOpenInterest1; int256 deltaOpenInterest2; (, , deltaOpenInterest1) = readonlyUpdateMargin( perpetual, perpetual.marginAccounts[address(this)].cash, perpetual.marginAccounts[address(this)].position, deltaPosition, deltaCash ); (account.cash, account.position, deltaOpenInterest2) = readonlyUpdateMargin( perpetual, account.cash, account.position, deltaPosition.neg(), deltaCash.neg() ); int256 perpetualOpenInterest = perpetual.openInterest.add(deltaOpenInterest1).add( deltaOpenInterest2 ); require(perpetualOpenInterest >= 0, "negative open interest"); if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) { // open interest will increase, check limit (int256 poolMargin, ) = liquidityPool.getPoolMargin(); // NOTE: this is a slight different from trade() require( perpetualOpenInterest <= perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()), "open interest exceeds limit" ); } } // A readonly version of postTrade. This function was written post-audit. So there's a lot of repeated logic here. function readonlyPostTrade( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, MarginAccount memory account, address referrer, int256 deltaCash, int256 deltaPosition, uint32 flags ) internal view returns (int256 totalFee, int256 adjustCollateral) { // fees int256 lpFee; int256 operatorFee; int256 vaultFee; int256 referralRebate; { bool hasOpened = Utils.hasOpenedPosition(account.position, deltaPosition.neg()); (lpFee, operatorFee, vaultFee, referralRebate) = readonlyGetFees( liquidityPool, perpetual, account, referrer, deltaCash.abs(), hasOpened ); } totalFee = lpFee.add(operatorFee).add(vaultFee).add(referralRebate); // was updateCash account.cash = account.cash.add(totalFee.neg()); // trader deposit/withdraw if (flags.useTargetLeverage()) { adjustCollateral = LiquidityPoolModule.readonlyAdjustMarginLeverage( perpetual, account, deltaPosition.neg(), deltaCash.neg(), totalFee ); } account.cash = account.cash.add(adjustCollateral); } // A readonly version of MarginAccountModule.updateMargin. This function was written post-audit. So there's a lot of repeated logic here. function readonlyUpdateMargin( PerpetualStorage storage perpetual, int256 oldCash, int256 oldPosition, int256 deltaPosition, int256 deltaCash ) internal view returns ( int256 newCash, int256 newPosition, int256 deltaOpenInterest ) { newPosition = oldPosition.add(deltaPosition); newCash = oldCash.add(deltaCash).add(perpetual.unitAccumulativeFunding.wmul(deltaPosition)); if (oldPosition > 0) { deltaOpenInterest = oldPosition.neg(); } if (newPosition > 0) { deltaOpenInterest = deltaOpenInterest.add(newPosition); } } // A readonly version of getFees. This function was written post-audit. So there's a lot of repeated logic here. function readonlyGetFees( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, MarginAccount memory trader, address referrer, int256 tradeValue, bool hasOpened ) public view returns ( int256 lpFee, int256 operatorFee, int256 vaultFee, int256 referralRebate ) { require(tradeValue >= 0, "trade value is negative"); vaultFee = tradeValue.wmul(liquidityPool.getVaultFeeRate()); lpFee = tradeValue.wmul(perpetual.lpFeeRate); if (liquidityPool.getOperator() != address(0)) { operatorFee = tradeValue.wmul(perpetual.operatorFeeRate); } int256 totalFee = lpFee.add(operatorFee).add(vaultFee); int256 availableMargin = LiquidityPoolModule.readonlyGetAvailableMargin( perpetual, trader, perpetual.getMarkPrice() ); if (!hasOpened) { if (availableMargin <= 0) { lpFee = 0; operatorFee = 0; vaultFee = 0; referralRebate = 0; } else if (totalFee > availableMargin) { // make sure the sum of fees < available margin int256 rate = availableMargin.wdiv(totalFee, Round.FLOOR); operatorFee = operatorFee.wmul(rate, Round.FLOOR); vaultFee = vaultFee.wmul(rate, Round.FLOOR); lpFee = availableMargin.sub(operatorFee).sub(vaultFee); } } if ( referrer != address(0) && perpetual.referralRebateRate > 0 && lpFee.add(operatorFee) > 0 ) { int256 lpFeeRebate = lpFee.wmul(perpetual.referralRebateRate); int256 operatorFeeRabate = operatorFee.wmul(perpetual.referralRebateRate); referralRebate = lpFeeRebate.add(operatorFeeRabate); lpFee = lpFee.sub(lpFeeRebate); operatorFee = operatorFee.sub(operatorFeeRabate); } } }
open interest will increase, check limit
function doTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 deltaCash, int256 deltaPosition ) internal { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; int256 deltaOpenInterest1 = perpetual.updateMargin(address(this), deltaPosition, deltaCash); int256 deltaOpenInterest2 = perpetual.updateMargin( trader, deltaPosition.neg(), deltaCash.neg() ); require(perpetual.openInterest >= 0, "negative open interest"); if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) { (int256 poolMargin, ) = liquidityPool.getPoolMargin(); require( perpetual.openInterest <= perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()), "open interest exceeds limit" ); } }
12,615,773
./full_match/3/0xD6c9DfFd4b84E23347491E340060808f815F8B0c/sources/contracts/10_Deposit.sol
Create a reference to the underlying asset contract, like DAI. Create a reference to the corresponding cToken contract, like cDAI Amount of current exchange rate from cToken to underlying Amount added to you supply balance this block Approve transfer on the ERC20 contract Mint cTokens
function supplyErc20ToCompound( address token, address c_token, uint256 amount ) private returns (uint) { IERC20 underlying = IERC20(token); CERC20 cToken = CERC20(c_token); uint256 exchangeRateMantissa = cToken.exchangeRateCurrent(); emit MyLog("Exchange Rate (scaled up): ", exchangeRateMantissa); uint256 supplyRateMantissa = cToken.supplyRatePerBlock(); emit MyLog("Supply Rate: (scaled up)", supplyRateMantissa); underlying.approve(c_token, amount); uint mintResult = cToken.mint(amount); balances[msg.sender][token] = balances[msg.sender][token].sub(amount); c_balances[msg.sender][token] = c_balances[msg.sender][token].add(mintResult); return mintResult; }
8,122,634
pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title Token Staking. * @dev Stake ERC20 for earning rewards. */ import { TokenInterface } from "../../common/interfaces.sol"; import { Stores } from "../../common/stores.sol"; import { Helpers } from "./helpers.sol"; import { Events } from "./events.sol"; import { IStakingRewards, StakingERC20Mapping } from "./interface.sol"; contract Main is Helpers, Events { /** * @dev Deposit ERC20. * @notice Deposit Tokens to staking pool. * @param stakingPoolName staking pool name. * @param amt staking token amount. * @param getId ID to retrieve amount. * @param setId ID stores the amount of staked tokens. */ function deposit( string calldata stakingPoolName, uint amt, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); ( IStakingRewards stakingContract, TokenInterface stakingToken, , bytes32 stakingType ) = getStakingData(stakingPoolName); _amt = _amt == uint(-1) ? stakingToken.balanceOf(address(this)) : _amt; stakingToken.approve(address(stakingContract), _amt); stakingContract.stake(_amt); setUint(setId, _amt); _eventName = "LogDeposit(address,bytes32,uint256,uint256,uint256)"; _eventParam = abi.encode(address(stakingToken), stakingType, _amt, getId, setId); } /** * @dev Withdraw ERC20. * @notice Withdraw Tokens from the staking pool. * @param stakingPoolName staking pool name. * @param amt staking token amount. * @param getId ID to retrieve amount. * @param setIdAmount ID stores the amount of stake tokens withdrawn. * @param setIdReward ID stores the amount of reward tokens claimed. */ function withdraw( string calldata stakingPoolName, uint amt, uint getId, uint setIdAmount, uint setIdReward ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amt = getUint(getId, amt); ( IStakingRewards stakingContract, TokenInterface stakingToken, TokenInterface rewardToken, bytes32 stakingType ) = getStakingData(stakingPoolName); _amt = _amt == uint(-1) ? stakingContract.balanceOf(address(this)) : _amt; uint intialBal = rewardToken.balanceOf(address(this)); stakingContract.withdraw(_amt); stakingContract.getReward(); uint rewardAmt = sub(rewardToken.balanceOf(address(this)), intialBal); setUint(setIdAmount, _amt); setUint(setIdReward, rewardAmt); { _eventName = "LogWithdrawAndClaimedReward(address,bytes32,uint256,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(address(stakingToken), stakingType, _amt, rewardAmt, getId, setIdAmount, setIdReward); } } /** * @dev Claim Reward. * @notice Claim Pending Rewards of tokens staked. * @param stakingPoolName staking pool name. * @param setId ID stores the amount of reward tokens claimed. */ function claimReward( string calldata stakingPoolName, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { ( IStakingRewards stakingContract, , TokenInterface rewardToken, bytes32 stakingType ) = getStakingData(stakingPoolName); uint intialBal = rewardToken.balanceOf(address(this)); stakingContract.getReward(); uint finalBal = rewardToken.balanceOf(address(this)); uint rewardAmt = sub(finalBal, intialBal); setUint(setId, rewardAmt); _eventName = "LogClaimedReward(address,bytes32,uint256,uint256)"; _eventParam = abi.encode(address(rewardToken), stakingType, rewardAmt, setId); } } contract connectV2StakeERC20 is Main { string public constant name = "Stake-ERC20-v1.0"; } pragma solidity ^0.7.0; interface TokenInterface { function approve(address, uint256) external; function transfer(address, uint) external; function transferFrom(address, address, uint) external; function deposit() external payable; function withdraw(uint) external; function balanceOf(address) external view returns (uint); function decimals() external view returns (uint); } interface MemoryInterface { function getUint(uint id) external returns (uint num); function setUint(uint id, uint val) external; } interface InstaMapping { function cTokenMapping(address) external view returns (address); function gemJoinMapping(bytes32) external view returns (address); } interface AccountInterface { function enable(address) external; function disable(address) external; function isAuth(address) external view returns (bool); } pragma solidity ^0.7.0; import { MemoryInterface, InstaMapping } from "./interfaces.sol"; abstract contract Stores { /** * @dev Return ethereum address */ address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev Return Wrapped ETH address */ address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @dev Return memory variable address */ MemoryInterface constant internal instaMemory = MemoryInterface(0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F); /** * @dev Return InstaDApp Mapping Addresses */ InstaMapping constant internal instaMapping = InstaMapping(0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88); /** * @dev Get Uint value from InstaMemory Contract. */ function getUint(uint getId, uint val) internal returns (uint returnVal) { returnVal = getId == 0 ? val : instaMemory.getUint(getId); } /** * @dev Set Uint value in InstaMemory Contract. */ function setUint(uint setId, uint val) virtual internal { if (setId != 0) instaMemory.setUint(setId, val); } } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import { DSMath } from "../../common/math.sol"; import { Basic } from "../../common/basic.sol"; import { TokenInterface } from "../../common/interfaces.sol"; import { IStakingRewards, StakingERC20Mapping } from "./interface.sol"; abstract contract Helpers is DSMath, Basic { /** * @dev Convert String to bytes32. */ function stringToBytes32(string memory str) internal pure returns (bytes32 result) { require(bytes(str).length != 0, "string-empty"); // solium-disable-next-line security/no-inline-assembly assembly { result := mload(add(str, 32)) } } /** * @dev Get staking data */ function getStakingData(string memory stakingName) internal view returns ( IStakingRewards stakingContract, TokenInterface stakingToken, TokenInterface rewardToken, bytes32 stakingType ) { stakingType = stringToBytes32(stakingName); StakingERC20Mapping.StakingData memory stakingData = StakingERC20Mapping(getMappingAddr()).stakingMapping(stakingType); require(stakingData.stakingPool != address(0) && stakingData.stakingToken != address(0), "Wrong Staking Name"); stakingContract = IStakingRewards(stakingData.stakingPool); stakingToken = TokenInterface(stakingData.stakingToken); rewardToken = TokenInterface(stakingData.rewardToken); } function getMappingAddr() internal virtual view returns (address) { return 0xbE658233bA9990d86155b3902fd05a7AfC7eBdB5; // InstaMapping Address } } pragma solidity ^0.7.0; contract Events { event LogDeposit( address indexed stakingToken, bytes32 indexed stakingType, uint256 amount, uint getId, uint setId ); event LogWithdrawAndClaimedReward( address indexed stakingToken, bytes32 indexed stakingType, uint256 amount, uint256 rewardAmt, uint getId, uint setIdAmount, uint setIdReward ); event LogClaimedReward( address indexed rewardToken, bytes32 indexed stakingType, uint256 rewardAmt, uint setId ); } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; interface IStakingRewards { function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function balanceOf(address) external view returns(uint); } interface StakingERC20Mapping { struct StakingData { address stakingPool; address stakingToken; address rewardToken; } function stakingMapping(bytes32) external view returns(StakingData memory); } pragma solidity ^0.7.0; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; contract DSMath { uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function add(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(x, y); } function sub(uint x, uint y) internal virtual pure returns (uint z) { z = SafeMath.sub(x, y); } function mul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.mul(x, y); } function div(uint x, uint y) internal pure returns (uint z) { z = SafeMath.div(x, y); } function wmul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y; } function rmul(uint x, uint y) internal pure returns (uint z) { z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY; } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } } pragma solidity ^0.7.0; import { TokenInterface } from "./interfaces.sol"; import { Stores } from "./stores.sol"; import { DSMath } from "./math.sol"; abstract contract Basic is DSMath, Stores { function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = (_amt / 10 ** (18 - _dec)); } function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { amt = mul(_amt, 10 ** (18 - _dec)); } function getTokenBal(TokenInterface token) internal view returns(uint _amt) { _amt = address(token) == ethAddr ? address(this).balance : token.balanceOf(address(this)); } function getTokensDec(TokenInterface buyAddr, TokenInterface sellAddr) internal view returns(uint buyDec, uint sellDec) { buyDec = address(buyAddr) == ethAddr ? 18 : buyAddr.decimals(); sellDec = address(sellAddr) == ethAddr ? 18 : sellAddr.decimals(); } function encodeEvent(string memory eventName, bytes memory eventParam) internal pure returns (bytes memory) { return abi.encode(eventName, eventParam); } function changeEthAddress(address buy, address sell) internal pure returns(TokenInterface _buy, TokenInterface _sell){ _buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy); _sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell); } function convertEthToWeth(bool isEth, TokenInterface token, uint amount) internal { if(isEth) token.deposit{value: amount}(); } function convertWethToEth(bool isEth, TokenInterface token, uint amount) internal { if(isEth) { token.approve(address(token), amount); token.withdraw(amount); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Claim Reward. Claim Pending Rewards of tokens staked. stakingPoolName staking pool name. setId ID stores the amount of reward tokens claimed./
function claimReward( string calldata stakingPoolName, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { ( IStakingRewards stakingContract, , TokenInterface rewardToken, bytes32 stakingType ) = getStakingData(stakingPoolName); uint intialBal = rewardToken.balanceOf(address(this)); stakingContract.getReward(); uint finalBal = rewardToken.balanceOf(address(this)); uint rewardAmt = sub(finalBal, intialBal); setUint(setId, rewardAmt); _eventName = "LogClaimedReward(address,bytes32,uint256,uint256)"; _eventParam = abi.encode(address(rewardToken), stakingType, rewardAmt, setId); }
5,775,446
pragma solidity ^0.4.16; contract TokenERC20 { /* Begin Owned Contract Members */ // An array of owners mapping (address => bool) public owners; // Has the next action been authorised by another owner bool public nextActionIsAuthorised = false; address public actionAuthorisedBy; // Does an owner-only action have to be authorised by another owner bool public requireAuthorisation = true; function isOwner(address addressToCheck) view public returns (bool) { return owners[addressToCheck]; } modifier onlyOwners { require(isOwner(msg.sender)); if (requireAuthorisation) { checkActionIsAuthorisedAndReset(); } _; } function authoriseNextAction() public { require(isOwner(msg.sender)); require(requireAuthorisation); require(!nextActionIsAuthorised); nextActionIsAuthorised = true; actionAuthorisedBy = msg.sender; } function checkActionIsAuthorisedAndReset() public { require(isOwner(msg.sender)); bool isValidAuthorisationRequest = (nextActionIsAuthorised && actionAuthorisedBy != msg.sender); require(isValidAuthorisationRequest); nextActionIsAuthorised = false; } function setRequireAuthorisation(bool _requireAuthorisation) onlyOwners public { requireAuthorisation = _requireAuthorisation; } /* End Owned Contract Members */ // Public variables of the token bool public tokenInitialised = false; string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; uint256 public sellPrice; address public currentSeller; // Are users currently allowed to... bool public allowTransfers = false; // transfer their tokens bool public allowBurns = false; // burn their tokens bool public allowBuying = false; // buy tokens // This creates an array with... mapping (address => uint256) public balanceOf; // all balances mapping (address => uint256) public etherSpent; // how much an addeess has spent mapping (address => bool) public frozenAccounts; // frozen accounts address[] investors; uint64 public investorCount; /*** Begin ICO Variables ***/ // Unit lenghts for week, month and year uint256 constant public weekLength = 60 * 60 * 24 * 7; uint256 constant public monthLength = 2627856; // (60 * 60 * 24 * 30.415) As to not have to re-adjust for different month lengths uint256 constant public yearLength = 60 * 60 * 24 * 7 * 52; uint256 public icoBeginDate; uint256 public icoEndDate; bool public icoParametersSet = false; uint256 public tokensSoldAtIco = 0; uint256 public minimumTokenThreshold; bool public etherHasBeenReturnedToInvestors = false; uint256 public softCap; uint256 public runTimeAfterSoftCapReached; uint256 public dateSoftCapWasReached = 0; uint256 public maxFundsThatCanBeWithdrawnByOwners = 0; uint256 public fundsWithdrawnByOwners = 0; uint8 immediateAllowancePercentage; uint8 firstYearAllowancePercentage; uint8 secondYearAllowancePercentage; mapping (uint8 => uint8) public weekBonuses; // Bonus of 20% is stored as 120, 10% as 110 etc. modifier onlyWhenIcoParametersAreSet { require(icoParametersSet); _; } modifier onlyWhenIcoParametersAreNotSet { require(!icoParametersSet); _; } modifier onlyDuringIco { require(icoParametersSet); updateContract(); require(isIcoRunning()); _; } /*** End ICO Variables ***/ /*** Begin ICO Setters ***/ function setIcoParametersSet(bool set) onlyWhenIcoParametersAreNotSet onlyOwners public { icoParametersSet = set; } function setIcoBeginDate(uint256 beginDate) onlyWhenIcoParametersAreNotSet onlyOwners public { icoBeginDate = beginDate; } function setIcoEndDate (uint256 endDate) onlyWhenIcoParametersAreNotSet onlyOwners public { icoEndDate = endDate; } function setSoftCap (uint256 cap) onlyWhenIcoParametersAreNotSet onlyOwners public { softCap = cap; } function setRunTimeAfterSoftCapReached (uint256 runTime) onlyWhenIcoParametersAreNotSet onlyOwners public { runTimeAfterSoftCapReached = runTime; } function setImmediateAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public { immediateAllowancePercentage = allowancePercentage; } function setFirstYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public { firstYearAllowancePercentage = allowancePercentage; } function setSecondYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public { secondYearAllowancePercentage = allowancePercentage; } function initialiseToken() public { require(!tokenInitialised); name = "BaraToken"; symbol = "BRT"; totalSupply = 160000000 * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; currentSeller = msg.sender; owners[msg.sender] = true; owners[0x1434e028b12D196AcBE5304A94d0a5F816eb5d55] = true; tokenInitialised = true; } function() payable public { buyTokens(); } function updateContract() onlyWhenIcoParametersAreSet public { if (hasSoftCapBeenReached() && dateSoftCapWasReached == 0) { dateSoftCapWasReached = now; bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached > icoEndDate); if (!reachingSoftCapWillExtendIco) icoEndDate = dateSoftCapWasReached + runTimeAfterSoftCapReached; } if (!isBeforeIco()) updateOwnersWithdrawAllowance(); } function isBeforeIco() onlyWhenIcoParametersAreSet internal view returns (bool) { return (now <= icoBeginDate); } function isIcoRunning() onlyWhenIcoParametersAreSet internal view returns (bool) { bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached) > icoEndDate; bool afterBeginDate = now > icoBeginDate; bool beforeEndDate = now < icoEndDate; if (hasSoftCapBeenReached() && !reachingSoftCapWillExtendIco) beforeEndDate = now < (dateSoftCapWasReached + runTimeAfterSoftCapReached); bool running = afterBeginDate && beforeEndDate; return running; } function isAfterIco() onlyWhenIcoParametersAreSet internal view returns (bool) { return (now > icoEndDate); } function hasSoftCapBeenReached() onlyWhenIcoParametersAreSet internal view returns (bool) { return (tokensSoldAtIco >= softCap && softCap != 0); } // In the first week of the ICO, there will be a bonus, say 20%, then the second week 10%, // of tokens. This retrieves that bonus. 20% is stored as 120, 10% as 110, etc. function getWeekBonus(uint256 amountPurchased) onlyWhenIcoParametersAreSet internal view returns (uint256) { uint256 weekBonus = uint256(weekBonuses[getWeeksPassedSinceStartOfIco()]); if (weekBonus != 0) return (amountPurchased * weekBonus) / 100; return amountPurchased; } function getTimeSinceEndOfIco() onlyWhenIcoParametersAreSet internal view returns (uint256) { require(now > icoEndDate); uint256 timeSinceEndOfIco = now - icoEndDate; return timeSinceEndOfIco; } function getWeeksPassedSinceStartOfIco() onlyWhenIcoParametersAreSet internal view returns (uint8) { require(!isBeforeIco()); uint256 timeSinceIco = now - icoBeginDate; uint8 weeksPassedSinceIco = uint8(timeSinceIco / weekLength); return weeksPassedSinceIco; } // Update how much the owners can withdraw based on how much time has passed // since the end of the ICO function updateOwnersWithdrawAllowance() onlyWhenIcoParametersAreSet internal { if (isAfterIco()) { uint256 totalFunds = this.balance; maxFundsThatCanBeWithdrawnByOwners = 0; uint256 immediateAllowance = (totalFunds * immediateAllowancePercentage) / 100; bool secondYear = now - icoEndDate >= yearLength; uint8 monthsPassedSinceIco = getMonthsPassedEndOfSinceIco(); if (secondYear) { uint256 monthsPassedInSecondYear = monthsPassedSinceIco - 12; // (monthsPassed / 12) * (allowancePercentage / 100) i.e. (monthsPassed * allowancePercentage / 1200) // all multiplied by the totalFunds available to be withdrwan // They're multiplied in one line to ensure not losing any information since we don't have floats // The minimum a person can buy is 1/10^12 tokens and we have 18 decimals, meaning always at least // 6 decimals to hold information done in multiplication/division uint256 secondYearAllowance = ((totalFunds * secondYearAllowancePercentage * monthsPassedInSecondYear) / 1200); } uint8 monthsPassedInFirstYear = monthsPassedSinceIco; if (secondYear) monthsPassedInFirstYear = 12; uint256 firstYearAllowance = ((totalFunds * firstYearAllowancePercentage * monthsPassedInFirstYear) / 1200); maxFundsThatCanBeWithdrawnByOwners = immediateAllowance + firstYearAllowance + secondYearAllowance; } } function getMonthsPassedEndOfSinceIco() onlyWhenIcoParametersAreSet internal view returns (uint8) { uint256 timePassedSinceIco = now - icoEndDate; uint8 monthsPassedSinceIco = uint8(timePassedSinceIco / weekLength); return monthsPassedSinceIco + 1; } // Check if the amount the owners are attempting to withdraw is within their current allowance function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) { if (now - icoEndDate >= yearLength * 2) return true; uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw; bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners; return withinAllowance; } function buyTokens() onlyDuringIco payable public { require(allowBuying); require(!frozenAccounts[msg.sender]); require(msg.value > 0); uint256 numberOfTokensPurchased = msg.value / sellPrice; require(numberOfTokensPurchased >= 10 ** 6); numberOfTokensPurchased = getWeekBonus(numberOfTokensPurchased); _transfer(currentSeller, msg.sender, numberOfTokensPurchased); tokensSoldAtIco += numberOfTokensPurchased; if (!(etherSpent[msg.sender] > 0)) { investors[investorCount] = msg.sender; investorCount++; } etherSpent[msg.sender] += msg.value; } /* These generate a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event FrozenFunds(address target, bool frozen); event NewSellPrice(uint256 _sellPrice); function setTokenName(string tokenName) onlyOwners public { name = tokenName; } function setTokenSymbol(string tokenSymbol) onlyOwners public { symbol = tokenSymbol; } function setAllowTransfers(bool allow) onlyOwners public { allowTransfers = allow; } function setAllowBurns(bool allow) onlyOwners public { allowBurns = allow; } function setAllowBuying(bool allow) onlyOwners public { allowBuying = allow; } function setSellPrice(uint256 _sellPrice) onlyOwners public { sellPrice = _sellPrice; NewSellPrice(_sellPrice); } function setCurrentSeller(address newSeller) onlyOwners public { currentSeller = newSeller; } function ownersTransfer(address _to, uint256 _amount) onlyOwners public { _transfer(msg.sender, _to, _amount); } function transfer(address _to, uint256 _value) public { require(allowTransfers && !isOwner(msg.sender)); _transfer(msg.sender, _to, _value); } function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value > balanceOf[_to]); require(!frozenAccounts[_from]); require(!frozenAccounts[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyOwners public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } function burn(uint256 amount) public { require(allowBurns && !isOwner(msg.sender)); require(balanceOf[msg.sender] >= amount); balanceOf[msg.sender] -= amount; totalSupply -= amount; Burn(msg.sender, amount); } function burnFrom(address from, uint256 amount) onlyOwners public { require (balanceOf[from] >= amount); balanceOf[from] -= amount; totalSupply -= amount; Burn(from, amount); } function freezeAccount(address target, bool freeze) onlyOwners public { frozenAccounts[target] = freeze; FrozenFunds(target, freeze); } function addOwner(address owner) onlyOwners public { owners[owner] = true; } function removeOwner(address owner) onlyOwners public { owners[owner] = false; } function sendContractFundsToAddress(uint256 amount, address recipient) onlyOwners public { require(icoParametersSet); require(isAfterIco()); require(tokensSoldAtIco >= minimumTokenThreshold); require(amount <= this.balance); updateContract(); require(amountIsWithinOwnersAllowance(amount)); recipient.transfer(amount); } function returnEtherToInvestors() onlyOwners onlyWhenIcoParametersAreSet public { require(isAfterIco()); require(!etherHasBeenReturnedToInvestors); require(tokensSoldAtIco < minimumTokenThreshold); for (uint64 investorNumber; investorNumber < investorCount; investorNumber++) { address investor = investors[investorNumber]; uint256 amountToSend = etherSpent[investor]; investor.transfer(amountToSend); } etherHasBeenReturnedToInvestors = true; } function getContractBalance() public view returns (uint256) { return this.balance; } }
Check if the amount the owners are attempting to withdraw is within their current allowance
function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) { if (now - icoEndDate >= yearLength * 2) return true; uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw; bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners; return withinAllowance; }
6,343,629
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "../../Math/SafeMath.sol"; import "../../XUS/XUS.sol"; import "../../XUSD/XUSD.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "./XUSDPoolLibrary.sol"; contract XUSDPool { using SafeMath for uint256; ERC20 private collateral_token; address private collateral_address; address private owner_address; address private xusd_contract_address; address private xus_contract_address; address private timelock_address; // Timelock address for the governance contract XUSDShares private XUS; XUSDStablecoin private XUSD; UniswapPairOracle private collatEthOracle; address private collat_eth_oracle_address; address private weth_address; mapping (address => uint256) public redeemXUSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolXUS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on XUS minted during recollateralizeXUSD(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl state variables bool private mintPaused = false; bool private redeemPaused = false; bool private recollateralizePaused = false; bool private buyBackPaused = false; bool private collateralPricePaused = false; address feepool_address; ChainlinkETHUSDPriceConsumer private collat_usd_pricer; uint8 private collat_usd_pricer_decimals; address public collat_usd_consumer_address; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner_address, "unauthorized"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "redeem paused"); _; } modifier notMintPaused() { require(mintPaused == false, "mint paused"); _; } modifier checkContract() { require(msg.sender == tx.origin, "contract not support"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _xusd_contract_address, address _xus_contract_address, address _collateral_address, address _timelock_address, uint256 _pool_ceiling ) public { XUSD = XUSDStablecoin(_xusd_contract_address); XUS = XUSDShares(_xus_contract_address); xusd_contract_address = _xusd_contract_address; xus_contract_address = _xus_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; owner_address = msg.sender; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); } function setCollatUSDOracle(address _collat_usd_consumer_address) public onlyByOwnerOrGovernance { collat_usd_consumer_address = _collat_usd_consumer_address; collat_usd_pricer = ChainlinkETHUSDPriceConsumer(collat_usd_consumer_address); collat_usd_pricer_decimals = collat_usd_pricer.getDecimals(); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this XUSD pool function collatDollarBalance() public view returns (uint256) { // uint256 eth_usd_price = XUSD.eth_usd_price(); // uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); // uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); uint256 collat_usd_price = uint256(collat_usd_pricer.getLatestPrice()).mul(1e6).div(uint256(10) ** collat_usd_pricer_decimals); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } // Returns the value of excess collateral held in this XUSD pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { ( , , uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value, , ,) = XUSD.xusd_info(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 XUSD with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true) { return pausedPrice; } else { // ( , , , , , , , uint256 eth_usd_price) = XUSD.xusd_info(); // return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); return uint256(collat_usd_pricer.getLatestPrice()).mul(1e6).div(uint256(10) ** collat_usd_pricer_decimals); //collat_usd_price } } function setFeePool(address _feepool) external onlyByOwnerOrGovernance { feepool_address = _feepool; } function getMint1t1Out(uint256 collat_amount) public view returns (uint256, uint256) { uint256 collateral_amount_d18 = collat_amount * (10 ** missing_decimals); ( , , , uint256 global_collateral_ratio, , uint256 minting_fee, ,) = XUSD.xusd_info(); require(global_collateral_ratio >= COLLATERAL_RATIO_MAX, "CR must >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collat_amount) <= pool_ceiling, "ceiling reached"); (uint256 xusd_amount_d18, uint256 fee) = XUSDPoolLibrary.calcMint1t1XUSD( getCollateralPrice(), minting_fee, collateral_amount_d18 ); return (xusd_amount_d18, fee); } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1XUSD(uint256 collateral_amount, uint256 XUSD_out_min) external notMintPaused { (uint256 xusd_amount_d18, uint256 fee) = getMint1t1Out(collateral_amount); require(XUSD_out_min <= xusd_amount_d18, "slippage"); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); XUSD.pool_mint(msg.sender, xusd_amount_d18); XUSD.pool_mint(feepool_address, fee); } function getMintAlgoOut(uint256 xus_amount) public view returns (uint256, uint256) { ( , uint256 xus_price, , uint256 global_collateral_ratio, , uint256 minting_fee, ,) = XUSD.xusd_info(); require(global_collateral_ratio == 0, "CR != 0"); (uint256 xusd_amount_d18, uint256 fee) = XUSDPoolLibrary.calcMintAlgorithmicXUSD( minting_fee, xus_price, // X XUS / 1 USD xus_amount ); return (xusd_amount_d18, fee); } // 0% collateral-backed function mintAlgorithmicXUSD(uint256 xus_amount_d18, uint256 XUSD_out_min) external notMintPaused { (uint256 xusd_amount_d18, uint256 fee) = getMintAlgoOut(xus_amount_d18); require(XUSD_out_min <= xusd_amount_d18, "slippage"); XUS.pool_burn_from(msg.sender, xus_amount_d18); XUSD.pool_mint(msg.sender, xusd_amount_d18); XUSD.pool_mint(feepool_address, fee); } function getMintFracOut(uint256 collat_amount) public view returns (uint256, uint256, uint256) { (, uint256 xus_price, , uint256 global_collateral_ratio, , uint256 minting_fee, ,) = XUSD.xusd_info(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "CR not in range"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collat_amount) <= pool_ceiling, "pool ceiling reached"); uint256 collateral_amount_d18 = collat_amount * (10 ** missing_decimals); (uint256 mint_amount, uint256 xus_needed, uint256 fee) = XUSDPoolLibrary.calcMintFractionalXUSD(collateral_amount_d18, getCollateralPrice(), xus_price, global_collateral_ratio, minting_fee); return (mint_amount, xus_needed, fee); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalXUSD(uint256 collateral_amount, uint256 XUSD_out_min) external notMintPaused { (uint256 mint_amount, uint256 xus_needed, uint256 fee) = getMintFracOut(collateral_amount); require(XUSD_out_min <= mint_amount, "slippage"); XUS.pool_burn_from(msg.sender, xus_needed); collateral_token.transferFrom(msg.sender, address(this), collateral_amount); XUSD.pool_mint(msg.sender, mint_amount); XUSD.pool_mint(feepool_address, fee); } function getRedeem1t1Out(uint256 xusd_amount) public view returns (uint256, uint256) { (, , , uint256 global_collateral_ratio, , , uint256 redemption_fee,) = XUSD.xusd_info(); require(global_collateral_ratio == COLLATERAL_RATIO_MAX, "CR != 1"); // Need to adjust for decimals of collateral uint256 XUSD_amount_precision = xusd_amount.div(10 ** missing_decimals); (uint256 collateral_needed, uint256 fee) = XUSDPoolLibrary.calcRedeem1t1XUSD( getCollateralPrice(), XUSD_amount_precision, redemption_fee ); return (collateral_needed, fee); } // Redeem collateral. 100% collateral-backed function redeem1t1XUSD(uint256 XUSD_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { (uint256 collateral_needed, uint256 fee) = getRedeem1t1Out(XUSD_amount); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; require(COLLATERAL_out_min <= collateral_needed, "slippage"); // Move all external functions to the end XUSD.pool_burn_from(msg.sender, XUSD_amount); XUSD.pool_mint(feepool_address, fee); } function getRedeemFracOut(uint256 XUSD_amount) public view returns (uint256, uint256, uint256) { (, uint256 xus_price, , uint256 global_collateral_ratio, , , uint256 redemption_fee,) = XUSD.xusd_info(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "CR not in range"); uint256 col_price_usd = getCollateralPrice(); uint256 fee = (XUSD_amount.mul(redemption_fee)).div(PRICE_PRECISION); uint256 XUSD_amount_post_fee = XUSD_amount.sub(fee); uint256 xus_dollar_value_d18 = XUSD_amount_post_fee.sub(XUSD_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 xus_amount = xus_dollar_value_d18.mul(PRICE_PRECISION).div(xus_price); // Need to adjust for decimals of collateral uint256 XUSD_amount_precision = XUSD_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = XUSD_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); return (xus_amount, collateral_amount, fee); } // Will fail if fully collateralized or algorithmic // Redeem XUSD for collateral and XUS. > 0% and < 100% collateral-backed function redeemFractionalXUSD(uint256 XUSD_amount, uint256 XUS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { (uint256 xus_amount, uint256 collateral_amount, uint256 fee) = getRedeemFracOut(XUSD_amount); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemXUSBalances[msg.sender] = redeemXUSBalances[msg.sender].add(xus_amount); unclaimedPoolXUS = unclaimedPoolXUS.add(xus_amount); lastRedeemed[msg.sender] = block.number; require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "not enough collateral"); require(COLLATERAL_out_min <= collateral_amount && XUS_out_min <= xus_amount, "slippage"); // Move all external functions to the end XUSD.pool_burn_from(msg.sender, XUSD_amount); XUS.pool_mint(address(this), xus_amount); XUSD.pool_mint(feepool_address, fee); } function getRedeemAlgoOut(uint256 XUSD_amount) public view returns (uint256, uint256) { (, uint256 xus_price, , uint256 global_collateral_ratio, , , uint256 redemption_fee,) = XUSD.xusd_info(); require(global_collateral_ratio == 0, "CR != 0"); uint256 fee = XUSD_amount.mul(redemption_fee).div(1e6); uint256 xus_dollar_value_d18 = XUSD_amount.sub(fee); uint256 xus_amount = xus_dollar_value_d18.mul(PRICE_PRECISION).div(xus_price); return (xus_amount, fee); } // Redeem XUSD for XUS. 0% collateral-backed function redeemAlgorithmicXUSD(uint256 XUSD_amount, uint256 XUS_out_min) external notRedeemPaused { (uint256 xus_amount, uint256 fee) = getRedeemAlgoOut(XUSD_amount); redeemXUSBalances[msg.sender] = redeemXUSBalances[msg.sender].add(xus_amount); unclaimedPoolXUS = unclaimedPoolXUS.add(xus_amount); lastRedeemed[msg.sender] = block.number; require(XUS_out_min <= xus_amount, "slippage"); // Move all external functions to the end XUSD.pool_burn_from(msg.sender, XUSD_amount); XUS.pool_mint(address(this), xus_amount); XUSD.pool_mint(feepool_address, fee); } // After a redemption happens, transfer the newly minted XUS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out XUSD/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "wait 1 block"); bool sendXUS = false; bool sendCollateral = false; uint XUSAmount; uint CollateralAmount; // Use Checks-Effects-Interactions pattern if(redeemXUSBalances[msg.sender] > 0){ XUSAmount = redeemXUSBalances[msg.sender]; redeemXUSBalances[msg.sender] = 0; unclaimedPoolXUS = unclaimedPoolXUS.sub(XUSAmount); sendXUS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendXUS == true){ XUS.transfer(msg.sender, XUSAmount); } if(sendCollateral == true){ collateral_token.transfer(msg.sender, CollateralAmount); } } function getRecollatOut(uint256 collateral_amount) public view returns (uint256, uint256) { require(recollateralizePaused == false, "recollat paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); ( , uint256 xus_price, uint256 xusd_total_supply , uint256 global_collateral_ratio, uint256 global_collat_value, , , ) = XUSD.xusd_info(); (uint256 collateral_units, uint256 amount_to_recollat) = XUSDPoolLibrary.calcRecollateralizeXUSDInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, xusd_total_supply, global_collateral_ratio ); uint256 xus_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate)).div(xus_price); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); return (collateral_units_precision, xus_paid_back); } // When the protocol is recollateralizing, we need to give a discount of XUS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get XUS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of XUS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra XUS value from the bonus rate as an arb opportunity function recollateralizeXUSD(uint256 collateral_amount, uint256 XUS_out_min) external { (uint256 collateral_units_precision, uint256 xus_paid_back) = getRecollatOut(collateral_amount); require(XUS_out_min <= xus_paid_back, "slippage"); collateral_token.transferFrom(msg.sender, address(this), collateral_units_precision); XUS.pool_mint(msg.sender, xus_paid_back); } function getBuybackOut(uint256 XUS_amount) public view returns (uint256) { require(buyBackPaused == false, "buyback paused"); (, uint256 xus_price, , , , , ,) = XUSD.xusd_info(); (uint256 collateral_equivalent_d18) = XUSDPoolLibrary.calcBuyBackXUS(XUS_amount, xus_price, availableExcessCollatDV(), getCollateralPrice()); return collateral_equivalent_d18.div(10 ** missing_decimals); } // Function can be called by an XUS holder to have the protocol buy back XUS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackXUS(uint256 XUS_amount, uint256 COLLATERAL_out_min) external { uint256 collateral_precision = getBuybackOut(XUS_amount); require(COLLATERAL_out_min <= collateral_precision, "slippage"); // Give the sender their desired collateral and burn the XUS XUS.pool_burn_from(msg.sender, XUS_amount); collateral_token.transfer(msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external onlyByOwnerOrGovernance { mintPaused = !mintPaused; } function toggleRedeeming() external onlyByOwnerOrGovernance { redeemPaused = !redeemPaused; } function toggleRecollateralize() external onlyByOwnerOrGovernance { recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external onlyByOwnerOrGovernance { buyBackPaused = !buyBackPaused; } function toggleCollateralPrice() external onlyByOwnerOrGovernance { // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = getCollateralPrice(); } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; } function setOwner(address _owner_address) external onlyByOwnerOrGovernance { owner_address = _owner_address; } }
Returns the price of the pool collateral in USD ( , , , , , , , uint256 eth_usd_price) = XUSD.xusd_info(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION (10 missing_decimals)));
function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true) { return pausedPrice; } }
6,416,057
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/storage/AccountRBAC.sol
Revokes all permissions for the specified target address. only removes permissions for the given address, not for the entire account/
function revokeAllPermissions(Data storage self, address target) internal { bytes32[] memory permissions = self.permissions[target].values(); if (permissions.length == 0) { return; } for (uint256 i = 0; i < permissions.length; i++) { self.permissions[target].remove(permissions[i]); } self.permissionAddresses.remove(target); }
16,517,166
pragma solidity ^0.4.25; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // 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 */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @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(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); 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 != 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 != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: openzeppelin-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 private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol /** * @title TokenRecover * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Allow to recover any ERC20 sent into the contract for error */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @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); } } // File: contracts/faucet/TokenFaucet.sol /** * @title TokenFaucet * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of a TokenFaucet */ contract TokenFaucet is TokenRecover { using SafeMath for uint256; // struct representing the faucet status for an account struct RecipientDetail { bool exists; uint256 tokens; uint256 lastUpdate; address referral; } // struct representing the referral status struct ReferralDetail { uint256 tokens; address[] recipients; } // the time between two tokens claim uint256 private _pauseTime = 1 days; // the token to distribute ERC20 private _token; // the daily rate of tokens distributed uint256 private _dailyRate; // the value earned by referral per mille uint256 private _referralPerMille; // the sum of distributed tokens uint256 private _totalDistributedTokens; // map of address and received token amount mapping (address => RecipientDetail) private _recipientList; // list of addresses who received tokens address[] private _recipients; // map of address and referred addresses mapping (address => ReferralDetail) private _referralList; /** * @param token Address of the token being distributed * @param dailyRate Daily rate of tokens distributed * @param referralPerMille The value earned by referral per mille */ constructor( address token, uint256 dailyRate, uint256 referralPerMille ) public { require(token != address(0)); require(dailyRate > 0); require(referralPerMille > 0); _token = ERC20(token); _dailyRate = dailyRate; _referralPerMille = referralPerMille; } /** * @dev fallback */ function () external payable { require(msg.value == 0); getTokens(); } /** * @dev function to be called to receive tokens */ function getTokens() public { // distribute tokens _distributeTokens(msg.sender, address(0)); } /** * @dev function to be called to receive tokens * @param referral Address to an account that is referring */ function getTokensWithReferral(address referral) public { require(referral != msg.sender); // distribute tokens _distributeTokens(msg.sender, referral); } /** * @return the token to distribute */ function token() public view returns (ERC20) { return _token; } /** * @return the daily rate of tokens distributed */ function dailyRate() public view returns (uint256) { return _dailyRate; } /** * @return the value earned by referral for each recipient */ function referralTokens() public view returns (uint256) { return _dailyRate.mul(_referralPerMille).div(1000); } /** * @return the sum of distributed tokens */ function totalDistributedTokens() public view returns (uint256) { return _totalDistributedTokens; } /** * @param account The address to check * @return received token amount for the given address */ function receivedTokens(address account) public view returns (uint256) { return _recipientList[account].tokens; } /** * @param account The address to check * @return last tokens received timestamp */ function lastUpdate(address account) public view returns (uint256) { return _recipientList[account].lastUpdate; } /** * @param account The address to check * @return time of next available claim or zero */ function nextClaimTime(address account) public view returns (uint256) { return !_recipientList[account].exists ? 0 : _recipientList[account].lastUpdate + _pauseTime; } /** * @param account The address to check * @return referral for given address */ function getReferral(address account) public view returns (address) { return _recipientList[account].referral; } /** * @param account The address to check * @return earned tokens by referrals */ function earnedByReferral(address account) public view returns (uint256) { return _referralList[account].tokens; } /** * @param account The address to check * @return referred addresses for given address */ function getReferredAddresses(address account) public view returns (address[]) { return _referralList[account].recipients; } /** * @param account The address to check * @return referred addresses for given address */ function getReferredAddressesLength(address account) public view returns (uint) { return _referralList[account].recipients.length; } /** * @dev return the number of remaining tokens to distribute * @return uint256 */ function remainingTokens() public view returns (uint256) { return _token.balanceOf(this); } /** * @return address of a recipient by list index */ function getRecipientAddress(uint256 index) public view returns (address) { return _recipients[index]; } /** * @dev return the recipients length * @return uint */ function getRecipientsLength() public view returns (uint) { return _recipients.length; } /** * @dev change daily rate and referral per mille * @param newDailyRate Daily rate of tokens distributed * @param newReferralPerMille The value earned by referral per mille */ function setRates(uint256 newDailyRate, uint256 newReferralPerMille) public onlyOwner { require(newDailyRate > 0); require(newReferralPerMille > 0); _dailyRate = newDailyRate; _referralPerMille = newReferralPerMille; } /** * @dev distribute tokens * @param account Address being distributing * @param referral Address to an account that is referring */ function _distributeTokens(address account, address referral) internal { require(nextClaimTime(account) <= block.timestamp); // solium-disable-line security/no-block-members // check if recipient exists if (!_recipientList[account].exists) { _recipients.push(account); _recipientList[account].exists = true; // check if valid referral if (referral != address(0)) { _recipientList[account].referral = referral; _referralList[referral].recipients.push(account); } } // update recipient status _recipientList[account].lastUpdate = block.timestamp; // solium-disable-line security/no-block-members _recipientList[account].tokens = _recipientList[account].tokens.add(_dailyRate); // update faucet status _totalDistributedTokens = _totalDistributedTokens.add(_dailyRate); // transfer tokens to recipient _token.transfer(account, _dailyRate); // check referral if (_recipientList[account].referral != address(0)) { // referral is only the first one referring address firstReferral = _recipientList[account].referral; uint256 referralEarnedTokens = referralTokens(); // update referral status _referralList[firstReferral].tokens = _referralList[firstReferral].tokens.add(referralEarnedTokens); // update faucet status _totalDistributedTokens = _totalDistributedTokens.add(referralEarnedTokens); // transfer tokens to referral _token.transfer(firstReferral, referralEarnedTokens); } } }
return the number of remaining tokens to distribute return uint256/
function remainingTokens() public view returns (uint256) { return _token.balanceOf(this); }
12,706,628
./full_match/1/0x2923A537546443AdcF47c7351b51Da6E423d3e58/sources/contracts/Marketplace.sol
Returns The Sale Info For A Fixed Price Sale/
function ViewSaleInfoFixedPrice ( uint SaleIndex, address Wallet, uint MaxAmount, bytes32[] calldata ProofEligibility, bytes32[] calldata ProofAmount ) public view returns (FixedPriceSaleInfo memory) { uint Price = FixedPriceSales[SaleIndex]._Price; uint AmountForSale = FixedPriceSales[SaleIndex]._AmountForSale; uint AmountRemaining = AmountForSale - AmountSoldFixedPrice[SaleIndex]; uint TimestampStart = FixedPriceSales[SaleIndex]._TimestampStart; uint ETHRevenue = ETHRevenueFixedPriceSale[SaleIndex]; uint AmountPurchasedUser = UserPurchasedAmount[SaleIndex][Wallet]; uint AmountRemainingMerklePriority; uint PurchasedAmountMerklePriority; bool BrightListMerkleAmount; uint[] memory DiscountAmountWEIValues = new uint[](FixedPriceSales[SaleIndex]._RootEligibilities.length); for(uint x; x < FixedPriceSales[SaleIndex]._RootEligibilities.length; x++) { DiscountAmountWEIValues[x] = (Price * DiscountAmounts[SaleIndex][x]) / 100; } (bool BrightListEligible, uint Priority) = VerifyBrightListWithPriority( SaleIndex, Wallet, ProofEligibility ); if(BrightListEligible) { BrightListMerkleAmount = VerifyBrightListAmount(Wallet, MaxAmount, FixedPriceSales[SaleIndex]._RootAmounts[Priority], ProofAmount); PurchasedAmountMerklePriority = PriorityPurchaseAmount[SaleIndex][Wallet][Priority]; if(MaxAmount > PurchasedAmountMerklePriority) { AmountRemainingMerklePriority = MaxAmount - PurchasedAmountMerklePriority; } } return FixedPriceSaleInfo( ETHRevenue, Price, AmountForSale, AmountRemaining, TimestampStart, Priority, AmountRemainingMerklePriority, AmountPurchasedUser, BrightListEligible, BrightListMerkleAmount, DiscountAmountWEIValues ); }
17,089,878
pragma solidity ^0.4.18; contract DataSourceInterface { function isDataSource() public pure returns (bool); function getGroupResult(uint matchId) external; function getRoundOfSixteenTeams(uint index) external; function getRoundOfSixteenResult(uint matchId) external; function getQuarterResult(uint matchId) external; function getSemiResult(uint matchId) external; function getFinalTeams() external; function getYellowCards() external; function getRedCards() external; } /** * @title DataLayer. * @author CryptoCup Team (https://cryptocup.io/about) */ contract DataLayer{ uint256 constant WCCTOKEN_CREATION_LIMIT = 5000000; uint256 constant STARTING_PRICE = 45 finney; /// Epoch times based on when the prices change. uint256 constant FIRST_PHASE = 1527476400; uint256 constant SECOND_PHASE = 1528081200; uint256 constant THIRD_PHASE = 1528686000; uint256 constant WORLD_CUP_START = 1528945200; DataSourceInterface public dataSource; address public dataSourceAddress; address public adminAddress; uint256 public deploymentTime = 0; uint256 public gameFinishedTime = 0; //set this to now when oraclize was called. uint32 public lastCalculatedToken = 0; uint256 public pointsLimit = 0; uint32 public lastCheckedToken = 0; uint32 public winnerCounter = 0; uint32 public lastAssigned = 0; uint256 public auxWorstPoints = 500000000; uint32 public payoutRange = 0; uint32 public lastPrizeGiven = 0; uint256 public prizePool = 0; uint256 public adminPool = 0; uint256 public finalizedTime = 0; enum teamState { None, ROS, QUARTERS, SEMIS, FINAL } enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished } /** * groups1 scores of the first half of matches (8 bits each) * groups2 scores of the second half of matches (8 bits each) * brackets winner&#39;s team ids of each round (5 bits each) * timeStamp creation timestamp * extra number of yellow and red cards (16 bits each) */ struct Token { uint192 groups1; uint192 groups2; uint160 brackets; uint64 timeStamp; uint32 extra; } struct GroupResult{ uint8 teamOneGoals; uint8 teamTwoGoals; } struct BracketPhase{ uint8[16] roundOfSixteenTeamsIds; mapping (uint8 => bool) teamExists; mapping (uint8 => teamState) middlePhaseTeamsIds; uint8[4] finalsTeamsIds; } struct Extras { uint16 yellowCards; uint16 redCards; } // List of all tokens Token[] tokens; GroupResult[48] groupsResults; BracketPhase bracketsResults; Extras extraResults; // List of all tokens that won uint256[] sortedWinners; // List of the worst tokens (they also win) uint256[] worstTokens; pointsValidationState public pValidationState = pointsValidationState.Unstarted; mapping (address => uint256[]) public tokensOfOwnerMap; mapping (uint256 => address) public ownerOfTokenMap; mapping (uint256 => address) public tokensApprovedMap; mapping (uint256 => uint256) public tokenToPayoutMap; mapping (uint256 => uint16) public tokenToPointsMap; event LogTokenBuilt(address creatorAddress, uint256 tokenId, Token token); event LogDataSourceCallbackList(uint8[] result); event LogDataSourceCallbackInt(uint8 result); event LogDataSourceCallbackTwoInt(uint8 result, uint8 result2); } ///Author Dieter Shirley (https://github.com/dete) contract ERC721 { event LogTransfer(address from, address to, uint256 tokenId); event LogApproval(address owner, address approved, uint256 tokenId); function name() public view returns (string); function symbol() public view returns (string); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); } /** * @title AccessControlLayer * @author CryptoCup Team (https://cryptocup.io/about) * @dev Containes basic admin modifiers to restrict access to some functions. Allows * for pauseing, and setting emergency stops. */ contract AccessControlLayer is DataLayer{ bool public paused = false; bool public finalized = false; bool public saleOpen = true; /** * @dev Main modifier to limit access to delicate functions. */ modifier onlyAdmin() { require(msg.sender == adminAddress); _; } /** * @dev Modifier that checks that the contract is not paused */ modifier isNotPaused() { require(!paused); _; } /** * @dev Modifier that checks that the contract is paused */ modifier isPaused() { require(paused); _; } /** * @dev Modifier that checks that the contract has finished successfully */ modifier hasFinished() { require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days))); _; } /** * @dev Modifier that checks that the contract has finalized */ modifier hasFinalized() { require(finalized); _; } /** * @dev Checks if pValidationState is in the provided stats * @param state State required to run */ modifier checkState(pointsValidationState state){ require(pValidationState == state); _; } /** * @dev Transfer contract&#39;s ownership * @param _newAdmin Address to be set */ function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); adminAddress = _newAdmin; } /** * @dev Sets the contract pause state * @param state True to pause */ function setPauseState(bool state) external onlyAdmin { paused = state; } /** * @dev Sets the contract to finalized * @param state True to finalize */ function setFinalized(bool state) external onlyAdmin { paused = state; finalized = state; if(finalized == true) finalizedTime = now; } } /** * @title CryptoCupToken, main implemantations of the ERC721 standard * @author CryptoCup Team (https://cryptocup.io/about) */ contract CryptocupToken is AccessControlLayer, ERC721 { //FUNCTIONALTIY /** * @notice checks if a user owns a token * @param userAddress - The address to check. * @param tokenId - ID of the token that needs to be verified. * @return true if the userAddress provided owns the token. */ function _userOwnsToken(address userAddress, uint256 tokenId) internal view returns (bool){ return ownerOfTokenMap[tokenId] == userAddress; } /** * @notice checks if the address provided is approved for a given token * @param userAddress * @param tokenId * @return true if it is aproved */ function _tokenIsApproved(address userAddress, uint256 tokenId) internal view returns (bool) { return tokensApprovedMap[tokenId] == userAddress; } /** * @notice transfers the token specified from sneder address to receiver address. * @param fromAddress the sender address that initially holds the token. * @param toAddress the receipient of the token. * @param tokenId ID of the token that will be sent. */ function _transfer(address fromAddress, address toAddress, uint256 tokenId) internal { require(tokensOfOwnerMap[toAddress].length < 100); require(pValidationState == pointsValidationState.Unstarted); tokensOfOwnerMap[toAddress].push(tokenId); ownerOfTokenMap[tokenId] = toAddress; uint256[] storage tokenArray = tokensOfOwnerMap[fromAddress]; for (uint256 i = 0; i < tokenArray.length; i++){ if(tokenArray[i] == tokenId){ tokenArray[i] = tokenArray[tokenArray.length-1]; } } delete tokenArray[tokenArray.length-1]; tokenArray.length--; delete tokensApprovedMap[tokenId]; } /** * @notice Approve the address for a given token * @param tokenId - ID of token to be approved * @param userAddress - Address that will be approved */ function _approve(uint256 tokenId, address userAddress) internal { tokensApprovedMap[tokenId] = userAddress; } /** * @notice set token owner to an address * @dev sets token owner on the contract data structures * @param ownerAddress address to be set * @param tokenId Id of token to be used */ function _setTokenOwner(address ownerAddress, uint256 tokenId) internal{ tokensOfOwnerMap[ownerAddress].push(tokenId); ownerOfTokenMap[tokenId] = ownerAddress; } //ERC721 INTERFACE function name() public view returns (string){ return "Cryptocup"; } function symbol() public view returns (string){ return "CC"; } function balanceOf(address userAddress) public view returns (uint256 count) { return tokensOfOwnerMap[userAddress].length; } function transfer(address toAddress,uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(toAddress != address(this)); require(_userOwnsToken(msg.sender, tokenId)); _transfer(msg.sender, toAddress, tokenId); LogTransfer(msg.sender, toAddress, tokenId); } function transferFrom(address fromAddress, address toAddress, uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(toAddress != address(this)); require(_tokenIsApproved(msg.sender, tokenId)); require(_userOwnsToken(fromAddress, tokenId)); _transfer(fromAddress, toAddress, tokenId); LogTransfer(fromAddress, toAddress, tokenId); } function approve( address toAddress, uint256 tokenId) external isNotPaused { require(toAddress != address(0)); require(_userOwnsToken(msg.sender, tokenId)); _approve(tokenId, toAddress); LogApproval(msg.sender, toAddress, tokenId); } function totalSupply() public view returns (uint) { return tokens.length; } function ownerOf(uint256 tokenId) external view returns (address ownerAddress) { ownerAddress = ownerOfTokenMap[tokenId]; require(ownerAddress != address(0)); } function tokensOfOwner(address ownerAddress) external view returns(uint256[] tokenIds) { tokenIds = tokensOfOwnerMap[ownerAddress]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title GameLogicLayer, contract in charge of everything related to calculating points, asigning * winners, and distributing prizes. * @author CryptoCup Team (https://cryptocup.io/about) */ contract GameLogicLayer is CryptocupToken{ using SafeMath for *; uint8 TEAM_RESULT_MASK_GROUPS = 15; uint160 RESULT_MASK_BRACKETS = 31; uint16 EXTRA_MASK_BRACKETS = 65535; uint16 private lastPosition; uint16 private superiorQuota; uint16[] private payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500]; uint32[] private payoutDistribution; event LogGroupDataArrived(uint matchId, uint8 result, uint8 result2); event LogRoundOfSixteenArrived(uint id, uint8 result); event LogMiddlePhaseArrived(uint matchId, uint8 result); event LogFinalsArrived(uint id, uint8[4] result); event LogExtrasArrived(uint id, uint16 result); //ORACLIZE function dataSourceGetGroupResult(uint matchId) external onlyAdmin{ dataSource.getGroupResult(matchId); } function dataSourceGetRoundOfSixteen(uint index) external onlyAdmin{ dataSource.getRoundOfSixteenTeams(index); } function dataSourceGetRoundOfSixteenResult(uint matchId) external onlyAdmin{ dataSource.getRoundOfSixteenResult(matchId); } function dataSourceGetQuarterResult(uint matchId) external onlyAdmin{ dataSource.getQuarterResult(matchId); } function dataSourceGetSemiResult(uint matchId) external onlyAdmin{ dataSource.getSemiResult(matchId); } function dataSourceGetFinals() external onlyAdmin{ dataSource.getFinalTeams(); } function dataSourceGetYellowCards() external onlyAdmin{ dataSource.getYellowCards(); } function dataSourceGetRedCards() external onlyAdmin{ dataSource.getRedCards(); } /** * @notice sets a match result to the contract storage * @param matchId id of match to check * @param result number of goals the first team scored * @param result2 number of goals the second team scored */ function dataSourceCallbackGroup(uint matchId, uint8 result, uint8 result2) public { require (msg.sender == dataSourceAddress); require (matchId >= 0 && matchId <= 47); groupsResults[matchId].teamOneGoals = result; groupsResults[matchId].teamTwoGoals = result2; LogGroupDataArrived(matchId, result, result2); } /** * @notice sets the sixteen teams that made it through groups to the contract storage * @param id index of sixteen teams * @param result results to be set */ function dataSourceCallbackRoundOfSixteen(uint id, uint8 result) public { require (msg.sender == dataSourceAddress); bracketsResults.roundOfSixteenTeamsIds[id] = result; bracketsResults.teamExists[result] = true; LogRoundOfSixteenArrived(id, result); } function dataSourceCallbackTeamId(uint matchId, uint8 result) public { require (msg.sender == dataSourceAddress); teamState state = bracketsResults.middlePhaseTeamsIds[result]; if (matchId >= 48 && matchId <= 55){ if (state < teamState.ROS) bracketsResults.middlePhaseTeamsIds[result] = teamState.ROS; } else if (matchId >= 56 && matchId <= 59){ if (state < teamState.QUARTERS) bracketsResults.middlePhaseTeamsIds[result] = teamState.QUARTERS; } else if (matchId == 60 || matchId == 61){ if (state < teamState.SEMIS) bracketsResults.middlePhaseTeamsIds[result] = teamState.SEMIS; } LogMiddlePhaseArrived(matchId, result); } /** * @notice sets the champion, second, third and fourth teams to the contract storage * @param id * @param result ids of the four teams */ function dataSourceCallbackFinals(uint id, uint8[4] result) public { require (msg.sender == dataSourceAddress); uint256 i; for(i = 0; i < 4; i++){ bracketsResults.finalsTeamsIds[i] = result[i]; } LogFinalsArrived(id, result); } /** * @notice sets the number of cards to the contract storage * @param id 101 for yellow cards, 102 for red cards * @param result amount of cards */ function dataSourceCallbackExtras(uint id, uint16 result) public { require (msg.sender == dataSourceAddress); if (id == 101){ extraResults.yellowCards = result; } else if (id == 102){ extraResults.redCards = result; } LogExtrasArrived(id, result); } /** * @notice check if prediction for a match winner is correct * @param realResultOne amount of goals team one scored * @param realResultTwo amount of goals team two scored * @param tokenResultOne amount of goals team one was predicted to score * @param tokenResultTwo amount of goals team two was predicted to score * @return */ function matchWinnerOk(uint8 realResultOne, uint8 realResultTwo, uint8 tokenResultOne, uint8 tokenResultTwo) internal pure returns(bool){ int8 realR = int8(realResultOne - realResultTwo); int8 tokenR = int8(tokenResultOne - tokenResultTwo); return (realR > 0 && tokenR > 0) || (realR < 0 && tokenR < 0) || (realR == 0 && tokenR == 0); } /** * @notice get points from a single match * @param matchIndex * @param groupsPhase token predictions * @return 10 if predicted score correctly, 3 if predicted only who would win * and 0 if otherwise */ function getMatchPointsGroups (uint256 matchIndex, uint192 groupsPhase) internal view returns(uint16 matchPoints) { uint8 tokenResultOne = uint8(groupsPhase & TEAM_RESULT_MASK_GROUPS); uint8 tokenResultTwo = uint8((groupsPhase >> 4) & TEAM_RESULT_MASK_GROUPS); uint8 teamOneGoals = groupsResults[matchIndex].teamOneGoals; uint8 teamTwoGoals = groupsResults[matchIndex].teamTwoGoals; if (teamOneGoals == tokenResultOne && teamTwoGoals == tokenResultTwo){ matchPoints += 10; } else { if (matchWinnerOk(teamOneGoals, teamTwoGoals, tokenResultOne, tokenResultTwo)){ matchPoints += 3; } } } /** * @notice calculates points from the last two matches * @param brackets token predictions * @return amount of points gained from the last two matches */ function getFinalRoundPoints (uint160 brackets) internal view returns(uint16 finalRoundPoints) { uint8[3] memory teamsIds; for (uint i = 0; i <= 2; i++){ brackets = brackets >> 5; //discard 4th place teamsIds[2-i] = uint8(brackets & RESULT_MASK_BRACKETS); } if (teamsIds[0] == bracketsResults.finalsTeamsIds[0]){ finalRoundPoints += 100; } if (teamsIds[2] == bracketsResults.finalsTeamsIds[2]){ finalRoundPoints += 25; } if (teamsIds[0] == bracketsResults.finalsTeamsIds[1]){ finalRoundPoints += 50; } if (teamsIds[1] == bracketsResults.finalsTeamsIds[0] || teamsIds[1] == bracketsResults.finalsTeamsIds[1]){ finalRoundPoints += 50; } } /** * @notice calculates points for round of sixteen, quarter-finals and semifinals * @param size amount of matches in round * @param round ros, qf, sf or f * @param brackets predictions * @return amount of points */ function getMiddleRoundPoints(uint8 size, teamState round, uint160 brackets) internal view returns(uint16 middleRoundResults){ uint8 teamId; for (uint i = 0; i < size; i++){ teamId = uint8(brackets & RESULT_MASK_BRACKETS); if (uint(bracketsResults.middlePhaseTeamsIds[teamId]) >= uint(round) ) { middleRoundResults+=60; } brackets = brackets >> 5; } } /** * @notice calculates points for correct predictions of group winners * @param brackets token predictions * @return amount of points */ function getQualifiersPoints(uint160 brackets) internal view returns(uint16 qualifiersPoints){ uint8 teamId; for (uint256 i = 0; i <= 15; i++){ teamId = uint8(brackets & RESULT_MASK_BRACKETS); if (teamId == bracketsResults.roundOfSixteenTeamsIds[15-i]){ qualifiersPoints+=30; } else if (bracketsResults.teamExists[teamId]){ qualifiersPoints+=25; } brackets = brackets >> 5; } } /** * @notice calculates points won by yellow and red cards predictions * @param extras token predictions * @return amount of points */ function getExtraPoints(uint32 extras) internal view returns(uint16 extraPoints){ uint16 redCards = uint16(extras & EXTRA_MASK_BRACKETS); extras = extras >> 16; uint16 yellowCards = uint16(extras); if (redCards == extraResults.redCards){ extraPoints+=20; } if (yellowCards == extraResults.yellowCards){ extraPoints+=20; } } /** * @notice calculates total amount of points for a token * @param t token to calculate points for * @return total amount of points */ function calculateTokenPoints (Token memory t) internal view returns(uint16 points){ //Groups phase 1 uint192 g1 = t.groups1; for (uint256 i = 0; i <= 23; i++){ points+=getMatchPointsGroups(23-i, g1); g1 = g1 >> 8; } //Groups phase 2 uint192 g2 = t.groups2; for (i = 0; i <= 23; i++){ points+=getMatchPointsGroups(47-i, g2); g2 = g2 >> 8; } uint160 bracketsLocal = t.brackets; //Brackets phase 1 points+=getFinalRoundPoints(bracketsLocal); bracketsLocal = bracketsLocal >> 20; //Brackets phase 2 points+=getMiddleRoundPoints(4, teamState.QUARTERS, bracketsLocal); bracketsLocal = bracketsLocal >> 20; //Brackets phase 3 points+=getMiddleRoundPoints(8, teamState.ROS, bracketsLocal); bracketsLocal = bracketsLocal >> 40; //Brackets phase 4 points+=getQualifiersPoints(bracketsLocal); //Extras points+=getExtraPoints(t.extra); } /** * @notice Sets the points of all the tokens between the last chunk set and the amount given. * @dev This function uses all the data collected earlier by oraclize to calculate points. * @param amount The amount of tokens that should be analyzed. */ function calculatePointsBlock(uint32 amount) external{ require (gameFinishedTime == 0); require(amount + lastCheckedToken <= tokens.length); for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) { uint16 points = calculateTokenPoints(tokens[i]); tokenToPointsMap[i] = points; if(worstTokens.length == 0 || points <= auxWorstPoints){ if(worstTokens.length != 0 && points < auxWorstPoints){ worstTokens.length = 0; } if(worstTokens.length < 100){ auxWorstPoints = points; worstTokens.push(i); } } } lastCalculatedToken += amount; } /** * @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the * percentage of the pot each position gets, last position is the percentage of the pot the last position gets, * and superior quota is the total amount OF winners that are given a prize. * @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game */ function setPayoutDistributionId () internal { if(tokens.length < 101){ payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 10; }else if(tokens.length < 201){ payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 20; }else if(tokens.length < 301){ payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 30; }else if(tokens.length < 501){ payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0]; lastPosition = 0; superiorQuota = 50; }else if(tokens.length < 1001){ payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0]; lastPosition = 4000; superiorQuota = 100; }else if(tokens.length < 2001){ payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0]; lastPosition = 2500; superiorQuota = 200; }else if(tokens.length < 3001){ payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0]; lastPosition = 2500; superiorQuota = 300; }else if(tokens.length < 5001){ payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0]; lastPosition = 2000; superiorQuota = 500; }else if(tokens.length < 10001){ payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0]; lastPosition = 1500; superiorQuota = 1000; }else if(tokens.length < 25001){ payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0]; lastPosition = 1000; superiorQuota = 2500; } else { payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70]; lastPosition = 900; superiorQuota = 5000; } } /** * @notice Sets the id of the last token that will be given a prize. * @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts * needed to just the winners and not the whole array of tokens. * @param tokenId last token id */ function setLimit(uint256 tokenId) external onlyAdmin{ require(tokenId < tokens.length); require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet); pointsLimit = tokenId; pValidationState = pointsValidationState.LimitSet; lastCheckedToken = 0; lastCalculatedToken = 0; winnerCounter = 0; setPayoutDistributionId(); } /** * @notice Sets the 10th percentile of the sorted array of points * @param amount tokens in a chunk */ function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){ require(amount + lastCheckedToken <= tokens.length); uint256 points = tokenToPointsMap[pointsLimit]; for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){ if(tokenToPointsMap[i] > points || (tokenToPointsMap[i] == points && i <= pointsLimit)){ winnerCounter++; } } lastCheckedToken += amount; if(lastCheckedToken == tokens.length){ require(superiorQuota == winnerCounter); pValidationState = pointsValidationState.LimitCalculated; } } /** * @notice Checks if the order given offchain coincides with the order of the actual previously calculated points * in the smart contract. * @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that * could occur from doing all the sorting onchain. * @param sortedChunk chunk sorted by points */ function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ require(sortedChunk.length + sortedWinners.length <= winnerCounter); for(uint256 i=0;i < sortedChunk.length-1;i++){ uint256 id = sortedChunk[i]; uint256 sigId = sortedChunk[i+1]; require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] && id < sigId)); } if(sortedWinners.length != 0){ uint256 id2 = sortedWinners[sortedWinners.length-1]; uint256 sigId2 = sortedChunk[0]; require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] || (tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2)); } for(uint256 j=0;j < sortedChunk.length;j++){ sortedWinners.push(sortedChunk[j]); } if(sortedWinners.length == winnerCounter){ require(sortedWinners[sortedWinners.length-1] == pointsLimit); pValidationState = pointsValidationState.OrderChecked; } } /** * @notice If anything during the point calculation and sorting part should fail, this function can reset * data structures to their initial position, so as to */ function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ sortedWinners.length = newLength; } /** * @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside * tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens * tie inside of the first 30 tokens, the prize will be summed and divided equally. */ function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){ uint256 percent = 0; uint[] memory tokensEquals = new uint[](30); uint16 tokenEqualsCounter = 0; uint256 currentTokenId; uint256 currentTokenPoints; uint256 lastTokenPoints; uint32 counter = 0; uint256 maxRange = 13; if(tokens.length < 201){ maxRange = 10; } while(payoutRange < maxRange){ uint256 inRangecounter = payDistributionAmount[payoutRange]; while(inRangecounter > 0){ currentTokenId = sortedWinners[counter]; currentTokenPoints = tokenToPointsMap[currentTokenId]; inRangecounter--; //Special case for the last one if(inRangecounter == 0 && payoutRange == maxRange - 1){ if(currentTokenPoints == lastTokenPoints){ percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; }else{ tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange]; } } if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){ //Fix second condition for(uint256 i=0;i < tokenEqualsCounter;i++){ tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter); } percent = 0; tokensEquals = new uint[](30); tokenEqualsCounter = 0; } percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; counter++; lastTokenPoints = currentTokenPoints; } payoutRange++; } pValidationState = pointsValidationState.TopWinnersAssigned; lastPrizeGiven = counter; } /** * @notice Sets prize percentage to every address that wins from the position 30th onwards * @dev If there are less than 300 tokens playing, then this function will set nothing. * @param amount tokens in a chunk */ function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){ require(lastPrizeGiven + amount <= winnerCounter); uint16 inRangeCounter = payDistributionAmount[payoutRange]; for(uint256 i = 0; i < amount; i++){ if (inRangeCounter == 0){ payoutRange++; inRangeCounter = payDistributionAmount[payoutRange]; } uint256 tokenId = sortedWinners[i + lastPrizeGiven]; tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange]; inRangeCounter--; } //i + amount prize was not given yet, so amount -1 lastPrizeGiven += amount; payDistributionAmount[payoutRange] = inRangeCounter; if(lastPrizeGiven == winnerCounter){ pValidationState = pointsValidationState.WinnersAssigned; return; } } /** * @notice Sets prizes for last tokens and sets prize pool amount */ function setLastPositions() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){ for(uint256 j = 0;j < worstTokens.length;j++){ uint256 tokenId = worstTokens[j]; tokenToPayoutMap[tokenId] += lastPosition.div(worstTokens.length); } uint256 balance = address(this).balance; adminPool = balance.mul(25).div(100); prizePool = balance.mul(75).div(100); pValidationState = pointsValidationState.Finished; gameFinishedTime = now; } } /** * @title CoreLayer * @author CryptoCup Team (https://cryptocup.io/about) * @notice Main contract */ contract CoreLayer is GameLogicLayer { function CoreLayer() public { adminAddress = msg.sender; deploymentTime = now; } /** * @dev Only accept eth from the admin */ function() external payable { require(msg.sender == adminAddress); } function isDataSourceCallback() public pure returns (bool){ return true; } /** * @notice Builds ERC721 token with the predictions provided by the user. * @param groups1 - First half of the group matches scores encoded in a uint192. * @param groups2 - Second half of the groups matches scores encoded in a uint192. * @param brackets - Bracket information encoded in a uint160. * @param extra - Extra information (number of red cards and yellow cards) encoded in a uint32. * @dev An automatic timestamp is added for internal use. */ function buildToken(uint192 groups1, uint192 groups2, uint160 brackets, uint32 extra) external payable isNotPaused { Token memory token = Token({ groups1: groups1, groups2: groups2, brackets: brackets, timeStamp: uint64(now), extra: extra }); require(msg.value >= _getTokenPrice()); require(msg.sender != address(0)); require(tokens.length < WCCTOKEN_CREATION_LIMIT); require(tokensOfOwnerMap[msg.sender].length < 100); require(now < WORLD_CUP_START); //World cup Start uint256 tokenId = tokens.push(token) - 1; require(tokenId == uint256(uint32(tokenId))); _setTokenOwner(msg.sender, tokenId); LogTokenBuilt(msg.sender, tokenId, token); } /** * @param tokenId - ID of token to get. * @return Returns all the valuable information about a specific token. */ function getToken(uint256 tokenId) external view returns (uint192 groups1, uint192 groups2, uint160 brackets, uint64 timeStamp, uint32 extra) { Token storage token = tokens[tokenId]; groups1 = token.groups1; groups2 = token.groups2; brackets = token.brackets; timeStamp = token.timeStamp; extra = token.extra; } /** * @notice Called by the development team once the World Cup has ended (adminPool is set) * @dev Allows dev team to retrieve adminPool */ function adminWithdrawBalance() external onlyAdmin { adminAddress.transfer(adminPool); adminPool = 0; } /** * @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens * owned by the caller of this function. * @dev If the caller has no prize, the function will revert costing no gas to the caller. */ function withdrawPrize() external checkState(pointsValidationState.Finished){ uint256 prize = 0; uint256[] memory tokenList = tokensOfOwnerMap[msg.sender]; for(uint256 i = 0;i < tokenList.length; i++){ prize += tokenToPayoutMap[tokenList[i]]; tokenToPayoutMap[tokenList[i]] = 0; } require(prize > 0); msg.sender.transfer((prizePool.mul(prize)).div(1000000)); } /** * @notice Gets current token price */ function _getTokenPrice() internal view returns(uint256 tokenPrice){ if ( now >= THIRD_PHASE){ tokenPrice = (150 finney); } else if (now >= SECOND_PHASE) { tokenPrice = (110 finney); } else if (now >= FIRST_PHASE) { tokenPrice = (75 finney); } else { tokenPrice = STARTING_PRICE; } require(tokenPrice >= STARTING_PRICE && tokenPrice <= (200 finney)); } /** * @dev Sets the data source contract address * @param _address Address to be set */ function setDataSourceAddress(address _address) external onlyAdmin { DataSourceInterface c = DataSourceInterface(_address); require(c.isDataSource()); dataSource = c; dataSourceAddress = _address; } /** * @notice Testing function to corroborate group data from oraclize call * @param x Id of the match to get * @return uint8 Team 1 goals * @return uint8 Team 2 goals */ function getGroupData(uint x) external view returns(uint8 a, uint8 b){ a = groupsResults[x].teamOneGoals; b = groupsResults[x].teamTwoGoals; } /** * @notice Testing function to corroborate round of sixteen data from oraclize call * @return An array with the ids of the round of sixteen teams */ function getBracketData() external view returns(uint8[16] a){ a = bracketsResults.roundOfSixteenTeamsIds; } /** * @notice Testing function to corroborate brackets data from oraclize call * @param x Team id * @return The place the team reached */ function getBracketDataMiddleTeamIds(uint8 x) external view returns(teamState a){ a = bracketsResults.middlePhaseTeamsIds[x]; } /** * @notice Testing function to corroborate finals data from oraclize call * @return the 4 (four) final teams ids */ function getBracketDataFinals() external view returns(uint8[4] a){ a = bracketsResults.finalsTeamsIds; } /** * @notice Testing function to corroborate extra data from oraclize call * @return amount of yellow and red cards */ function getExtrasData() external view returns(uint16 a, uint16 b){ a = extraResults.yellowCards; b = extraResults.redCards; } //EMERGENCY CALLS //If something goes wrong or fails, these functions will allow retribution for token holders /** * @notice if there is an unresolvable problem, users can call to this function to get a refund. */ function emergencyWithdraw() external hasFinalized{ uint256 balance = STARTING_PRICE * tokensOfOwnerMap[msg.sender].length; delete tokensOfOwnerMap[msg.sender]; msg.sender.transfer(balance); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function finishedGameWithdraw() external onlyAdmin hasFinished{ uint256 balance = address(this).balance; adminAddress.transfer(balance); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{ require(finalizedTime != 0 && now >= finalizedTime + 10 days ); msg.sender.transfer(address(this).balance); } }
checks if a user owns a token userAddress - The address to check. tokenId - ID of the token that needs to be verified. return true if the userAddress provided owns the token./
function _userOwnsToken(address userAddress, uint256 tokenId) internal view returns (bool){ return ownerOfTokenMap[tokenId] == userAddress; }
7,712,450
// SPDX-License-Identifier: NONE pragma solidity 0.7.6; // Part: IERC20Permit /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // Part: LixirErrors library LixirErrors { function require_INSUFFICIENT_BALANCE(bool cond) internal pure { require(cond, 'INSUFFICIENT_BALANCE'); } function require_INSUFFICIENT_ALLOWANCE(bool cond) internal pure { require(cond, 'INSUFFICIENT_ALLOWANCE'); } function require_PERMIT_EXPIRED(bool cond) internal pure { require(cond, 'PERMIT_EXPIRED'); } function require_INVALID_SIGNATURE(bool cond) internal pure { require(cond, 'INVALID_SIGNATURE'); } function require_XFER_ZERO_ADDRESS(bool cond) internal pure { require(cond, 'XFER_ZERO_ADDRESS'); } function require_INSUFFICIENT_INPUT_AMOUNT(bool cond) internal pure { require(cond, 'INSUFFICIENT_INPUT_AMOUNT'); } function require_INSUFFICIENT_OUTPUT_AMOUNT(bool cond) internal pure { require(cond, 'INSUFFICIENT_OUTPUT_AMOUNT'); } function require_INSUFFICIENT_ETH(bool cond) internal pure { require(cond, 'INSUFFICIENT_ETH'); } function require_MAX_SUPPLY(bool cond) internal pure { require(cond, 'MAX_SUPPLY'); } } // Part: LixirRoles library LixirRoles { bytes32 constant gov_role = keccak256('v1_gov_role'); bytes32 constant delegate_role = keccak256('v1_delegate_role'); bytes32 constant vault_role = keccak256('v1_vault_role'); bytes32 constant strategist_role = keccak256('v1_strategist_role'); bytes32 constant pauser_role = keccak256('v1_pauser_role'); bytes32 constant keeper_role = keccak256('v1_keeper_role'); bytes32 constant deployer_role = keccak256('v1_deployer_role'); bytes32 constant strategy_role = keccak256('v1_strategy_role'); bytes32 constant vault_implementation_role = keccak256('v1_vault_implementation_role'); bytes32 constant eth_vault_implementation_role = keccak256('v1_eth_vault_implementation_role'); bytes32 constant factory_role = keccak256('v1_factory_role'); bytes32 constant fee_setter_role = keccak256('fee_setter_role'); } // Part: OpenZeppelin/openzeppelin-contracts@3.4.1-solc-0.7-2/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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.1-solc-0.7-2/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 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; } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.1-solc-0.7-2/EnumerableSet /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.1-solc-0.7-2/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/openzeppelin-contracts@3.4.1-solc-0.7-2/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: SafeCast /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } function abs(int256 y) internal pure returns (uint256 z) { z = y < 0 ? uint256(-y) : uint256(y); } } // Part: Uniswap/uniswap-v3-core@1.0.0/FixedPoint128 /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // Part: Uniswap/uniswap-v3-core@1.0.0/FixedPoint96 /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // Part: Uniswap/uniswap-v3-core@1.0.0/FullMath /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3MintCallback /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolActions /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolDerivedState /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolEvents /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolImmutables /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolOwnerActions /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3PoolState /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // Part: Uniswap/uniswap-v3-core@1.0.0/LowGasSafeMath /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // Part: Uniswap/uniswap-v3-core@1.0.0/TickMath /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // Part: Uniswap/uniswap-v3-core@1.0.0/UnsafeMath /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } // Part: Uniswap/uniswap-v3-periphery@1.0.0/PoolAddress /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // Part: Uniswap/uniswap-v3-periphery@1.0.0/PositionKey library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } // Part: Uniswap/uniswap-v3-periphery@1.0.0/TransferHelper library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // Part: ILixirVaultToken interface ILixirVaultToken is IERC20, IERC20Permit {} // Part: OpenZeppelin/openzeppelin-contracts@3.4.1-solc-0.7-2/AccessControl /** * @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, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { 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 `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 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. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _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()); } } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.1-solc-0.7-2/Initializable /** * @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 !Address.isContract(address(this)); } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.1-solc-0.7-2/Pausable /** * @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()); } } // Part: SqrtPriceMath /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // Part: Uniswap/uniswap-v3-core@1.0.0/IUniswapV3Pool /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // Part: Uniswap/uniswap-v3-periphery@1.0.0/IWETH9 /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // Part: Uniswap/uniswap-v3-periphery@1.0.0/LiquidityAmounts /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // Part: EIP712Initializable /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Initializable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; constructor(string memory version) { _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); } /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712__initialize(string memory name) internal initializer { _HASHED_NAME = keccak256(bytes(name)); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256( abi.encode( _TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked('\x19\x01', _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // Part: ILixirVault interface ILixirVault is ILixirVaultToken { function initialize( string memory name, string memory symbol, address _token0, address _token1, address _strategist, address _keeper, address _strategy ) external; function token0() external view returns (IERC20); function token1() external view returns (IERC20); function activeFee() external view returns (uint24); function activePool() external view returns (IUniswapV3Pool); function strategist() external view returns (address); function strategy() external view returns (address); function keeper() external view returns (address); function setKeeper(address _keeper) external; function setStrategist(address _strategist) external; function setStrategy(address _strategy) external; function setPerformanceFee(uint24 newFee) external; function emergencyExit() external; function unpause() external; function mainPosition() external view returns (int24 tickLower, int24 tickUpper); function rangePosition() external view returns (int24 tickLower, int24 tickUpper); function rebalance( int24 mainTickLower, int24 mainTickUpper, int24 rangeTickLower0, int24 rangeTickUpper0, int24 rangeTickLower1, int24 rangeTickUpper1, uint24 fee ) external; function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min, address receiver, uint256 deadline ) external returns (uint256 amount0Out, uint256 amount1Out); function withdrawFrom( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external returns (uint256 amount0Out, uint256 amount1Out); function deposit( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external returns ( uint256 shares, uint256 amount0, uint256 amount1 ); function calculateTotalsFromTick(int24 virtualTick) external view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ); } // Part: LixirRegistry /** @notice an access control contract with roles used to handle permissioning throughout the `Vault` and `Strategy` contracts. */ contract LixirRegistry is AccessControl { address public immutable uniV3Factory; IWETH9 public immutable weth9; /// king bytes32 public constant gov_role = keccak256('v1_gov_role'); /// same privileges as `gov_role` bytes32 public constant delegate_role = keccak256('v1_delegate_role'); /// configuring options within the strategy contract & vault bytes32 public constant strategist_role = keccak256('v1_strategist_role'); /// can `emergencyExit` a vault bytes32 public constant pauser_role = keccak256('v1_pauser_role'); /// can `rebalance` the vault via the strategy contract bytes32 public constant keeper_role = keccak256('v1_keeper_role'); /// can `createVault`s from the factory contract bytes32 public constant deployer_role = keccak256('v1_deployer_role'); /// verified vault in the registry bytes32 public constant vault_role = keccak256('v1_vault_role'); /// can initialize vaults bytes32 public constant strategy_role = keccak256('v1_strategy_role'); bytes32 public constant vault_implementation_role = keccak256('v1_vault_implementation_role'); bytes32 public constant eth_vault_implementation_role = keccak256('v1_eth_vault_implementation_role'); /// verified vault factory in the registry bytes32 public constant factory_role = keccak256('v1_factory_role'); /// can `setPerformanceFee` on a vault bytes32 public constant fee_setter_role = keccak256('fee_setter_role'); address public feeTo; address public emergencyReturn; uint24 public constant PERFORMANCE_FEE_PRECISION = 1e6; event FeeToChanged(address indexed previousFeeTo, address indexed newFeeTo); event EmergencyReturnChanged( address indexed previousEmergencyReturn, address indexed newEmergencyReturn ); constructor( address _governance, address _delegate, address _uniV3Factory, address _weth9 ) { uniV3Factory = _uniV3Factory; weth9 = IWETH9(_weth9); _setupRole(gov_role, _governance); _setupRole(delegate_role, _delegate); // gov is its own admin _setRoleAdmin(gov_role, gov_role); _setRoleAdmin(delegate_role, gov_role); _setRoleAdmin(strategist_role, delegate_role); _setRoleAdmin(fee_setter_role, delegate_role); _setRoleAdmin(pauser_role, delegate_role); _setRoleAdmin(keeper_role, delegate_role); _setRoleAdmin(deployer_role, delegate_role); _setRoleAdmin(factory_role, delegate_role); _setRoleAdmin(strategy_role, delegate_role); _setRoleAdmin(vault_implementation_role, delegate_role); _setRoleAdmin(eth_vault_implementation_role, delegate_role); _setRoleAdmin(vault_role, factory_role); } function addRole(bytes32 role, bytes32 roleAdmin) public { require(isGovOrDelegate(msg.sender)); require(getRoleAdmin(role) == bytes32(0) && getRoleMemberCount(role) == 0); _setRoleAdmin(role, roleAdmin); } function isGovOrDelegate(address account) public view returns (bool) { return hasRole(gov_role, account) || hasRole(delegate_role, account); } function setFeeTo(address _feeTo) external { require(isGovOrDelegate(msg.sender)); address previous = feeTo; feeTo = _feeTo; emit FeeToChanged(previous, _feeTo); } function setEmergencyReturn(address _emergencyReturn) external { require(isGovOrDelegate(msg.sender)); address previous = emergencyReturn; emergencyReturn = _emergencyReturn; emit EmergencyReturnChanged(previous, _emergencyReturn); } } // Part: ILixirVaultETH interface ILixirVaultETH is ILixirVault { enum TOKEN {ZERO, ONE} function WETH_TOKEN() external view returns (TOKEN); function depositETH( uint256 amountDesired, uint256 amountEthMin, uint256 amountMin, address recipient, uint256 deadline ) external payable returns ( uint256 shares, uint256 amountEthIn, uint256 amountIn ); function withdrawETHFrom( address withdrawer, uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external returns (uint256 amountEthOut, uint256 amountOut); function withdrawETH( uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external returns (uint256 amountEthOut, uint256 amountOut); receive() external payable; } // Part: LixirBase /** @notice An abstract contract that gives access to the registry and contains common modifiers for restricting access to functions based on role. */ abstract contract LixirBase { LixirRegistry public immutable registry; constructor(address _registry) { registry = LixirRegistry(_registry); } modifier onlyRole(bytes32 role) { require(registry.hasRole(role, msg.sender)); _; } modifier onlyGovOrDelegate { require(registry.isGovOrDelegate(msg.sender)); _; } modifier hasRole(bytes32 role, address account) { require(registry.hasRole(role, account)); _; } } // Part: LixirVaultToken /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` */ contract LixirVaultToken is ILixirVaultToken, EIP712Initializable { using SafeMath for uint256; // State variables uint8 private constant _DECIMALS = 18; mapping(address => uint256) private _balance; mapping(address => mapping(address => uint256)) _allowance; uint256 private _totalSupply; string private _name; string private _symbol; mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPE_HASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); constructor() EIP712Initializable('1') {} // Function declarations function __LixirVaultToken__initialize( string memory tokenName, string memory tokenSymbol ) internal initializer { __EIP712__initialize(tokenName); _name = tokenName; _symbol = tokenSymbol; } // External functions function allowance(address owner, address spender) public view override returns (uint256) { return _allowance[owner][spender]; } function balanceOf(address account) external view override returns (uint256) { return _balance[account]; } function approve(address spender, uint256 amount) external override returns (bool) { _setAllowance(msg.sender, spender, amount); return true; } function increaseApproval(address spender, uint256 amount) external returns (bool) { _setAllowance( msg.sender, spender, _allowance[msg.sender][spender].add(amount) ); return true; } function decreaseApproval(address spender, uint256 amount) external returns (bool) { uint256 currentAllowance = _allowance[msg.sender][spender]; if (amount >= currentAllowance) { _setAllowance(msg.sender, spender, 0); } else { _setAllowance(msg.sender, spender, currentAllowance.sub(amount)); } return true; } function transfer(address recipient, uint256 amount) external override returns (bool) { _move(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 currentAllowance = _allowance[sender][msg.sender]; LixirErrors.require_INSUFFICIENT_ALLOWANCE( msg.sender == sender || currentAllowance >= amount ); _move(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _setAllowance(sender, msg.sender, currentAllowance - amount); } return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time LixirErrors.require_PERMIT_EXPIRED(block.timestamp <= deadline); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256( abi.encode(_PERMIT_TYPE_HASH, owner, spender, value, nonce, deadline) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); LixirErrors.require_INVALID_SIGNATURE(signer != address(0)); _nonces[owner] = nonce + 1; _setAllowance(owner, spender, value); } // Public functions function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _DECIMALS; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function nonces(address owner) external view override returns (uint256) { return _nonces[owner]; } // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } // Internal functions function _beforeMintCallback(address recipient, uint256 amount) internal virtual {} function _mintPoolTokens(address recipient, uint256 amount) internal { _beforeMintCallback(recipient, amount); _balance[recipient] = _balance[recipient].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { uint256 currentBalance = _balance[sender]; LixirErrors.require_INSUFFICIENT_BALANCE(currentBalance >= amount); _balance[sender] = currentBalance - amount; _totalSupply = _totalSupply.sub(amount); emit Transfer(sender, address(0), amount); } function _move( address sender, address recipient, uint256 amount ) internal { uint256 currentBalance = _balance[sender]; LixirErrors.require_INSUFFICIENT_BALANCE(currentBalance >= amount); // Prohibit transfers to the zero address to avoid confusion with the // Transfer event emitted by `_burnPoolTokens` LixirErrors.require_XFER_ZERO_ADDRESS(recipient != address(0)); _balance[sender] = currentBalance - amount; _balance[recipient] = _balance[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _setAllowance( address owner, address spender, uint256 amount ) internal { _allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } } // Part: LixirVault contract LixirVault is ILixirVault, LixirVaultToken, LixirBase, IUniswapV3MintCallback, Pausable { using LowGasSafeMath for uint256; using SafeCast for uint256; using SafeCast for int256; using SafeCast for uint128; IERC20 public override token0; IERC20 public override token1; uint24 public override activeFee; IUniswapV3Pool public override activePool; address public override strategy; address public override strategist; address public override keeper; Position public override mainPosition; Position public override rangePosition; uint24 public performanceFee; uint24 immutable PERFORMANCE_FEE_PRECISION; address immutable uniV3Factory; event Deposit( address indexed depositor, address indexed recipient, uint256 shares, uint256 amount0In, uint256 amount1In, uint256 total0, uint256 total1 ); event Withdraw( address indexed withdrawer, address indexed recipient, uint256 shares, uint256 amount0Out, uint256 amount1Out ); event Rebalance( int24 mainTickLower, int24 mainTickUpper, int24 rangeTickLower, int24 rangeTickUpper, uint24 newFee, uint256 total0, uint256 total1 ); event PerformanceFeeSet(uint24 oldFee, uint24 newFee); event StrategySet(address oldStrategy, address newStrategy); struct DepositPositionData { uint128 LDelta; int24 tickLower; int24 tickUpper; } enum POSITION {MAIN, RANGE} // details about the uniswap position struct Position { // the tick range of the position int24 tickLower; int24 tickUpper; } constructor(address _registry) LixirBase(_registry) { PERFORMANCE_FEE_PRECISION = LixirRegistry(_registry) .PERFORMANCE_FEE_PRECISION(); uniV3Factory = LixirRegistry(_registry).uniV3Factory(); } /** @notice sets fields in the contract and initializes the `LixirVaultToken` */ function initialize( string memory name, string memory symbol, address _token0, address _token1, address _strategist, address _keeper, address _strategy ) public virtual override hasRole(LixirRoles.strategist_role, _strategist) hasRole(LixirRoles.keeper_role, _keeper) hasRole(LixirRoles.strategy_role, _strategy) initializer { require(_token0 < _token1); __LixirVaultToken__initialize(name, symbol); token0 = IERC20(_token0); token1 = IERC20(_token1); strategist = _strategist; keeper = _keeper; strategy = _strategy; } modifier onlyStrategist() { require(msg.sender == strategist); _; } modifier onlyStrategy() { require(msg.sender == strategy); _; } modifier notExpired(uint256 deadline) { require(block.timestamp <= deadline, 'Expired'); _; } /** @dev calculates shares, totals, etc. to mint the proper amount of `LixirVaultToken`s to `recipient` */ function _depositStepOne( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient ) internal returns ( DepositPositionData memory mainData, DepositPositionData memory rangeData, uint256 shares, uint256 amount0In, uint256 amount1In, uint256 total0, uint256 total1 ) { uint256 _totalSupply = totalSupply(); mainData = DepositPositionData({ LDelta: 0, tickLower: mainPosition.tickLower, tickUpper: mainPosition.tickUpper }); rangeData = DepositPositionData({ LDelta: 0, tickLower: rangePosition.tickLower, tickUpper: rangePosition.tickUpper }); if (_totalSupply == 0) { (shares, mainData.LDelta, amount0In, amount1In) = calculateInitialDeposit( amount0Desired, amount1Desired ); total0 = amount0In; total1 = amount1In; } else { uint128 mL; uint128 rL; { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); (total0, total1, mL, rL) = _calculateTotals( sqrtRatioX96, tick, mainData, rangeData ); } (shares, amount0In, amount1In) = calcSharesAndAmounts( amount0Desired, amount1Desired, total0, total1, _totalSupply ); mainData.LDelta = uint128(FullMath.mulDiv(mL, shares, _totalSupply)); rangeData.LDelta = uint128(FullMath.mulDiv(rL, shares, _totalSupply)); } LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount0Min <= amount0In && amount1Min <= amount1In ); _mintPoolTokens(recipient, shares); } /** @dev this function deposits the tokens into the UniV3 pool */ function _depositStepTwo( DepositPositionData memory mainData, DepositPositionData memory rangeData, address recipient, uint256 shares, uint256 amount0In, uint256 amount1In, uint256 total0, uint256 total1 ) internal { uint128 mLDelta = mainData.LDelta; if (0 < mLDelta) { activePool.mint( address(this), mainData.tickLower, mainData.tickUpper, mLDelta, '' ); } uint128 rLDelta = rangeData.LDelta; if (0 < rLDelta) { activePool.mint( address(this), rangeData.tickLower, rangeData.tickUpper, rLDelta, '' ); } emit Deposit( address(msg.sender), address(recipient), shares, amount0In, amount1In, total0, total1 ); } /** @notice deposit's the callers ERC20 tokens into the vault, mints them `LixirVaultToken`s, and adds their liquidity to the UniswapV3 pool. @param amount0Desired Amount of token 0 desired by user @param amount1Desired Amount of token 1 desired by user @param amount0Min Minimum amount of token 0 desired by user @param amount1Min Minimum amount of token 1 desired by user @param recipient The address for which the liquidity will be created @param deadline Blocktimestamp that this must execute before @return shares @return amount0In how much token0 was actually deposited @return amount1In how much token1 was actually deposited */ function deposit( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external override whenNotPaused notExpired(deadline) returns ( uint256 shares, uint256 amount0In, uint256 amount1In ) { DepositPositionData memory mainData; DepositPositionData memory rangeData; uint256 total0; uint256 total1; ( mainData, rangeData, shares, amount0In, amount1In, total0, total1 ) = _depositStepOne( amount0Desired, amount1Desired, amount0Min, amount1Min, recipient ); if (0 < amount0In) { // token0.transferFrom(msg.sender, address(this), amount0In); TransferHelper.safeTransferFrom( address(token0), msg.sender, address(this), amount0In ); } if (0 < amount1In) { // token1.transferFrom(msg.sender, address(this), amount1In); TransferHelper.safeTransferFrom( address(token1), msg.sender, address(this), amount1In ); } _depositStepTwo( mainData, rangeData, recipient, shares, amount0In, amount1In, total0, total1 ); } function _withdrawStep( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient ) internal returns (uint256 amount0Out, uint256 amount1Out) { uint256 _totalSupply = totalSupply(); _burnPoolTokens(withdrawer, shares); // does balance check (, int24 tick, , , , , ) = activePool.slot0(); // if withdrawing everything, then burn and collect the all positions // else, calculate their share and return it if (shares == _totalSupply) { if (!paused()) { burnCollectPositions(); } amount0Out = token0.balanceOf(address(this)); amount1Out = token1.balanceOf(address(this)); } else { { uint256 e0 = token0.balanceOf(address(this)); amount0Out = e0 > 0 ? FullMath.mulDiv(e0, shares, _totalSupply) : 0; uint256 e1 = token1.balanceOf(address(this)); amount1Out = e1 > 0 ? FullMath.mulDiv(e1, shares, _totalSupply) : 0; } if (!paused()) { { (uint256 ma0Out, uint256 ma1Out) = burnAndCollect(mainPosition, tick, shares, _totalSupply); amount0Out = amount0Out.add(ma0Out); amount1Out = amount1Out.add(ma1Out); } { (uint256 ra0Out, uint256 ra1Out) = burnAndCollect(rangePosition, tick, shares, _totalSupply); amount0Out = amount0Out.add(ra0Out); amount1Out = amount1Out.add(ra1Out); } } } LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount0Min <= amount0Out && amount1Min <= amount1Out ); emit Withdraw( address(msg.sender), address(recipient), shares, amount0Out, amount1Out ); } modifier canSpend(address withdrawer, uint256 shares) { uint256 currentAllowance = _allowance[withdrawer][msg.sender]; LixirErrors.require_INSUFFICIENT_ALLOWANCE( msg.sender == withdrawer || currentAllowance >= shares ); if (msg.sender != withdrawer && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != withdrawer then currentAllowance >= shares _setAllowance(withdrawer, msg.sender, currentAllowance - shares); } _; } /** @notice withdraws the desired shares from the vault on behalf of another account @dev same as `withdraw` except this can be called from an `approve`d address @param withdrawer the address to withdraw from @param shares number of shares to withdraw @param amount0Min Minimum amount of token 0 desired by user @param amount1Min Minimum amount of token 1 desired by user @param recipient address to recieve token0 and token1 withdrawals @param deadline blocktimestamp that this must execute by @return amount0Out how much token0 was actually withdrawn @return amount1Out how much token1 was actually withdrawn */ function withdrawFrom( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external override canSpend(withdrawer, shares) returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdraw( withdrawer, shares, amount0Min, amount1Min, recipient, deadline ); } /** @notice withdraws the desired shares from the vault and transfers to caller. @dev `_withdrawStep` calculates how much the caller is owed @dev `_withdraw` transfers the tokens to the caller @param shares number of shares to withdraw @param amount0Min Minimum amount of token 0 desired by user @param amount1Min Minimum amount of token 1 desired by user @param recipient address to recieve token0 and token1 withdrawals @param deadline blocktimestamp that this must execute by @return amount0Out how much token0 was actually withdrawn @return amount1Out how much token1 was actually withdrawn */ function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) external override returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdraw( msg.sender, shares, amount0Min, amount1Min, recipient, deadline ); } function _withdraw( address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) internal notExpired(deadline) returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdrawStep( withdrawer, shares, amount0Min, amount1Min, recipient ); if (0 < amount0Out) { TransferHelper.safeTransfer(address(token0), recipient, amount0Out); } if (0 < amount1Out) { TransferHelper.safeTransfer(address(token1), recipient, amount1Out); } } function setPerformanceFee(uint24 newFee) external override onlyRole(LixirRoles.fee_setter_role) { require(newFee < PERFORMANCE_FEE_PRECISION); emit PerformanceFeeSet(performanceFee, newFee); performanceFee = newFee; } function _setPool(uint24 fee) internal { activePool = IUniswapV3Pool( PoolAddress.computeAddress( uniV3Factory, PoolAddress.getPoolKey(address(token0), address(token1), fee) ) ); require(Address.isContract(address(activePool))); activeFee = fee; } function setKeeper(address _keeper) external override onlyStrategist hasRole(LixirRoles.keeper_role, _keeper) { keeper = _keeper; } function setStrategy(address _strategy) external override onlyStrategist hasRole(LixirRoles.strategy_role, _strategy) { emit StrategySet(strategy, _strategy); strategy = _strategy; } function setStrategist(address _strategist) external override onlyGovOrDelegate hasRole(LixirRoles.strategist_role, _strategist) { strategist = _strategist; } function emergencyExit() external override whenNotPaused onlyRole(LixirRoles.pauser_role) { burnCollectPositions(); _pause(); } function unpause() external override whenPaused onlyGovOrDelegate { _unpause(); } /** @notice burns all positions collects any fees accrued since last `rebalance` and mints new positions. @dev This function is not called by an external account, but instead by the strategy contract, which automatically calculates the proper positions to mint. */ function rebalance( int24 mainTickLower, int24 mainTickUpper, int24 rangeTickLower0, int24 rangeTickUpper0, int24 rangeTickLower1, int24 rangeTickUpper1, uint24 fee ) external override onlyStrategy whenNotPaused { require( TickMath.MIN_TICK <= mainTickLower && mainTickUpper <= TickMath.MAX_TICK && mainTickLower < mainTickUpper && TickMath.MIN_TICK <= rangeTickLower0 && rangeTickUpper0 <= TickMath.MAX_TICK && rangeTickLower0 < rangeTickUpper0 && TickMath.MIN_TICK <= rangeTickLower1 && rangeTickUpper1 <= TickMath.MAX_TICK && rangeTickLower1 < rangeTickUpper1 ); /// if a pool has been previously set, then take the performance fee accrued since last `rebalance` /// and burn and collect all positions. if (address(activePool) != address(0)) { _takeFee(); burnCollectPositions(); } /// if the strategist has changed the pool fee tier (e.g. 0.05%, 0.3%, 1%), then change the pool if (fee != activeFee) { _setPool(fee); } uint256 total0 = token0.balanceOf(address(this)); uint256 total1 = token1.balanceOf(address(this)); Position memory mainData = Position(mainTickLower, mainTickUpper); Position memory rangeData0 = Position(rangeTickLower0, rangeTickUpper0); Position memory rangeData1 = Position(rangeTickLower1, rangeTickUpper1); mintPositions(total0, total1, mainData, rangeData0, rangeData1); emit Rebalance( mainTickLower, mainTickUpper, rangePosition.tickLower, rangePosition.tickUpper, fee, total0, total1 ); } function mintPositions( uint256 amount0, uint256 amount1, Position memory mainData, Position memory rangeData0, Position memory rangeData1 ) internal { (uint160 sqrtRatioX96, ) = getSqrtRatioX96AndTick(); mainPosition.tickLower = mainData.tickLower; mainPosition.tickUpper = mainData.tickUpper; if (0 < amount0 || 0 < amount1) { uint128 mL = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(mainData.tickLower), TickMath.getSqrtRatioAtTick(mainData.tickUpper), amount0, amount1 ); if (0 < mL) { activePool.mint( address(this), mainData.tickLower, mainData.tickUpper, mL, '' ); } } amount0 = token0.balanceOf(address(this)); amount1 = token1.balanceOf(address(this)); uint128 rL; Position memory rangeData; if (0 < amount0 || 0 < amount1) { uint128 rL0 = LiquidityAmounts.getLiquidityForAmount0( TickMath.getSqrtRatioAtTick(rangeData0.tickLower), TickMath.getSqrtRatioAtTick(rangeData0.tickUpper), amount0 ); uint128 rL1 = LiquidityAmounts.getLiquidityForAmount1( TickMath.getSqrtRatioAtTick(rangeData1.tickLower), TickMath.getSqrtRatioAtTick(rangeData1.tickUpper), amount1 ); /// only one range position will ever have liquidity (if any) if (rL1 < rL0) { rL = rL0; rangeData = rangeData0; } else if (0 < rL1) { rangeData = rangeData1; rL = rL1; } } else { rangeData = Position(0, 0); } rangePosition.tickLower = rangeData.tickLower; rangePosition.tickUpper = rangeData.tickUpper; if (0 < rL) { activePool.mint( address(this), rangeData.tickLower, rangeData.tickUpper, rL, '' ); } } function _takeFee() internal { uint24 _perfFee = performanceFee; address _feeTo = registry.feeTo(); if (_feeTo != address(0) && 0 < _perfFee) { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); ( , uint256 total0, uint256 total1, uint256 tokensOwed0, uint256 tokensOwed1 ) = calculatePositionInfo( tick, sqrtRatioX96, mainPosition.tickLower, mainPosition.tickUpper ); { ( , uint256 total0Range, uint256 total1Range, uint256 tokensOwed0Range, uint256 tokensOwed1Range ) = calculatePositionInfo( tick, sqrtRatioX96, rangePosition.tickLower, rangePosition.tickUpper ); total0 = total0.add(total0Range).add(token0.balanceOf(address(this))); total1 = total1.add(total1Range).add(token1.balanceOf(address(this))); tokensOwed0 = tokensOwed0.add(tokensOwed0Range); tokensOwed1 = tokensOwed1.add(tokensOwed1Range); } uint256 _totalSupply = totalSupply(); uint256 price = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, FixedPoint96.Q96); total1 = total1.add(FullMath.mulDiv(total0, price, FixedPoint96.Q96)); if (total1 > 0) { tokensOwed1 = tokensOwed1.add( FullMath.mulDiv(tokensOwed0, price, FixedPoint96.Q96) ); uint256 shares = FullMath.mulDiv( FullMath.mulDiv(tokensOwed1, _totalSupply, total1), performanceFee, PERFORMANCE_FEE_PRECISION ); if (shares > 0) { _mintPoolTokens(_feeTo, shares); } } } } /** @notice burns everyting (main and range positions) and collects any fees accrued in the pool. @dev this is called fairly frequently since compounding is not automatic: in UniV3, all fees must be manually withdrawn. */ function burnCollectPositions() internal { uint128 mL = positionLiquidity(mainPosition); uint128 rL = positionLiquidity(rangePosition); if (0 < mL) { activePool.burn(mainPosition.tickLower, mainPosition.tickUpper, mL); activePool.collect( address(this), mainPosition.tickLower, mainPosition.tickUpper, type(uint128).max, type(uint128).max ); } if (0 < rL) { activePool.burn(rangePosition.tickLower, rangePosition.tickUpper, rL); activePool.collect( address(this), rangePosition.tickLower, rangePosition.tickUpper, type(uint128).max, type(uint128).max ); } } /** @notice in contrast to `burnCollectPositions`, this only burns a portion of liqudity, used for when a user withdraws tokens from the vault. @param position Storage pointer to position @param tick Current tick @param shares User shares to burn @param _totalSupply totalSupply of Lixir vault tokens */ function burnAndCollect( Position storage position, int24 tick, uint256 shares, uint256 _totalSupply ) internal returns (uint256 amount0Out, uint256 amount1Out) { int24 tickLower = position.tickLower; int24 tickUpper = position.tickUpper; /* * N.B. that tokensOwed{0,1} here are calculated prior to burning, * and so should only contain tokensOwed from fees and never tokensOwed from a burn */ (uint128 liquidity, uint256 tokensOwed0, uint256 tokensOwed1) = liquidityAndTokensOwed(tick, tickLower, tickUpper); uint128 LDelta = FullMath.mulDiv(shares, liquidity, _totalSupply).toUint128(); amount0Out = FullMath.mulDiv(tokensOwed0, shares, _totalSupply); amount1Out = FullMath.mulDiv(tokensOwed1, shares, _totalSupply); if (0 < LDelta) { (uint256 burnt0Out, uint256 burnt1Out) = activePool.burn(tickLower, tickUpper, LDelta); amount0Out = amount0Out.add(burnt0Out); amount1Out = amount1Out.add(burnt1Out); } if (0 < amount0Out || 0 < amount1Out) { activePool.collect( address(this), tickLower, tickUpper, amount0Out.toUint128(), amount1Out.toUint128() ); } } /// @dev internal readonly getters and pure helper functions /** * @dev Calculates shares and amounts to deposit from amounts desired, TVL of vault, and totalSupply of vault tokens * @param amount0Desired Amount of token 0 desired by user * @param amount1Desired Amount of token 1 desired by user * @param total0 Total amount of token 0 available to activePool * @param total1 Total amount of token 1 available to activePool * @param _totalSupply Total supply of vault tokens * @return shares Shares of activePool to mint to user * @return amount0In Actual amount of token0 user should deposit into activePool * @return amount1In Actual amount of token1 user should deposit into activePool */ function calcSharesAndAmounts( uint256 amount0Desired, uint256 amount1Desired, uint256 total0, uint256 total1, uint256 _totalSupply ) internal pure returns ( uint256 shares, uint256 amount0In, uint256 amount1In ) { (bool roundedSharesFrom0, uint256 sharesFrom0) = 0 < total0 ? mulDivRoundingUp(amount0Desired, _totalSupply, total0) : (false, 0); (bool roundedSharesFrom1, uint256 sharesFrom1) = 0 < total1 ? mulDivRoundingUp(amount1Desired, _totalSupply, total1) : (false, 0); uint8 realSharesOffsetFor0 = roundedSharesFrom0 ? 1 : 2; uint8 realSharesOffsetFor1 = roundedSharesFrom1 ? 1 : 2; if ( realSharesOffsetFor0 < sharesFrom0 && (total1 == 0 || sharesFrom0 < sharesFrom1) ) { shares = sharesFrom0 - 1 - realSharesOffsetFor0; amount0In = amount0Desired; amount1In = FullMath.mulDivRoundingUp(sharesFrom0, total1, _totalSupply); LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount1In <= amount1Desired ); } else { LixirErrors.require_INSUFFICIENT_INPUT_AMOUNT( realSharesOffsetFor1 < sharesFrom1 ); shares = sharesFrom1 - 1 - realSharesOffsetFor1; amount0In = FullMath.mulDivRoundingUp(sharesFrom1, total0, _totalSupply); LixirErrors.require_INSUFFICIENT_OUTPUT_AMOUNT( amount0In <= amount0Desired ); amount1In = amount1Desired; } } function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (bool rounded, uint256 result) { result = FullMath.mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; rounded = true; } } /** * @dev Calculates shares, liquidity deltas, and amounts in for initial deposit * @param amount0Desired Amount of token 0 desired by user * @param amount1Desired Amount of token 1 desired by user * @return shares Initial shares to mint * @return mLDelta Liquidity delta for main position * @return amount0In Amount of token 0 to transfer from user * @return amount1In Amount of token 1 to transfer from user */ function calculateInitialDeposit( uint256 amount0Desired, uint256 amount1Desired ) internal view returns ( uint256 shares, uint128 mLDelta, uint256 amount0In, uint256 amount1In ) { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); uint160 sqrtRatioLowerX96 = TickMath.getSqrtRatioAtTick(mainPosition.tickLower); uint160 sqrtRatioUpperX96 = TickMath.getSqrtRatioAtTick(mainPosition.tickUpper); mLDelta = LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, sqrtRatioLowerX96, sqrtRatioUpperX96, amount0Desired, amount1Desired ); LixirErrors.require_INSUFFICIENT_INPUT_AMOUNT(0 < mLDelta); (amount0In, amount1In) = getAmountsForLiquidity( sqrtRatioX96, sqrtRatioLowerX96, sqrtRatioUpperX96, mLDelta.toInt128() ); shares = mLDelta; } /** * @dev Queries activePool for current square root price and current tick * @return _sqrtRatioX96 Current square root price * @return _tick Current tick */ function getSqrtRatioX96AndTick() internal view returns (uint160 _sqrtRatioX96, int24 _tick) { (_sqrtRatioX96, _tick, , , , , ) = activePool.slot0(); } /** * @dev Calculates tokens owed for a position * @param realTick Current tick * @param tickLower Lower tick of position * @param tickUpper Upper tick of position * @param feeGrowthInside0LastX128 Last fee growth of token0 between tickLower and tickUpper * @param feeGrowthInside1LastX128 Last fee growth of token0 between tickLower and tickUpper * @param liquidity Liquidity of position for which tokens owed is being calculated * @param tokensOwed0Last Last tokens owed to position * @param tokensOwed1Last Last tokens owed to position * @return tokensOwed0 Amount of token0 owed to position * @return tokensOwed1 Amount of token1 owed to position */ function calculateTokensOwed( int24 realTick, int24 tickLower, int24 tickUpper, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 liquidity, uint128 tokensOwed0Last, uint128 tokensOwed1Last ) internal view returns (uint128 tokensOwed0, uint128 tokensOwed1) { /* * V3 doesn't use SafeMath here, so we don't either * This could of course result in a dramatic forfeiture of fees. The reality though is * we rebalance far frequently enough for this to never happen in any realistic scenario. * This has no difference from the v3 implementation, and was copied from contracts/libraries/Position.sol */ (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInsideTicks(realTick, tickLower, tickUpper); tokensOwed0 = uint128( tokensOwed0Last + FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ) ); tokensOwed1 = uint128( tokensOwed1Last + FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ) ); } function _positionDataHelper( int24 realTick, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { ( liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 ) = activePool.positions( PositionKey.compute(address(this), tickLower, tickUpper) ); if (liquidity == 0) { return ( 0, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 ); } (tokensOwed0, tokensOwed1) = calculateTokensOwed( realTick, tickLower, tickUpper, feeGrowthInside0LastX128, feeGrowthInside1LastX128, liquidity, tokensOwed0, tokensOwed1 ); } /** * @dev Queries and calculates liquidity and tokens owed * @param tick Current tick * @param tickLower Lower tick of position * @param tickUpper Upper tick of position * @return liquidity Liquidity of position for which tokens owed is being calculated * @return tokensOwed0 Amount of token0 owed to position * @return tokensOwed1 Amount of token1 owed to position */ function liquidityAndTokensOwed( int24 tick, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, , , tokensOwed0, tokensOwed1) = _positionDataHelper( tick, tickLower, tickUpper ); } function calculateTotals() external view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { (uint160 sqrtRatioX96, int24 tick) = getSqrtRatioX96AndTick(); return _calculateTotals( sqrtRatioX96, tick, DepositPositionData(0, mainPosition.tickLower, mainPosition.tickUpper), DepositPositionData(0, rangePosition.tickLower, rangePosition.tickUpper) ); } /** * @notice This variant is so that tick TWAP's may be used by other protocols to calculate * totals, allowing them to safeguard themselves from manipulation. This would be useful if * Lixir vault tokens were used as collateral in a lending protocol. * @param virtualTick Tick at which to calculate amounts from liquidity */ function calculateTotalsFromTick(int24 virtualTick) external view override returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(virtualTick); (, int24 realTick) = getSqrtRatioX96AndTick(); return _calculateTotalsFromTick( sqrtRatioX96, realTick, DepositPositionData(0, mainPosition.tickLower, mainPosition.tickUpper), DepositPositionData(0, rangePosition.tickLower, rangePosition.tickUpper) ); } /** * @dev Helper function for calculating totals * @param sqrtRatioX96 *Current or virtual* sqrtPriceX96 * @param realTick Current tick, for calculating tokensOwed correctly * @param mainData Main position data * @param rangeData Range position data * N.B realTick must be provided because tokensOwed calculation needs * the current correct tick because the ticks are only updated upon the * crossing of ticks * sqrtRatioX96 can be a current sqrtPriceX96 *or* a sqrtPriceX96 calculated * from a virtual tick, for external consumption */ function _calculateTotalsFromTick( uint160 sqrtRatioX96, int24 realTick, DepositPositionData memory mainData, DepositPositionData memory rangeData ) internal view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { (mL, total0, total1) = calculatePositionTotals( realTick, sqrtRatioX96, mainData.tickLower, mainData.tickUpper ); { uint256 rt0; uint256 rt1; (rL, rt0, rt1) = calculatePositionTotals( realTick, sqrtRatioX96, rangeData.tickLower, rangeData.tickUpper ); total0 = total0.add(rt0); total1 = total1.add(rt1); } total0 = total0.add(token0.balanceOf(address(this))); total1 = total1.add(token1.balanceOf(address(this))); } function _calculateTotals( uint160 sqrtRatioX96, int24 tick, DepositPositionData memory mainData, DepositPositionData memory rangeData ) internal view returns ( uint256 total0, uint256 total1, uint128 mL, uint128 rL ) { return _calculateTotalsFromTick(sqrtRatioX96, tick, mainData, rangeData); } /** * @dev Calculates total tokens obtainable and liquidity of a given position (fees + amounts in position) * total{0,1} is sum of tokensOwed{0,1} from each position plus sum of liquidityForAmount{0,1} for each position plus vault balance of token{0,1} * @param realTick Current tick (for calculating tokensOwed) * @param sqrtRatioX96 Current (or virtual) square root price * @param tickLower Lower tick of position * @param tickLower Upper tick of position * @return liquidity Liquidity of position * @return total0 Total amount of token0 obtainable from position * @return total1 Total amount of token1 obtainable from position */ function calculatePositionTotals( int24 realTick, uint160 sqrtRatioX96, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint256 total0, uint256 total1 ) { uint256 tokensOwed0; uint256 tokensOwed1; ( liquidity, total0, total1, tokensOwed0, tokensOwed1 ) = calculatePositionInfo(realTick, sqrtRatioX96, tickLower, tickUpper); total0 = total0.add(tokensOwed0); total1 = total1.add(tokensOwed1); } function calculatePositionInfo( int24 realTick, uint160 sqrtRatioX96, int24 tickLower, int24 tickUpper ) internal view returns ( uint128 liquidity, uint256 total0, uint256 total1, uint256 tokensOwed0, uint256 tokensOwed1 ) { uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; ( liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1 ) = _positionDataHelper(realTick, tickLower, tickUpper); uint160 sqrtPriceLower = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtPriceUpper = TickMath.getSqrtRatioAtTick(tickUpper); (uint256 amount0, uint256 amount1) = getAmountsForLiquidity( sqrtRatioX96, sqrtPriceLower, sqrtPriceUpper, liquidity.toInt128() ); } /** * @dev Calculates fee growth between a tick range * @param tick Current tick * @param tickLower Lower tick of range * @param tickUpper Upper tick of range * @return feeGrowthInside0X128 Fee growth of token 0 inside ticks * @return feeGrowthInside1X128 Fee growth of token 1 inside ticks */ function getFeeGrowthInsideTicks( int24 tick, int24 tickLower, int24 tickUpper ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { /* * Underflow is Good here, actually. * Uniswap V3 doesn't use SafeMath here, and the cases where it does underflow, * it should help us get back to the rightful fee growth value of our position. * It would underflow only when feeGrowthGlobal{0,1}X128 has overflowed already in the V3 contract. * It should never underflow if feeGrowthGlobal{0,1}X128 hasn't yet overflowed. * Of course, if feeGrowthGlobal{0,1}X128 has overflowed twice over or more, we cannot possibly recover * fees from the overflow before last via underflow here, and it is possible our feeGrowthOutside values are * insufficently large to underflow enough to recover fees from the most recent overflow. * But, we rebalance frequently, so this should never be an issue. * This math is no different than in the v3 activePool contract and was copied from contracts/libraries/Tick.sol */ uint256 feeGrowthGlobal0X128 = activePool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = activePool.feeGrowthGlobal1X128(); ( , , uint256 feeGrowthOutside0X128Lower, uint256 feeGrowthOutside1X128Lower, , , , ) = activePool.ticks(tickLower); ( , , uint256 feeGrowthOutside0X128Upper, uint256 feeGrowthOutside1X128Upper, , , , ) = activePool.ticks(tickUpper); // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tick >= tickLower) { feeGrowthBelow0X128 = feeGrowthOutside0X128Lower; feeGrowthBelow1X128 = feeGrowthOutside1X128Lower; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - feeGrowthOutside0X128Lower; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - feeGrowthOutside1X128Lower; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tick < tickUpper) { feeGrowthAbove0X128 = feeGrowthOutside0X128Upper; feeGrowthAbove1X128 = feeGrowthOutside1X128Upper; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - feeGrowthOutside0X128Upper; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - feeGrowthOutside1X128Upper; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } /** * @dev Queries position liquidity * @param position Storage pointer to position we want to query */ function positionLiquidity(Position storage position) internal view returns (uint128 _liquidity) { (_liquidity, , , , ) = activePool.positions( PositionKey.compute(address(this), position.tickLower, position.tickUpper) ); } function getAmountsForLiquidity( uint160 sqrtPriceX96, uint160 sqrtPriceX96Lower, uint160 sqrtPriceX96Upper, int128 liquidityDelta ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtPriceX96 <= sqrtPriceX96Lower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = SqrtPriceMath .getAmount0Delta(sqrtPriceX96Lower, sqrtPriceX96Upper, liquidityDelta) .abs(); } else if (sqrtPriceX96 < sqrtPriceX96Upper) { amount0 = SqrtPriceMath .getAmount0Delta(sqrtPriceX96, sqrtPriceX96Upper, liquidityDelta) .abs(); amount1 = SqrtPriceMath .getAmount1Delta(sqrtPriceX96Lower, sqrtPriceX96, liquidityDelta) .abs(); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = SqrtPriceMath .getAmount1Delta(sqrtPriceX96Lower, sqrtPriceX96Upper, liquidityDelta) .abs(); } } /// @inheritdoc IUniswapV3MintCallback function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata ) external virtual override { require(msg.sender == address(activePool)); if (amount0Owed > 0) { TransferHelper.safeTransfer(address(token0), msg.sender, amount0Owed); } if (amount1Owed > 0) { TransferHelper.safeTransfer(address(token1), msg.sender, amount1Owed); } } } // File: LixirVaultETH.sol contract LixirVaultETH is LixirVault, ILixirVaultETH { using SafeMath for uint256; using SafeCast for uint256; IWETH9 public immutable weth9; TOKEN public override WETH_TOKEN; constructor(address _registry) LixirVault(_registry) { weth9 = LixirRegistry(_registry).weth9(); } function initialize( string memory name, string memory symbol, address _token0, address _token1, address _strategist, address _keeper, address _strategy ) public override(LixirVault, ILixirVault) initializer { LixirVault.initialize( name, symbol, _token0, _token1, _strategist, _keeper, _strategy ); TOKEN _WETH_TOKEN; if (_token0 == address(weth9)) { _WETH_TOKEN = TOKEN.ZERO; } else { require(_token1 == address(weth9)); _WETH_TOKEN = TOKEN.ONE; } WETH_TOKEN = _WETH_TOKEN; } /** @notice equivalent to `deposit` except logic is configured for ETH instead of ERC20 payments. @param amountDesired amount of ERC20 token desired by caller @param amountEthMin minimum amount of ETH desired by caller @param amountMin minimum amount of ERC20 token desired by caller @param recipient The address for which the liquidity will be created @param deadline Blocktimestamp that this must execute before @return shares @return amountEthIn how much ETH was actually deposited @return amountIn how much the ERC20 token was actually deposited */ function depositETH( uint256 amountDesired, uint256 amountEthMin, uint256 amountMin, address recipient, uint256 deadline ) external payable override whenNotPaused notExpired(deadline) returns ( uint256 shares, uint256 amountEthIn, uint256 amountIn ) { TOKEN _WETH_TOKEN = WETH_TOKEN; if (_WETH_TOKEN == TOKEN.ZERO) { (shares, amountEthIn, amountIn) = _depositETH( _WETH_TOKEN, msg.value, amountDesired, amountEthMin, amountMin, recipient, deadline ); } else { (shares, amountIn, amountEthIn) = _depositETH( _WETH_TOKEN, amountDesired, msg.value, amountMin, amountEthMin, recipient, deadline ); } } function _depositETH( TOKEN _WETH_TOKEN, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address recipient, uint256 deadline ) internal returns ( uint256 shares, uint256 amount0In, uint256 amount1In ) { uint256 amountEthDesired = msg.value; DepositPositionData memory mainData; DepositPositionData memory rangeData; uint256 total0; uint256 total1; ( mainData, rangeData, shares, amount0In, amount1In, total0, total1 ) = _depositStepOne( amount0Desired, amount1Desired, amount0Min, amount1Min, recipient ); if (_WETH_TOKEN == TOKEN.ZERO) { if (0 < amount0In) { weth9.deposit{value: amount0In}(); } if (0 < amount1In) { TransferHelper.safeTransferFrom( address(token1), msg.sender, address(this), amount1In ); } } else { if (0 < amount0In) { TransferHelper.safeTransferFrom( address(token0), msg.sender, address(this), amount0In ); } if (0 < amount1In) { weth9.deposit{value: amount1In}(); } } _depositStepTwo( mainData, rangeData, recipient, shares, amount0In, amount1In, total0, total1 ); Address.sendValue(msg.sender, address(this).balance); } /** @notice withdraws the desired shares from the vault @dev same as `withdraw` except this can be called from an `approve`d address @param withdrawer the address to withdraw from @param shares number of shares to withdraw @param amountEthMin amount of ETH desired by user @param amountMin Minimum amount of ERC20 token desired by user @param recipient address to recieve ETH and ERC20 withdrawals @param deadline blocktimestamp that this must execute by @return amountEthOut how much ETH was actually withdrawn @return amountOut how much ERC20 token was actually withdrawn */ function withdrawETHFrom( address withdrawer, uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external override canSpend(withdrawer, shares) returns (uint256 amountEthOut, uint256 amountOut) { TOKEN _WETH_TOKEN = WETH_TOKEN; uint256 amount0Min; uint256 amount1Min; if (_WETH_TOKEN == TOKEN.ZERO) { amount0Min = amountEthMin; amount1Min = amountMin; (amountEthOut, amountOut) = _withdrawETH( _WETH_TOKEN, withdrawer, shares, amount0Min, amount1Min, recipient, deadline ); } else { amount0Min = amountMin; amount1Min = amountEthMin; (amountOut, amountEthOut) = _withdrawETH( _WETH_TOKEN, withdrawer, shares, amount0Min, amount1Min, recipient, deadline ); } } /** @notice withdraws the desired shares from the vault @param shares number of shares to withdraw @param amountEthMin amount of ETH desired by user @param amountMin Minimum amount of ERC20 token desired by user @param recipient address to recieve ETH and ERC20 withdrawals @param deadline blocktimestamp that this must execute by @return amountEthOut how much ETH was actually withdrawn @return amountOut how much ERC20 token was actually withdrawn */ function withdrawETH( uint256 shares, uint256 amountEthMin, uint256 amountMin, address payable recipient, uint256 deadline ) external override returns (uint256 amountEthOut, uint256 amountOut) { TOKEN _WETH_TOKEN = WETH_TOKEN; uint256 amount0Min; uint256 amount1Min; if (_WETH_TOKEN == TOKEN.ZERO) { amount0Min = amountEthMin; amount1Min = amountMin; (amountEthOut, amountOut) = _withdrawETH( _WETH_TOKEN, msg.sender, shares, amount0Min, amount1Min, recipient, deadline ); } else { amount0Min = amountMin; amount1Min = amountEthMin; (amountOut, amountEthOut) = _withdrawETH( _WETH_TOKEN, msg.sender, shares, amount0Min, amount1Min, recipient, deadline ); } } function _withdrawETH( TOKEN _WETH_TOKEN, address withdrawer, uint256 shares, uint256 amount0Min, uint256 amount1Min, address payable recipient, uint256 deadline ) internal notExpired(deadline) returns (uint256 amount0Out, uint256 amount1Out) { (amount0Out, amount1Out) = _withdrawStep( withdrawer, shares, amount0Min, amount1Min, recipient ); if (_WETH_TOKEN == TOKEN.ZERO) { if (0 < amount0Out) { weth9.withdraw(amount0Out); Address.sendValue(recipient, amount0Out); } if (0 < amount1Out) { TransferHelper.safeTransfer(address(token1), recipient, amount1Out); } } else { if (0 < amount1Out) { TransferHelper.safeTransfer(address(token0), recipient, amount0Out); } if (0 < amount1Out) { weth9.withdraw(amount1Out); Address.sendValue(recipient, amount1Out); } } } receive() external payable override { require(msg.sender == address(weth9)); } }
Silence state mutability warning without generating bytecode. See https:github.com/ethereum/solidity/issues/10090issuecomment-741789128 and https:github.com/ethereum/solidity/issues/2691 solhint-disable-next-line no-inline-assembly
function _getChainId() private view returns (uint256 chainId) { this; assembly { chainId := chainid() } }
327,156
./partial_match/4/0xa5d9C34950DB1199BE5b7f8C0e5C13b7471af00B/sources/GenesisPool.sol
重写了TopTokenWrapper的stake方法,加入了一些约束合约精度为18 require(amount.add(balanceOf(msg.sender)) <= 100000000000000000000, "Cannot stake more than 100");更新数组,如果是刚加入的时候积分肯定为0初始化积分有效期
function stake(uint256 amount) public calBonus { require(amount.add(balanceOf(msg.sender)) >= 1000000000000000000, "Cannot stake less than 1"); require(amount % 1000000000000000000 == 0, "Cannot stake float coin"); super.stake(amount); if(points[msg.sender]==0){ ownerAddress.push(msg.sender); pointFreshTime[msg.sender] = block.timestamp; } points[msg.sender] = points[msg.sender].add(amount.div(1000000000000000000)); emit Staked(msg.sender, amount); }
8,522,787
./full_match/1/0x51b898efAf8366b494b917d51839a4E015DCde3A/sources/lib/geb/src/single/CollateralAuctionHouse.sol
Settle/finish an auction id ID of the auction to settle/
function settleAuction(uint256 id) external { require(bids[id].bidExpiry != 0 && (bids[id].bidExpiry < now || bids[id].auctionDeadline < now), "EnglishCollateralAuctionHouse/not-finished"); safeEngine.transferCollateral(collateralType, address(this), bids[id].highBidder, bids[id].amountToSell); liquidationEngine.removeCoinsFromAuction(bids[id].amountToRaise); delete bids[id]; emit SettleAuction(id); }
8,439,159
/** *Submitted for verification at Etherscan.io on 2021-09-04 */ /** *Submitted for verification at Etherscan.io on 2021-09-01 */ // SPDX-License-Identifier: UNLICENSED 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; } } /** * @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); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev 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); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } 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); } /** * @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 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 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); } contract FirstGold is Context, Ownable, ERC20 { // first contract is available at https://etherscan.io/address/0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7 address public firstContractAddress = 0xc9Cb0FEe73f060Db66D2693D92d75c825B1afdbF; IERC721Enumerable public firstContract; // Give out 10,000 First Gold for every first Bag that a user holds uint256 public FirstGoldPerTokenId = 10000 * (10**decimals()); // tokenIdStart of 1 is First on the following lines in the first contract: /** function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } */ uint256 public tokenIdStart = 1; // tokenIdEnd of 8000 is First on the following lines in the first contract: /** function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 7777 && tokenId < 8001, "Token ID invalid"); _safeMint(owner(), tokenId); } */ uint256 public tokenIdEnd = 8000; // Seasons are used to allow users to claim tokens regularly. Seasons are // decided by the DAO. uint256 public season = 0; // Track claimed tokens within a season // IMPORTANT: The format of the mapping is: // claimedForSeason[season][tokenId][claimed] mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId; constructor() Ownable() ERC20("First Gold", "BGLD") { // Transfer ownership to the first DAO // Ownable by OpenZeppelin automatically sets owner to msg.sender, but // we're going to be using a separate wallet for deployment transferOwnership(_msgSender()); firstContract = IERC721Enumerable(firstContractAddress); } /// @notice Claim First Gold for a given first ID /// @param tokenId The tokenId of the first NFT function claimById(uint256 tokenId) external { // Follow the Checks-Effects-Interactions pattern to prevent reentrancy // attacks // Checks // Check that the msgSender owns the token that is being claimed require( _msgSender() == firstContract.ownerOf(tokenId), "MUST_OWN_TOKEN_ID" ); // Further Checks, Effects, and Interactions are contained within the // _claim() function _claim(tokenId, _msgSender()); } /// @notice Claim First Gold for all tokens owned by the sender /// @notice This function will run out of gas if you have too much first! If /// this is a concern, you should use claimRangeForOwner and claim First /// Gold in batches. function claimAllForOwner() external { uint256 tokenBalanceOwner = firstContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed for (uint256 i = 0; i < tokenBalanceOwner; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( firstContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } /// @notice Claim First Gold for all tokens owned by the sender within a /// given range /// @notice This function is useful if you own too much first to claim all at /// once or if you want to leave some first unclaimed. If you leave first /// unclaimed, however, you cannot claim it once the next season starts. function claimRangeForOwner(uint256 ownerIndexStart, uint256 ownerIndexEnd) external { uint256 tokenBalanceOwner = firstContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // We use < for ownerIndexEnd and tokenBalanceOwner because // tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed require( ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE" ); // i <= ownerIndexEnd because ownerIndexEnd is 0-indexed for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( firstContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } /// @dev Internal function to mint first upon claiming function _claim(uint256 tokenId, address tokenOwner) internal { // Checks // Check that the token ID is in range // We use >= and <= to here because all of the token IDs are 0-indexed require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_OF_RANGE" ); // Check that First Gold have not already been claimed this season // for a given tokenId require( !seasonClaimedByTokenId[season][tokenId], "GOLD_CLAIMED_FOR_TOKEN_ID" ); // Effects // Mark that First Gold has been claimed for this season for the // given tokenId seasonClaimedByTokenId[season][tokenId] = true; // Interactions // Send First Gold to the owner of the token ID _mint(tokenOwner, FirstGoldPerTokenId); } /// @notice Allows the DAO to mint new tokens for use within the first /// Ecosystem /// @param amountDisplayValue The amount of first to mint. This should be /// input as the display value, not in raw decimals. If you want to mint /// 100 first, you should enter "100" rather than the value of 100 * 10^18. function daoMint(uint256 amountDisplayValue) external onlyOwner { _mint(owner(), amountDisplayValue * (10**decimals())); } /// @notice Allows the DAO to set a new contract address for first. This is /// relevant in the event that first migrates to a new contract. /// @param firstContractAddress_ The new contract address for first function daoSetfirstContractAddress(address firstContractAddress_) external onlyOwner { firstContractAddress = firstContractAddress_; firstContract = IERC721Enumerable(firstContractAddress); } /// @notice Allows the DAO to set the token IDs that are eligible to claim /// first /// @param tokenIdStart_ The start of the eligible token range /// @param tokenIdEnd_ The end of the eligible token range /// @dev This is relevant in case a future first contract has a different /// total supply of first function daoSetTokenIdRange(uint256 tokenIdStart_, uint256 tokenIdEnd_) external onlyOwner { tokenIdStart = tokenIdStart_; tokenIdEnd = tokenIdEnd_; } /// @notice Allows the DAO to set a season for new First Gold claims /// @param season_ The season to use for claiming first function daoSetSeason(uint256 season_) public onlyOwner { season = season_; } /// @notice Allows the DAO to set the amount of First Gold that is /// claimed per token ID /// @param FirstGoldDisplayValue The amount of first a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 first, you should enter "100" rather than the value of /// 100 * 10^18. function daoSetFirstGoldPerTokenId(uint256 FirstGoldDisplayValue) public onlyOwner { FirstGoldPerTokenId = FirstGoldDisplayValue * (10**decimals()); } /// @notice Allows the DAO to set the season and First Gold per token ID /// in one transaction. This ensures that there is not a gap where a user /// can claim more First Gold than others /// @param season_ The season to use for claiming first /// @param FirstGoldDisplayValue The amount of first a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 first, you should enter "100" rather than the value of /// 100 * 10^18. /// @dev We would save a tiny amount of gas by modifying the season and /// FirstGold variables directly. It is better practice for security, /// however, to avoid repeating code. This function is so rarely used that /// it's not worth moving these values into their own internal function to /// skip the gas used on the modifier check. function daoSetSeasonAndFirstGoldPerTokenID( uint256 season_, uint256 FirstGoldDisplayValue ) external onlyOwner { daoSetSeason(season_); daoSetFirstGoldPerTokenId(FirstGoldDisplayValue); } }
Allows the DAO to set a season for new First Gold claims season_ The season to use for claiming first
function daoSetSeason(uint256 season_) public onlyOwner { season = season_; }
124,231
./full_match/1/0xDd5097FC3f68958649cE70F42B7c1CF0067a3545/sources/cache/solpp-generated-contracts/Storage.sol
Return accept record hash for fast withdraw
function getFastWithdrawHash(uint32 accountIdOfNonce, uint8 subAccountIdOfNonce, uint32 nonce, address owner, uint16 tokenId, uint128 amount, uint16 fastWithdrawFeeRate) internal pure returns (bytes32) { return keccak256(abi.encodePacked(accountIdOfNonce, subAccountIdOfNonce, nonce, owner, tokenId, amount, fastWithdrawFeeRate)); }
16,530,461
pragma solidity 0.5.3; /** * @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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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); } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract SecretaryRole { using Roles for Roles.Role; event SecretaryAdded(address indexed account); event SecretaryRemoved(address indexed account); Roles.Role private _secretaries; constructor () internal { _addSecretary(msg.sender); } modifier onlySecretary() { require(isSecretary(msg.sender), "SecretaryRole: caller does not have the Secretary role"); _; } function isSecretary(address account) public view returns (bool) { return _secretaries.has(account); } function addSecretary(address account) public onlySecretary { _addSecretary(account); } function renounceSecretary() public { _removeSecretary(msg.sender); } function _addSecretary(address account) internal { _secretaries.add(account); emit SecretaryAdded(account); } function _removeSecretary(address account) internal { _secretaries.remove(account); emit SecretaryRemoved(account); } } contract DigitalSecretary is SecretaryRole { using SafeMath for uint256; uint256 public entityFilings; // tallies number of successful entity registration calls uint256 public filingFeeAmount; // filing fee amount adjustable by secretary / default wei amount: "50000000000000000000" address public feeTokenAddress; // fee token address for paying filing and other administration fees / default testnet: "0x8ad3aa5d5ff084307d28c8f514d7a193b2bfe725" address public secretary; // administrator of digital secretary contract address public treasuryAddress; // receives filing and other administrative fees generated by digital secretary mapping (uint256 => Entity) public entities; // mapping registered entities to filing numbers event entityRegistered(uint256 fileNumber, uint256 filingDate, string entityName, uint8 entityKind, bool domestic); struct Entity { uint256 fileNumber; // latest successful registration function call uint256 filingDate; // blocktime of successful registration function call string entityName; // Full Legal Name / e.g., "ACME LLC" uint8 entityKind; // see below enum / default, '3' - "LLC" uint8 entityType; // see below enum / default, '1' - "General" bool domestic; // default "true" string registeredAgentdetails; // could be IPFS hash, plaintext, or JSON detailing registered agent string filingDetails; // could be IPFS hash, plaintext, or JSON detailing articles or certificate of incorporation uint256 feesPaid; // running tally of fees paid to digital secretary by registered entity bool goodStanding; // default "true" on successful registration function call } // compare: Delaware resource: https://icis.corp.delaware.gov/Ecorp/FieldDesc.aspx#ENTITY%20TYPE enum Kind { CORP, LP, LLC, TRUST, PARTNERSHIP, UNPA } // compare: Delaware resource: https://icis.corp.delaware.gov/Ecorp/FieldDesc.aspx#ENTITY%20TYPE enum Type { GENERAL, BANK, CLOSED, DISC, PA, GP, RIC, LLP, NT, NP, STOCK } /** * @dev Sets the initial values for `filingFeeAmount`, `feeTokenAddress`, `treasuryAddress`. */ constructor (uint256 _filingFeeAmount, address _feeTokenAddress, address _treasuryAddress) public { filingFeeAmount = _filingFeeAmount; feeTokenAddress = _feeTokenAddress; secretary = msg.sender; treasuryAddress = _treasuryAddress; } // public function to register entity with digital secretary function registerEntity( string memory entityName, uint8 entityKind, uint8 entityType, bool domestic, string memory registeredAgentdetails, string memory filingDetails) public { IERC20 feeToken = IERC20(feeTokenAddress); require(feeToken.transferFrom(msg.sender, address(secretary), filingFeeAmount)); Kind(entityKind); Type(entityType); uint256 fileNumber = entityFilings.add(1); // tallies from running total uint256 filingDate = block.timestamp; // "now" uint256 feesPaid = filingFeeAmount; // pushes fee amount to entity tally bool goodStanding = true; // default value for new entity entityFilings = entityFilings.add(1); // tallies new filing to running total entities[fileNumber] = Entity( fileNumber, filingDate, entityName, entityKind, entityType, domestic, registeredAgentdetails, filingDetails, feesPaid, goodStanding); emit entityRegistered(fileNumber, filingDate, entityName, entityKind, domestic); } /*************** TREASURY MGMT ***************/ // digital secretary can update entity filing fee amount function updateFilingFee(uint256 _filingFeeAmount) public onlySecretary { filingFeeAmount = _filingFeeAmount; } // digital secretary can update entity fee token address function updateFeeTokenAddress(address _feeTokenAddress) public onlySecretary { feeTokenAddress = _feeTokenAddress; } // digital secretary can update treasury address function updateTreasuryAddress(address _treasuryAddress) public onlySecretary { treasuryAddress = _treasuryAddress; } /*************** ENTITY MGMT ***************/ // digital secretary can update entity name function updateEntityName(uint256 fileNumber, string memory newName) public onlySecretary { Entity storage entity = entities[fileNumber]; entity.entityName = newName; } // digital secretary can update registered agent details function updateRegisteredAgent(uint256 fileNumber, string memory registeredAgentdetails) public onlySecretary { Entity storage entity = entities[fileNumber]; entity.registeredAgentdetails = registeredAgentdetails; } // digital secretary can convert entity kind function convertEntityKind(uint256 fileNumber, uint8 newKind) public onlySecretary { Entity storage entity = entities[fileNumber]; entity.entityKind = newKind; } // digital secretary can convert entity type function convertEntityType(uint256 fileNumber, uint8 newType) public onlySecretary { Entity storage entity = entities[fileNumber]; entity.entityType = newType; } // digital secretary can convert entity domicile function convertEntityDomicile(uint256 fileNumber, bool domestic) public onlySecretary { Entity storage entity = entities[fileNumber]; entity.domestic = domestic; } // digital secretary can convert entity standing function convertEntityStanding(uint256 fileNumber, bool goodStanding) public onlySecretary { Entity storage entity = entities[fileNumber]; entity.goodStanding = goodStanding; } }
digital secretary can convert entity type
function convertEntityType(uint256 fileNumber, uint8 newType) public onlySecretary { Entity storage entity = entities[fileNumber]; entity.entityType = newType; }
12,550,536
./partial_match/1/0xc8024fB5C7beD98CcE0e498E54B7D89816B3521B/sources/GenesisLiquidityPool.sol
Swaps Collateral for GEX. Mints a percentage of the amount of GEX tokens as new supply.
function mintSwap(uint256 inCollatAmount, uint256 minOutGEXAmount) external virtual whenMintNotPaused { uint256 outGEXAmount = amountOutGEX(inCollatAmount); uint256 fee = amountFeeMint(outGEXAmount); require(outGEXAmount - fee >= minOutGEXAmount, "Max slippage"); uint256 amountMinted = amountMint(outGEXAmount); balanceFees += fee; balanceCollateral += inCollatAmount; balanceGEX += amountMinted; balanceGEX -= outGEXAmount; mintedGEX += _toInt256(amountMinted); _updateOracle(outGEXAmount); outGEXAmount -= fee; require(collateral.transferFrom(msg.sender, address(this), inCollatAmount)); if (outGEXAmount == amountMinted) GEX.mint(msg.sender, amountMinted); else { GEX.mint(address(this), amountMinted); require(GEX.transfer(msg.sender, outGEXAmount)); } }
3,668,737
/* SPDX-License-Identifier: LGPL-3.0-or-later */ pragma solidity ^0.7.0; import "./Admin.sol"; import "./CarefulMath.sol"; import "./Erc20.sol"; import "./Erc20Interface.sol"; import "./Erc20Permit.sol"; import "./Erc20Recover.sol"; import "./ReentrancyGuard.sol"; import "./BalanceSheetInterface.sol"; import "./FintrollerInterface.sol"; import "./FyTokenInterface.sol"; import "./RedemptionPool.sol"; /** * @title FyToken * @author Hifi * @notice Zero-coupon bond that tracks an Erc20 underlying asset. */ contract FyToken is ReentrancyGuard, /* no depedency */ FyTokenInterface, /* one dependency */ Admin, /* two dependencies */ Exponential, /* two dependencies */ Erc20, /* three dependencies */ Erc20Permit, /* five dependencies */ Erc20Recover /* five dependencies */ { modifier isVaultOpen(address account) { require(balanceSheet.isVaultOpen(this, account), "ERR_VAULT_NOT_OPEN"); _; } /** * @notice The fyToken always has 18 decimals. * @dev Instantiates the Redemption Pool. * @param name_ Erc20 name of this token. * @param symbol_ Erc20 symbol of this token. * @param expirationTime_ Unix timestamp in seconds for when this token expires. * @param fintroller_ The address of the Fintroller contract. * @param balanceSheet_ The address of the BalanceSheet contract. * @param underlying_ The contract address of the underlying asset. * @param collateral_ The contract address of the collateral asset. */ constructor( string memory name_, string memory symbol_, uint256 expirationTime_, FintrollerInterface fintroller_, BalanceSheetInterface balanceSheet_, Erc20Interface underlying_, Erc20Interface collateral_ ) Erc20Permit(name_, symbol_, 18) Admin() { uint8 defaultNumberOfDecimals = 18; /* Set the underlying contract and calculate the decimal scalar offsets. */ uint256 underlyingDecimals = underlying_.decimals(); require(underlyingDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_ZERO"); require(underlyingDecimals <= defaultNumberOfDecimals, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_OVERFLOW"); underlyingPrecisionScalar = 10**(defaultNumberOfDecimals - underlyingDecimals); underlying = underlying_; /* Set the collateral contract and calculate the decimal scalar offsets. */ uint256 collateralDecimals = collateral_.decimals(); require(collateralDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_ZERO"); require(defaultNumberOfDecimals >= collateralDecimals, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_OVERFLOW"); collateralPrecisionScalar = 10**(defaultNumberOfDecimals - collateralDecimals); collateral = collateral_; /* Set the unix expiration time. */ require(expirationTime_ > block.timestamp, "ERR_FYTOKEN_CONSTRUCTOR_EXPIRATION_TIME_NOT_VALID"); expirationTime = expirationTime_; /* Set the Fintroller contract and sanity check it. */ fintroller = fintroller_; fintroller.isFintroller(); /* Set the Balance Sheet contract and sanity check it. */ balanceSheet = balanceSheet_; balanceSheet.isBalanceSheet(); /* Create the Redemption Pool contract and transfer the owner from the fyToken itself to the current caller. */ redemptionPool = new RedemptionPool(fintroller_, this); AdminInterface(address(redemptionPool))._transferAdmin(msg.sender); } /** * CONSTANT FUNCTIONS */ /** * @notice Checks if the bond matured. * @return bool true = bond matured, otherwise it didn't. */ function isMatured() public view override returns (bool) { return block.timestamp >= expirationTime; } /** * NON-CONSTANT FUNCTIONS */ struct BorrowLocalVars { MathError mathErr; uint256 debt; uint256 debtCeiling; uint256 lockedCollateral; uint256 hypotheticalCollateralizationRatioMantissa; uint256 hypotheticalTotalSupply; uint256 newDebt; uint256 thresholdCollateralizationRatioMantissa; } /** * @notice Increases the debt of the caller and mints new fyToken. * * @dev Emits a {Borrow}, {Mint} and {Transfer} event. * * Requirements: * * - The vault must be open. * - Must be called prior to maturation. * - The amount to borrow cannot be zero. * - The Fintroller must allow this action to be performed. * - The locked collateral cannot be zero. * - The total supply of fyTokens cannot exceed the debt ceiling. * - The caller must not fall below the threshold collateralization ratio. * * @param borrowAmount The amount of fyTokens to borrow and print into existence. * @return bool true = success, otherwise it reverts. */ function borrow(uint256 borrowAmount) public override isVaultOpen(msg.sender) nonReentrant returns (bool) { BorrowLocalVars memory vars; /* Checks: bond not matured. */ require(isMatured() == false, "ERR_BOND_MATURED"); /* Checks: the zero edge case. */ require(borrowAmount > 0, "ERR_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getBorrowAllowed(this), "ERR_BORROW_NOT_ALLOWED"); /* Checks: debt ceiling. */ (vars.mathErr, vars.hypotheticalTotalSupply) = addUInt(totalSupply, borrowAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR"); vars.debtCeiling = fintroller.getBondDebtCeiling(this); require(vars.hypotheticalTotalSupply <= vars.debtCeiling, "ERR_BORROW_DEBT_CEILING_OVERFLOW"); /* Add the borrow amount to the borrower account's current debt. */ (vars.debt, , vars.lockedCollateral, ) = balanceSheet.getVault(this, msg.sender); require(vars.lockedCollateral > 0, "ERR_BORROW_LOCKED_COLLATERAL_ZERO"); (vars.mathErr, vars.newDebt) = addUInt(vars.debt, borrowAmount); require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR"); /* Checks: the hypothetical collateralization ratio is above the threshold. */ vars.hypotheticalCollateralizationRatioMantissa = balanceSheet.getHypotheticalCollateralizationRatio( this, msg.sender, vars.lockedCollateral, vars.newDebt ); vars.thresholdCollateralizationRatioMantissa = fintroller.getBondCollateralizationRatio(this); require( vars.hypotheticalCollateralizationRatioMantissa >= vars.thresholdCollateralizationRatioMantissa, "ERR_BELOW_COLLATERALIZATION_RATIO" ); /* Effects: print the new fyTokens into existence. */ mintInternal(msg.sender, borrowAmount); /* Emit a Transfer event. */ emit Transfer(address(this), msg.sender, borrowAmount); /* Interactions: increase the debt of the borrower account. */ require(balanceSheet.setVaultDebt(this, msg.sender, vars.newDebt), "ERR_BORROW_CALL_SET_VAULT_DEBT"); /* Emit a Borrow event. */ emit Borrow(msg.sender, borrowAmount); return true; } /** * @notice Destroys `burnAmount` tokens from `holder`, reducing the token supply. * * @dev Emits a {Burn} and a {Transfer} event. * * Requirements: * * - Must be called prior to maturation. * - Can only be called by the Redemption Pool. * - The amount to burn cannot be zero. * * @param holder The account whose fyTokens to burn. * @param burnAmount The amount of fyTokens to burn. * @return bool true = success, otherwise it reverts. */ function burn(address holder, uint256 burnAmount) external override nonReentrant returns (bool) { /* Checks: the caller is the Redemption Pool. */ require(msg.sender == address(redemptionPool), "ERR_BURN_NOT_AUTHORIZED"); /* Checks: the zero edge case. */ require(burnAmount > 0, "ERR_BURN_ZERO"); /* Effects: burns the fyTokens. */ burnInternal(holder, burnAmount); /* Emit a Transfer event. */ emit Transfer(holder, address(this), burnAmount); return true; } struct LiquidateBorrowsLocalVars { MathError mathErr; uint256 collateralizationRatioMantissa; uint256 lockedCollateral; bool isAccountUnderwater; } /** * @notice Repays the debt of the borrower and rewards the caler with a surplus of collateral. * * @dev Emits a {RepayBorrow}, {Transfer}, {ClutchCollateral} and {LiquidateBorrow} event. * * Requirements: * * - The vault must be open. * - The liquidator cannot liquidate themselves. * - The amount to repay cannot be zero. * - The Fintroller must allow this action to be performed. * - The borrower must be underwater if the bond didn't mature. * - The caller must have at least `repayAmount` fyTokens. * - The borrower must have at least `repayAmount` debt. * - The amount of clutched collateral cannot be more than what the borrower has in the vault. * * @param borrower The account to liquidate. * @param repayAmount The amount of fyTokens to repay. * @return bool true = success, otherwise it reverts. */ function liquidateBorrow(address borrower, uint256 repayAmount) external override isVaultOpen(borrower) nonReentrant returns (bool) { LiquidateBorrowsLocalVars memory vars; /* Checks: borrowers cannot self liquidate. */ require(msg.sender != borrower, "ERR_LIQUIDATE_BORROW_SELF"); /* Checks: the zero edge case. */ require(repayAmount > 0, "ERR_LIQUIDATE_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getLiquidateBorrowAllowed(this), "ERR_LIQUIDATE_BORROW_NOT_ALLOWED"); /* After maturation, any vault can be liquidated, irrespective of collateralization ratio. */ if (isMatured() == false) { /* Checks: the borrower fell below the threshold collateralization ratio. */ vars.isAccountUnderwater = balanceSheet.isAccountUnderwater(this, borrower); require(vars.isAccountUnderwater, "ERR_ACCOUNT_NOT_UNDERWATER"); } /* Effects & Interactions: repay the borrower's debt. */ repayBorrowInternal(msg.sender, borrower, repayAmount); /* Interactions: clutch the collateral. */ uint256 clutchableCollateralAmount = balanceSheet.getClutchableCollateral(this, repayAmount); require( balanceSheet.clutchCollateral(this, msg.sender, borrower, clutchableCollateralAmount), "ERR_LIQUIDATE_BORROW_CALL_CLUTCH_COLLATERAL" ); emit LiquidateBorrow(msg.sender, borrower, repayAmount, clutchableCollateralAmount); return true; } /** /** @notice Prints new tokens into existence and assigns them to `beneficiary`, * increasing the total supply. * * @dev Emits a {Mint} and a {Transfer} event. * * Requirements: * * - Can only be called by the Redemption Pool. * - The amount to mint cannot be zero. * * @param beneficiary The borrower account for which to mint the tokens. * @param mintAmount The amount of fyTokens to print into existence. * @return bool true = success, otherwise it reverts. */ function mint(address beneficiary, uint256 mintAmount) external override nonReentrant returns (bool) { /* Checks: the caller is the Redemption Pool. */ require(msg.sender == address(redemptionPool), "ERR_MINT_NOT_AUTHORIZED"); /* Checks: the zero edge case. */ require(mintAmount > 0, "ERR_MINT_ZERO"); /* Effects: print the new fyTokens into existence. */ mintInternal(beneficiary, mintAmount); /* Emit a Transfer event. */ emit Transfer(address(this), beneficiary, mintAmount); return true; } /** * @notice Deletes the borrower account's debt from the registry and take the fyTokens * out of circulation. * * @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event. * * Requirements: * * - The vault must be open. * - The amount to repay cannot be zero. * - The Fintroller must allow this action to be performed. * - The caller must have at least `repayAmount` fyTokens. * - The caller must have at least `repayAmount` debt. * * @param repayAmount The amount of fyTokens to repay. * @return bool true = success, otherwise it reverts. */ function repayBorrow(uint256 repayAmount) external override isVaultOpen(msg.sender) nonReentrant returns (bool) { repayBorrowInternal(msg.sender, msg.sender, repayAmount); return true; } /** * @notice Clears the borrower account's debt from the registry and take the fyTokens * out of circulation. * * @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event. * * Requirements: same as the `repayBorrow` function, but here `borrower` is the account that must * have at least `repayAmount` fyTokens to repay the borrow. * * @param borrower The borrower account for which to repay the borrow. * @param repayAmount The amount of fyTokens to repay. * @return bool true = success, otherwise it reverts. */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external override isVaultOpen(borrower) nonReentrant returns (bool) { repayBorrowInternal(msg.sender, borrower, repayAmount); return true; } /** * @notice Updates the Fintroller contract's address saved in storage. * * @dev Throws a {SetFintroller} event. * * Requirements: * * - The caller must be the admin. * - The new Fintroller must pass the inspection. * * @param newFintroller The address of the new Fintroller contract. * @return bool true = success, otherwise it reverts. */ function _setFintroller(FintrollerInterface newFintroller) external override onlyAdmin returns (bool) { /* Checks: sanity check the new Fintroller contract. */ require(newFintroller.isFintroller(), "ERR_SET_FINTROLLER_INSPECTION"); /* Effects: update storage. */ FintrollerInterface oldFintroller = fintroller; fintroller = newFintroller; emit SetFintroller(admin, oldFintroller, newFintroller); return true; } /** * INTERNAL FUNCTIONS */ /** * @dev See the documentation for the public functions that call this internal function. */ function repayBorrowInternal( address payer, address borrower, uint256 repayAmount ) internal { /* Checks: the zero edge case. */ require(repayAmount > 0, "ERR_REPAY_BORROW_ZERO"); /* Checks: the Fintroller allows this action to be performed. */ require(fintroller.getRepayBorrowAllowed(this), "ERR_REPAY_BORROW_NOT_ALLOWED"); /* Checks: borrower has a debt to pay. */ uint256 debt = balanceSheet.getVaultDebt(this, borrower); require(debt >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_DEBT"); /* Checks: the payer has enough fyTokens. */ require(balanceOf(payer) >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_BALANCE"); /* Effects: burn the fyTokens. */ burnInternal(payer, repayAmount); /* Emit a Transfer event. */ emit Transfer(payer, address(this), repayAmount); /* Calculate the new debt of the borrower. */ MathError mathErr; uint256 newDebt; (mathErr, newDebt) = subUInt(debt, repayAmount); /* This operation can't fail because of the previous `require`. */ assert(mathErr == MathError.NO_ERROR); /* Interactions: reduce the debt of the borrower . */ require(balanceSheet.setVaultDebt(this, borrower, newDebt), "ERR_REPAY_BORROW_CALL_SET_VAULT_DEBT"); /* Emit both a RepayBorrow event. */ emit RepayBorrow(payer, borrower, repayAmount, newDebt); } }
Deletes the borrower account's debt from the registry and take the fyTokens out of circulation. Emits a {Burn}, {Transfer} and {RepayBorrow} event. Requirements: - The vault must be open. - The amount to repay cannot be zero. - The Fintroller must allow this action to be performed. - The caller must have at least `repayAmount` fyTokens. - The caller must have at least `repayAmount` debt. repayAmount The amount of fyTokens to repay. return bool true = success, otherwise it reverts./
function repayBorrow(uint256 repayAmount) external override isVaultOpen(msg.sender) nonReentrant returns (bool) { repayBorrowInternal(msg.sender, msg.sender, repayAmount); return true; }
14,900,291
./partial_match/42/0x7dFdB85E6775E3082Ec30298Fa3a46c9Dfdf7b7a/sources/ThirdContract.sol
&& anx.balanceOf(address(0)) > 0 anx.transferFrom(address(this), msg.sender, decimalValue);
function giveANXToUser(uint256 value) public { uint256 decimalValue = value * 100; require( usdt.allowance(msg.sender, address(this)) >= decimalValue && usdt.allowance(msg.sender, address(this)) > 0 ); usdt.transferFrom(msg.sender, address(this), decimalValue); }
9,091,633
contract NoxonFund { address public owner; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; //18160ddd for rpc call https://api.etherscan.io/api?module=proxy&data=0x18160ddd&to=0xContractAdress&apikey={eserscan api}&action=eth_call uint256 public Entropy; uint256 public ownbalance; //d9c7041b uint256 public sellPrice; //4b750334 uint256 public buyPrice; //8620410b /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* Initializes cont ract with initial supply tokens to the creator of the contract */ function token() { if (owner!=0) throw; buyPrice = msg.value; balanceOf[msg.sender] = 1; // Give the creator all initial tokens totalSupply = 1; // Update total supply Entropy = 1; name = 'noxonfund.com'; // Set the name for display purposes symbol = '? SHARE'; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes owner = msg.sender; setPrices(); } /* Send shares function */ function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } function setPrices() { ownbalance = this.balance; //own contract balance sellPrice = ownbalance/totalSupply; buyPrice = sellPrice*2; } function () returns (uint buyreturn) { uint256 amount = msg.value / buyPrice; // calculates the amount balanceOf[msg.sender] += amount; // adds the amount to buyer's balance totalSupply += amount; Entropy += amount; Transfer(0, msg.sender, amount); owner.send(msg.value/2); //set next price setPrices(); return buyPrice; } function sell(uint256 amount) { setPrices(); if (balanceOf[msg.sender] < amount ) throw; // checks if the sender has enough to sell Transfer(msg.sender, this, amount); //return shares to contract totalSupply -= amount; balanceOf[msg.sender] -= amount; // subtracts the amount from seller's balance msg.sender.send(amount * sellPrice); // sends ether to the seller setPrices(); } //All incomse will send using newIncome method event newincomelog(uint amount,string description); function newIncome( string JobDescription ) returns (string result) { if (msg.value <= 1 ether/100) throw; newincomelog(msg.value,JobDescription); return JobDescription; } //some democracy uint votecount; uint voteno; uint voteyes; mapping (address => uint256) public voters; function newProposal( string JobDescription ) returns (string result) { if (msg.sender == owner) { votecount = 0; newProposallog(JobDescription); return "ok"; } else { return "Only admin can do this"; } } function ivote(bool myposition) returns (uint result) { votecount += balanceOf[msg.sender]; if (voters[msg.sender]>0) throw; voters[msg.sender]++; votelog(myposition,msg.sender,balanceOf[msg.sender]); return votecount; } event newProposallog(string description); event votelog(bool position, address voter, uint sharesonhand); }
This creates an array with all balances / This generates a public event on the blockchain that will notify clients / Initializes cont ract with initial supply tokens to the creator of the contract /
function token() { if (owner!=0) throw; buyPrice = msg.value; Entropy = 1; owner = msg.sender; setPrices(); }
13,032,781
/* https://t.me/CryptoListingOfficial https://cryptolisting.com/ https://twitter.com/cryptolisting_ https://www.reddit.com/r/cryptolistingcom/ https://cryptolisting.medium.com/ // SPDX-License-Identifier: MIT */ pragma solidity ^0.8.4; 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); } // pragma solidity >=0.6.2; 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; } 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; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns(uint256); } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); } /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. 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. */ /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } // File: contracts/SafeMathUint.sol /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } // File: contracts/SafeMath.sol 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: contracts/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/Ownable.sol contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } /** * @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 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0xcb3451ed0BA9d1A3306351e7B8EFcC8A34e9F846), _msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/DividendPayingToken.sol /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; // Need to make gas fee customizable to future-proof against Ethereum network upgrades. uint256 public gasForTransfer; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { gasForTransfer = 3000; } /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public override payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value: _withdrawableDividend, gas: gasForTransfer}(""); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @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 virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @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 override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } contract CLISTINGDividendTracker is DividendPayingToken, Ownable { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 10000 * (10**18); // Must hold 10000+ tokens. event ExcludedFromDividends(address indexed account); event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("CLISTING_Dividend_Tracker", "CLISTING_Dividend_Tracker") { claimWait = 3600; } function _transfer(address, address, uint256) internal pure override { require(false, "CLISTING_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "CLISTING_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main CLISTING contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludedFromDividends(account); } function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner { require(newGasForTransfer != gasForTransfer, "CLISTING_Dividend_Tracker: Cannot update gasForTransfer to same value"); emit GasForTransferUpdated(newGasForTransfer, gasForTransfer); gasForTransfer = newGasForTransfer; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "CLISTING_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "CLISTING_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if (index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if (excludedFromDividends[account]) { return; } if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } } contract CLISTING is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private liquidating; CLISTINGDividendTracker public dividendTracker; address public liquidityWallet; address payable public buyBackWalletAddress; address payable public operationWalletAddress; address payable public charityWalletAddress; uint256 public maxTxnAmount = 3000000 * (10**18); uint256 private ethRewardFee = 4; uint256 private buyBackFee = 4; uint256 private devOpsFee = 4; uint256 public buyBackDevOpsTotalFee = buyBackFee + devOpsFee; uint256 public totalFees = ethRewardFee + buyBackDevOpsTotalFee; bool _swapEnabled = false; bool _maxBuyEnabled = true; bool buyBackEnabled = true; bool teamFeeEnabled = true; bool ethRewardFeeEnabled = true; // use by default 150,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 150000; // liquidate tokens for ETH when the contract reaches 100k tokens by default uint256 public liquidateTokensAtAmount = 100000 * (10**18); // whether the token can already be traded bool public tradingEnabled; bool public walletsRegistered; function activate() external onlyOwner { require(walletsRegistered, "CLISTING: Taxes wallets not yet registered"); require(!tradingEnabled, "CLISTING: Trading is already enabled"); _swapEnabled = true; tradingEnabled = true; } function updateTax(uint256 _ethRewardFee, uint256 _buyBackFee, uint256 _devOpsFee) external onlyOwner { ethRewardFee = _ethRewardFee; buyBackFee = _buyBackFee; devOpsFee = _devOpsFee; buyBackDevOpsTotalFee = buyBackFee + devOpsFee; totalFees = ethRewardFee + buyBackDevOpsTotalFee; } function updateMaxBuySellAmount(uint256 _maxBuySellAmount) external onlyOwner { uint256 updatedMaxBuySellAmount = _maxBuySellAmount * (10**18); maxTxnAmount = updatedMaxBuySellAmount; } function enableDisableTaxflags(bool _buyBackEnabled, bool _teamFeeEnabled, bool _ethRewardFeeEnabled) external onlyOwner { buyBackEnabled = _buyBackEnabled; teamFeeEnabled = _teamFeeEnabled; ethRewardFeeEnabled = _ethRewardFeeEnabled; } function registerWallets(address payable _buyBackWalletAddress, address payable _operationWalletAddress, address payable _charityWalletAddress) external onlyOwner { buyBackWalletAddress = _buyBackWalletAddress; operationWalletAddress = _operationWalletAddress; charityWalletAddress = _charityWalletAddress; walletsRegistered = true; } function updateRegisteredWallets(address payable _buyBackWalletAddr, address payable _operationWalletAddr, address payable _charityWalletAddr) external onlyOwner { require(_buyBackWalletAddr != address(0), "ERC20: transfer from the zero address"); require(_operationWalletAddr != address(0), "ERC20: transfer from the zero address"); require(_charityWalletAddr != address(0), "ERC20: transfer from the zero address"); if(_buyBackWalletAddr != buyBackWalletAddress) { buyBackWalletAddress = _buyBackWalletAddr; } if(_operationWalletAddr != operationWalletAddress) { operationWalletAddress = _operationWalletAddr; } if(_charityWalletAddr != charityWalletAddress) { charityWalletAddress = _charityWalletAddr; } } // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; // addresses that can make transfers before presale is over mapping (address => bool) public canTransferBeforeTradingIsEnabled; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Liquified( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapAndSendToDev( uint256 tokensSwapped, uint256 ethReceived ); event SentDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); constructor() ERC20("CryptolistingDotCom", "CLISTING") { dividendTracker = new CLISTINGDividendTracker(); liquidityWallet = owner(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD)); dividendTracker.excludeFromDividends(address(0xa57075df283Bf2dC9b2C8e066113b2dcE111B2e2)); // Manual Burn Wallet // exclude from paying fees or having max transaction amount excludeFromFees(liquidityWallet); excludeFromFees(address(this)); // enable owner wallet to send tokens before presales are over. canTransferBeforeTradingIsEnabled[owner()] = true; /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), 1000000000 * (10**18)); } function doConstructorStuff() external onlyOwner { } receive() external payable { } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "CLISTING: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "CLISTING: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function excludeFromFees(address account) public onlyOwner { require(!_isExcludedFromFees[account], "CLISTING: Account is already excluded from fees"); _isExcludedFromFees[account] = true; } function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner { dividendTracker.updateGasForTransfer(gasForTransfer); } function allowTransferBeforeTradingIsEnabled(address account) public onlyOwner { require(!canTransferBeforeTradingIsEnabled[account], "CLISTING: Account is already allowed to transfer before trading is enabled"); canTransferBeforeTradingIsEnabled[account] = true; } function updateGasForProcessing(uint256 newValue) public onlyOwner { // Need to make gas fee customizable to future-proof against Ethereum network upgrades. require(newValue != gasForProcessing, "CLISTING: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getGasForTransfer() external view returns(uint256) { return dividendTracker.gasForTransfer(); } function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){ require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee"); _swapEnabled = _devFeeEnabled; return(_swapEnabled); } function setMaxBuyEnabled(bool enabled ) external onlyOwner { _maxBuyEnabled = enabled; } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool tradingIsEnabled = tradingEnabled; if(from != owner() && to != owner() && _maxBuyEnabled) { require(amount <= maxTxnAmount, "Transfer amount exceeds the maxTxAmount."); } // only whitelisted addresses can make transfers before the public presale is over. if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "CLISTING: This account cannot send tokens until trading is enabled"); } if (amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if (tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(buyBackDevOpsTotalFee).div(totalFees); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(totalFees).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch { } if (!liquidating) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndSendToDev(uint256 tokens) private { uint256 tokenBalance = tokens; // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); sendEthToDev(newBalance); emit SwapAndSendToDev(tokens, newBalance); } function sendEthToDev(uint256 amount) private { if(!buyBackEnabled && teamFeeEnabled) { operationWalletAddress.transfer(amount); } if(!teamFeeEnabled && buyBackEnabled) { buyBackWalletAddress.transfer(amount); } if(teamFeeEnabled && buyBackEnabled) { buyBackWalletAddress.transfer(amount.div(2)); operationWalletAddress.transfer(amount.div(2)); } if( !teamFeeEnabled && !buyBackEnabled && amount != 0 ) { // Send the taxes to _charityWallet just in in case if there is any leakage charityWalletAddress.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), block.timestamp ); } function swapAndSendDividends(uint256 tokens) private { swapTokensForEth(tokens); uint256 dividends = address(this).balance; (bool success,) = address(dividendTracker).call{value: dividends}(""); if (success) { emit SentDividends(tokens, dividends); } } }
capture the contract's current ETH balance. this is so that we can capture exactly the amount of ETH that the swap creates, and not make the liquidity event include any ETH that has been manually sent to the contract swap tokens for ETH how much ETH did we just swap into?
function swapAndSendToDev(uint256 tokens) private { uint256 tokenBalance = tokens; uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); sendEthToDev(newBalance); emit SwapAndSendToDev(tokens, newBalance); }
107,848
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @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; } } // File: @openzeppelin/contracts/GSN/Context.sol 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 not 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, with should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address) { 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; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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/ERC20.sol pragma solidity ^0.5.0; /** * @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 value) public returns (bool) { _approve(_msgSender(), spender, value); 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 `value`. * - 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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(value, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(value); emit Transfer(account, address(0), value); } /** * @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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @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")); } } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.0; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: contracts/roles/AdminRole.sol pragma solidity ^0.5.6; contract AdminRole is WhitelistAdminRole { address[] private _adminList; function _addWhitelistAdmin(address account) internal { super._addWhitelistAdmin(account); _adminList.push(account); } function _removeWhitelistAdmin(address account) internal { require(_adminList.length > 1, "At lease 1 Admin"); super._removeWhitelistAdmin(account); uint256 s = getIndexOfAdmin(account); _adminList[s] = _adminList[_adminList.length - 1]; _adminList.pop(); } function getIndexOfAdmin(address account) public view returns(uint256) { uint256 s = 0; for (s; s < _adminList.length; s += 1) { if (account == _adminList[s]) return s; } return 0; } function getAdminList() public view onlyWhitelistAdmin returns(address[] memory) { return _adminList; } } // File: contracts/token/PausableToken.sol pragma solidity ^0.5.6; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract PausableToken is ERC20, AdminRole { /** * @dev Emitted when the pause is triggered by a whitelistAdmin (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a whitelistAdmin (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the whitelistAdmin 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 whitelistAdmin to pause, triggers stopped state. */ function pause() public onlyWhitelistAdmin whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a whitelistAdmin to unpause, returns to normal state. */ function unpause() public onlyWhitelistAdmin whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev set modifier is paused to transfer function * @param to address * @param value uint256 */ function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } /** * @dev set modifier is paused to transferFrom function * @param from address * @param to address * @param value uint256 */ function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } /** * @dev set modifier is paused to approve function * @param spender address * @param value uint256 */ function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } /** * @dev set modifier is paused to increaseAllowance function * @param spender address * @param addedValue uint256 */ function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } /** * @dev set modifier is paused to decreaseAllowance function * @param spender address * @param subtractedValue uint256 */ function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: contracts/erc/ERC1132.sol pragma solidity ^0.5.6; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract ERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); // /** // * @dev Locks a specified amount of tokens against an address, // * for a specified reason and time // * @param _reason The reason to lock tokens // * @param _amount Number of tokens to be locked // * @param _time Lock time in seconds // */ // function lock(bytes32 _reason, uint256 _amount, uint256 _time) // internal returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns tokens validity for a specified address for a specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensValidity(address _of, bytes32 _reason) public view returns (uint256 validity); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function lockBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _to adress to which tokens are to be extended lock * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(address _to, bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _to adress to which tokens are to be increased * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(address _to, bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: contracts/token/LockableToken.sol pragma solidity ^0.5.6; contract LockableToken is PausableToken, ERC1132 { /** * @dev Error messages for require statements */ string internal constant ALREADY_LOCKED = "Tokens already locked"; string internal constant NOT_LOCKED = "No tokens locked"; string internal constant AMOUNT_ZERO = "Amount can not be 0"; /** * @dev is msg.sender or shitelistadmin * @param _address address */ modifier isAdminOrSelf(address _address) { require(_address == msg.sender || isWhitelistAdmin(msg.sender), "tokens are unlockable by owner or admin"); _; } /** * @dev Returns tokens locked for a specified address for a specified reason * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { if (!locked[_of][_reason].claimed) amount = locked[_of][_reason].amount; } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) amount = locked[_of][_reason].amount; } /** * @dev Returns tokens validity for a specified address for a specified reason * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensValidity(address _of, bytes32 _reason) public view returns (uint256 validity) { validity = locked[_of][_reason].validity; } /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function lockBalanceOf(address _of) public view returns (uint256 amount) { amount = 0; uint256 i = 0; for ( i ; i < lockReason[_of].length; i++) { amount = amount.add(tokensLocked(_of, lockReason[_of][i])); } } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) //solium-disable-line amount = locked[_of][_reason].amount; } /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public isAdminOrSelf(_of) returns (uint256 unlockableTokens) { uint256 lockedTokens; uint256 i = 0; for ( i ; i < lockReason[_of].length; i++) { lockedTokens = tokensUnlockable(_of, lockReason[_of][i]); if (lockedTokens > 0) { unlockableTokens = unlockableTokens.add(lockedTokens); locked[_of][lockReason[_of][i]].claimed = true; emit Unlocked(_of, lockReason[_of][i], lockedTokens); } } if (unlockableTokens > 0) { _transfer(address(this), _of, unlockableTokens); } } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { uint256 i = 0; for ( i ; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Transfers and Locks a specified amount of tokens, * for a specified reason and time * @param _to adress to which tokens are to be transfered * @param _reason The reason to lock tokens * @param _amount Number of tokens to be transfered and locked * @param _time Lock time in seconds */ function transferWithLock(address _to, bytes32 _reason, uint256 _amount, uint256 _time) public onlyWhitelistAdmin returns (bool) { require(_to != address(0), "Zero address not allowed"); require(_amount != 0, AMOUNT_ZERO); require(tokensLocked(_to, _reason) == 0, ALREADY_LOCKED); require(balanceOf(msg.sender) > _amount); uint256 validUntil = now.add(_time); //solium-disable-line // not allowed duplicate reason for address if (locked[_to][_reason].amount == 0) lockReason[_to].push(_reason); _transfer(msg.sender, address(this), _amount); locked[_to][_reason] = LockToken(_amount, validUntil, false); emit Locked(_to, _reason, _amount, validUntil); return true; } /** * @dev Extends lock for a specified reason and time * @param _to adress to which tokens are to be extended lock * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(address _to, bytes32 _reason, uint256 _time) public onlyWhitelistAdmin returns (bool) { require(_to != address(0), "Zero address not allowed"); require(tokensLocked(_to, _reason) > 0, NOT_LOCKED); locked[_to][_reason].validity = locked[_to][_reason].validity.add(_time); emit Locked(_to, _reason, locked[_to][_reason].amount, locked[_to][_reason].validity); return true; } /** * @dev Increase number of tokens locked for a specified reason * @param _to adress to which tokens are to be increased * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(address _to, bytes32 _reason, uint256 _amount) public onlyWhitelistAdmin returns (bool) { require(_to != address(0), "Zero address not allowed"); require(tokensLocked(_to, _reason) > 0, NOT_LOCKED); _transfer(msg.sender, address(this), _amount); locked[_to][_reason].amount = locked[_to][_reason].amount.add(_amount); emit Locked(_to, _reason, locked[_to][_reason].amount, locked[_to][_reason].validity); return true; } /** * @dev get length of lockReason array * @param _of address */ function getSizeOfLockReason(address _of) public view returns (uint256) { return lockReason[_of].length; } } // File: contracts/token/StakingToken.sol pragma solidity ^0.5.6; /** * @title Staking Token (STK) * @author Alberto Cuesta Canada * @dev Implements a basic ERC20 staking token with incentive distribution. */ contract StakingToken is LockableToken { /** * @dev Emitted when user staked token. */ event Staked(address account, uint256 amount); /** * @dev Emitted when user unstaked token. */ event Unstaked(address account, uint256 amount); /** * @dev Emitted when user unstaked token. */ event validStakePeriod(uint256 _startTime, uint256 _duration, bool stakeFlag); /** * @dev We usually require to know who are all the stakeholders. */ address[] internal stakeholders; /** * @dev The stakes for each stakeholder. */ mapping(address => uint256) internal stakes; uint256 private secondsInterval; uint256 private validStakeDuration; uint256 private validStakeStartTime; bool private stakeFlag; /** * @dev Initializes the contract in stake state. * to the deployer. */ constructor () internal { secondsInterval = 60*60*24*7; // default : interval 7 days validStakeDuration = 32400; // default : 60*60*9 ( 9hours ) validStakeStartTime = now - validStakeDuration; //solium-disable-line stakeFlag = false; } // ---------- SET TIME ---------- modifier isvalidStakePeriod() { require(stakeFlag, "stake is disabled"); require(isAbleToStake(), "It's not valid time to stake"); //solium-disable-line _; } /** * @dev Set period of able to stake. (It is automatically set to the same day each week.) * @param _startTime uint256 available start time to set stake/unstake * @param _duration uint256 duration second to set stake/unstake */ function setvalidStakePeriod(uint256 _startTime, uint256 _duration) public onlyWhitelistAdmin returns (uint256, uint256){ validStakeStartTime = _startTime; validStakeDuration = _duration; stakeFlag = true; emit validStakePeriod(_startTime, _duration, stakeFlag); return stakePeriod(); } /** * @dev change the stakeFlag state. * @param _stakeFlag bool stakeFlag state */ function setStakeFlag(bool _stakeFlag) public onlyWhitelistAdmin returns (bool) { stakeFlag = _stakeFlag; return stakeFlag; } /** * @dev A method for check is able to stake */ function isAbleToStake() public view returns (bool){ if(!stakeFlag || now < validStakeStartTime) { //solium-disable-line return false; } uint256 validTime = now.sub(validStakeStartTime).mod(secondsInterval); //solium-disable-line return (validTime >= 0 && validTime < validStakeDuration); } /** * @dev A method for check period for stake */ function stakePeriod() public view returns (uint256 validStakePeriodStart, uint256 validStakePeriodEnd){ if(now < validStakeStartTime) { //solium-disable-line validStakePeriodStart = validStakeStartTime; validStakePeriodEnd = validStakePeriodStart.add(validStakeDuration); }else{ uint256 week = now.sub(validStakeStartTime).div(secondsInterval); //solium-disable-line if(isAbleToStake()){ validStakePeriodStart = validStakeStartTime.add(secondsInterval.mul(week)); }else{ validStakePeriodStart = validStakeStartTime.add(secondsInterval.mul(week.add(1))); } validStakePeriodEnd = validStakePeriodStart.add(validStakeDuration); } } // ---------- STAKES ---------- /** * @dev A method for a stakeholder to create a stake. * @param _stake The size of the stake to be created. */ function createStake(uint256 _stake) external isvalidStakePeriod { require(transfer(address(this), _stake), "Token transfer failed"); if(stakes[msg.sender] == 0) _addStakeholder(msg.sender); stakes[msg.sender] = stakes[msg.sender].add(_stake); emit Staked(msg.sender,_stake); } /** * @dev A method for a stakeholder to remove a stake. * @param _stake The size of the stake to be removed. */ function removeStake(uint256 _stake) external isvalidStakePeriod { require(_stake <= stakes[msg.sender], "insufficient stake balance"); stakes[msg.sender] = stakes[msg.sender].sub(_stake); if(stakes[msg.sender] == 0) _removeStakeholder(msg.sender); _transfer(address(this), msg.sender, _stake); emit Unstaked(msg.sender,_stake); } /** * @dev A method to retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return uint256 The amount of wei staked. */ function stakeOf(address _stakeholder) public view returns(uint256) { return stakes[_stakeholder]; } /** * @dev A method to the aggregated stakes from all stakeholders. * @return uint256 The aggregated stakes from all stakeholders. */ function totalStakes() public view returns(uint256) { uint256 _totalStakes = 0; uint256 s = 0; for ( s ; s < stakeholders.length; s += 1){ _totalStakes = _totalStakes.add(stakes[stakeholders[s]]); } return _totalStakes; } // ---------- STAKEHOLDERS ---------- /** * @dev A method to check if an address is a stakeholder. * @param _address The address to verify. * @return bool, uint256 Whether the address is a stakeholder, * and if so its position in the stakeholders array. */ function isStakeholder(address _address) public view returns(bool, uint256) { uint256 s = 0; for ( s ; s < stakeholders.length; s += 1){ if (_address == stakeholders[s]) return (true, s); } return (false, 0); } /** * @dev A method to add a stakeholder. * @param _stakeholder The stakeholder to add. */ function _addStakeholder(address _stakeholder) internal { (bool _isStakeholder, ) = isStakeholder(_stakeholder); if(!_isStakeholder) stakeholders.push(_stakeholder); } /** * @dev A method to remove a stakeholder. * @param _stakeholder The stakeholder to remove. */ function _removeStakeholder(address _stakeholder) internal { (bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder); if(_isStakeholder){ stakeholders[s] = stakeholders[stakeholders.length - 1]; stakeholders.pop(); } } /** * @dev A method to get stake holders */ function stakeholderList() external view returns (address[] memory) { return stakeholders; } } // File: contracts/HiblocksToken.sol pragma solidity ^0.5.6; contract HiblocksToken is ERC20Detailed, StakingToken { mapping(address => mapping(uint => bytes)) public memos; /** * @dev constructor to mint initial tokens * @param name string * @param symbol string * @param decimals uint8 * @param initialSupply uint256 */ constructor(string memory name, string memory symbol, uint8 decimals, uint256 initialSupply) public ERC20Detailed(name, symbol, decimals) { // Mint the initial supply require(initialSupply > 0, "initialSupply must be greater than zero."); _mint(_msgSender(), initialSupply * (10 ** uint256(decimals))); } /** * @dev Transfer token for a specified address with memo * @param to The address to transfer to. * @param value The amount to be transferred. * @param memo The memo to be saved. */ function transferWithMemo(address to, uint256 value, bytes memory memo) public returns (bool) { require(transfer(to, value), "Token transfer failed"); memos[to][block.number] = memo; return true; } /** * @dev Gets the memo of the specified address and block number. * @param addr The address to query the memo of. * @param blockNumber The block number to query the memo of. * @return An bytes representing the memo writed by the passed address. */ function memoOf(address addr, uint blockNumber) external view returns (bytes memory) { return(memos[addr][blockNumber]); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public onlyWhitelistAdmin { super._burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from the address. * * See {ERC20-_burnFrom}. */ function burnFrom(address addr, uint256 amount) public onlyWhitelistAdmin { super._burnFrom(addr, amount); } /** * @dev Returns total tokens held by an address (transferable + locked) * @param _addr The address to query the total balance of */ function totalBalanceOf(address _addr) external view returns (uint256 amount, uint256 token, uint256 locked, uint256 staked) { token = balanceOf(_addr); locked = lockBalanceOf(_addr); staked = stakeOf(_addr); amount = token.add(locked).add(staked); } }
---------- STAKES ---------- A method for a stakeholder to create a stake. _stake The size of the stake to be created./
function createStake(uint256 _stake) external isvalidStakePeriod { require(transfer(address(this), _stake), "Token transfer failed"); if(stakes[msg.sender] == 0) _addStakeholder(msg.sender); stakes[msg.sender] = stakes[msg.sender].add(_stake); emit Staked(msg.sender,_stake); }
5,500,715
pragma solidity 0.5.11; /** * @title OUSD Vault Contract * @notice The Vault contract stores assets. On a deposit, OUSD will be minted and sent to the depositor. On a withdrawal, OUSD will be burned and assets will be sent to the withdrawer. The Vault accepts deposits of interest form yield bearing strategies which will modify the supply of OUSD. * @author Origin Protocol Inc */ 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; } } 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; } } 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); } 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")); } } 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"); } } } 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, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } 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; } contract Governable { // Storage position of the owner and pendingOwner of the contract bytes32 private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a; //keccak256("OUSD.governor"); bytes32 private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db; //keccak256("OUSD.pending.governor"); event PendingGovernorshipTransfer( address indexed previousGovernor, address indexed newGovernor ); event GovernorshipTransferred( address indexed previousGovernor, address indexed newGovernor ); /** * @dev Initializes the contract setting the deployer as the initial Governor. */ constructor() internal { _setGovernor(msg.sender); emit GovernorshipTransferred(address(0), _governor()); } /** * @dev Returns the address of the current Governor. */ function governor() public view returns (address) { return _governor(); } function _governor() internal view returns (address governorOut) { bytes32 position = governorPosition; assembly { governorOut := sload(position) } } function _pendingGovernor() internal view returns (address pendingGovernor) { bytes32 position = pendingGovernorPosition; assembly { pendingGovernor := sload(position) } } /** * @dev Throws if called by any account other than the Governor. */ modifier onlyGovernor() { require(isGovernor(), "Caller is not the Governor"); _; } /** * @dev Returns true if the caller is the current Governor. */ function isGovernor() public view returns (bool) { return msg.sender == _governor(); } function _setGovernor(address newGovernor) internal { bytes32 position = governorPosition; assembly { sstore(position, newGovernor) } } function _setPendingGovernor(address newGovernor) internal { bytes32 position = pendingGovernorPosition; assembly { sstore(position, newGovernor) } } /** * @dev Transfers Governance of the contract to a new account (`newGovernor`). * Can only be called by the current Governor. Must be claimed for this to complete * @param _newGovernor Address of the new Governor */ function transferGovernance(address _newGovernor) external onlyGovernor { _setPendingGovernor(_newGovernor); emit PendingGovernorshipTransfer(_governor(), _newGovernor); } /** * @dev Claim Governance of the contract to a new account (`newGovernor`). * Can only be called by the new Governor. */ function claimGovernance() external { require( msg.sender == _pendingGovernor(), "Only the pending Governor can complete the claim" ); _changeGovernor(msg.sender); } /** * @dev Change Governance of the contract to a new account (`newGovernor`). * @param _newGovernor Address of the new Governor */ function _changeGovernor(address _newGovernor) internal { require(_newGovernor != address(0), "New Governor is address(0)"); emit GovernorshipTransferred(_governor(), _newGovernor); _setGovernor(_newGovernor); } } interface IBasicToken { function symbol() external view returns (string memory); function decimals() external view returns (uint8); } interface IMinMaxOracle { //Assuming 8 decimals function priceMin(string calldata symbol) external returns (uint256); function priceMax(string calldata symbol) external returns (uint256); } interface IViewMinMaxOracle { function priceMin(string calldata symbol) external view returns (uint256); function priceMax(string calldata symbol) external view returns (uint256); } interface IStrategy { /** * @dev Deposit the given asset to Lending platform. * @param _asset asset address * @param _amount Amount to deposit */ function deposit(address _asset, uint256 _amount) external returns (uint256 amountDeposited); /** * @dev Withdraw given asset from Lending platform */ function withdraw( address _recipient, address _asset, uint256 _amount ) external returns (uint256 amountWithdrawn); /** * @dev Returns the current balance of the given asset. */ function checkBalance(address _asset) external view returns (uint256 balance); /** * @dev Returns bool indicating whether strategy supports asset. */ function supportsAsset(address _asset) external view returns (bool); /** * @dev Liquidate all assets in strategy and return them to Vault. */ function liquidate() external; /** * @dev Get the APR for the Strategy. */ function getAPR() external view returns (uint256); /** * @dev Collect reward tokens from the Strategy. */ function collectRewardToken() external; } library Helpers { /** * @notice Fetch the `symbol()` from an ERC20 token * @dev Grabs the `symbol()` from a contract * @param _token Address of the ERC20 token * @return string Symbol of the ERC20 token */ function getSymbol(address _token) internal view returns (string memory) { string memory symbol = IBasicToken(_token).symbol(); return symbol; } /** * @notice Fetch the `decimals()` from an ERC20 token * @dev Grabs the `decimals()` from a contract and fails if * the decimal value does not live within a certain range * @param _token Address of the ERC20 token * @return uint256 Decimals of the ERC20 token */ function getDecimals(address _token) internal view returns (uint256) { uint256 decimals = IBasicToken(_token).decimals(); require( decimals >= 4 && decimals <= 18, "Token must have sufficient decimal places" ); return decimals; } } contract InitializableERC20Detailed 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. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @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; } } contract InitializableToken is ERC20, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract OUSD is Initializable, InitializableToken, Governable { using SafeMath for uint256; using StableMath for uint256; event TotalSupplyUpdated( uint256 totalSupply, uint256 totalCredits, uint256 creditsPerToken ); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private totalCredits; // Exchange rate between internal credits and OUSD uint256 private creditsPerToken; mapping(address => uint256) private _creditBalances; // Allowances denominated in OUSD mapping(address => mapping(address => uint256)) private _allowances; address public vaultAddress = address(0); function initialize( string calldata _nameArg, string calldata _symbolArg, address _vaultAddress ) external onlyGovernor initializer { InitializableToken._initialize(_nameArg, _symbolArg); _totalSupply = 0; totalCredits = 0; creditsPerToken = 1e18; vaultAddress = _vaultAddress; } /** * @dev Verifies that the caller is the Savings Manager contract */ modifier onlyVault() { require(vaultAddress == msg.sender, "Caller is not the Vault"); _; } /** * @return The total supply of OUSD. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _account The address to query the balance of. * @return A unit256 representing the _amount of base units owned by the * specified address. */ function balanceOf(address _account) public view returns (uint256) { if (creditsPerToken == 0) return 0; return _creditBalances[_account].divPrecisely(creditsPerToken); } /** * @dev Gets the credits balance of the specified address. * @param _account The address to query the balance of. * @return A uint256 representing the _amount of base units owned by the * specified address. */ function creditsBalanceOf(address _account) public view returns (uint256) { return _creditBalances[_account]; } /** * @dev Transfer tokens to a specified address. * @param _to the address to transfer to. * @param _value the _amount to be transferred. * @return true on success. */ function transfer(address _to, uint256 _value) public returns (bool) { uint256 creditValue = _removeCredits(msg.sender, _value); _creditBalances[_to] = _creditBalances[_to].add(creditValue); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another. * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value The _amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub( _value ); uint256 creditValue = _removeCredits(_from, _value); _creditBalances[_to] = _creditBalances[_to].add(creditValue); emit Transfer(_from, _to, _value); return true; } /** * @dev Function to check the _amount of tokens that an owner has allowed to a _spender. * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return The number of tokens still available for the _spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return _allowances[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified _amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @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) { _allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the _amount of tokens that an owner has allowed to a _spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @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) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender] .add(_addedValue); emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Decrease the _amount of tokens that an owner has allowed to a _spender. * @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) { uint256 oldValue = _allowances[msg.sender][_spender]; if (_subtractedValue >= oldValue) { _allowances[msg.sender][_spender] = 0; } else { _allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @notice Mints new tokens, increasing totalSupply. */ function mint(address _account, uint256 _amount) external onlyVault { return _mint(_account, _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), "Mint to the zero address"); _totalSupply = _totalSupply.add(_amount); uint256 creditAmount = _amount.mulTruncate(creditsPerToken); _creditBalances[_account] = _creditBalances[_account].add(creditAmount); totalCredits = totalCredits.add(creditAmount); emit Transfer(address(0), _account, _amount); } /** * @notice Burns tokens, decreasing totalSupply. */ function burn(address account, uint256 amount) external onlyVault { return _burn(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), "Burn from the zero address"); _totalSupply = _totalSupply.sub(_amount); uint256 creditAmount = _removeCredits(_account, _amount); totalCredits = totalCredits.sub(creditAmount); emit Transfer(_account, address(0), _amount); } /** * @dev Removes credits from a credit balance and burns rounding errors. * @param _account Account to remove credits from * @param _amount Amount in OUSD which will be converted to credits and * removed */ function _removeCredits(address _account, uint256 _amount) internal returns (uint256 creditAmount) { creditAmount = _amount.mulTruncate(creditsPerToken); uint256 currentCredits = _creditBalances[_account]; if ( currentCredits == creditAmount || currentCredits - 1 == creditAmount ) { _creditBalances[_account] = 0; } else if (currentCredits > creditAmount) { _creditBalances[_account] = currentCredits - creditAmount; } else { revert("Remove exceeds balance"); } } /** * @dev Modify the supply without minting new tokens. This uses a change in * the exchange rate between "credits" and OUSD tokens to change balances. * @param _newTotalSupply New total supply of OUSD. * @return uint256 representing the new total supply. */ function changeSupply(uint256 _newTotalSupply) external onlyVault returns (uint256) { require(_totalSupply > 0, "Cannot increase 0 supply"); if (_totalSupply == _newTotalSupply) { emit TotalSupplyUpdated( _totalSupply, totalCredits, creditsPerToken ); return _totalSupply; } _totalSupply = _newTotalSupply; if (_totalSupply > MAX_SUPPLY) _totalSupply = MAX_SUPPLY; creditsPerToken = totalCredits.divPrecisely(_totalSupply); emit TotalSupplyUpdated(_totalSupply, totalCredits, creditsPerToken); return _totalSupply; } } library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /*************************************** Helpers ****************************************/ /** * @dev Adjust the scale of an integer * @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17 */ function scaleBy(uint256 x, int8 adjustment) internal pure returns (uint256) { if (adjustment > 0) { x = x.mul(10**uint256(adjustment)); } else if (adjustment < 0) { x = x.div(10**uint256(adjustment * -1)); } return x; } /*************************************** Precise Arithmetic ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } } contract Vault is Initializable, Governable { using SafeMath for uint256; using StableMath for uint256; using SafeMath for int256; using SafeERC20 for IERC20; event AssetSupported(address _asset); event StrategyAdded(address _addr); event StrategyRemoved(address _addr); event Mint(address _addr, uint256 _value); event Redeem(address _addr, uint256 _value); event StrategyWeightsUpdated( address[] _strategyAddresses, uint256[] weights ); event DepositsPaused(); event DepositsUnpaused(); // Assets supported by the Vault, i.e. Stablecoins struct Asset { bool isSupported; } mapping(address => Asset) assets; address[] allAssets; // Strategies supported by the Vault struct Strategy { bool isSupported; uint256 targetWeight; // 18 decimals. 100% = 1e18 } mapping(address => Strategy) strategies; address[] allStrategies; // Address of the Oracle price provider contract address public priceProvider; // Pausing bools bool public rebasePaused = false; bool public depositPaused = true; // Redemption fee in basis points uint256 public redeemFeeBps; // Buffer of assets to keep in Vault to handle (most) withdrawals uint256 public vaultBuffer; // Mints over this amount automatically allocate funds. 18 decimals. uint256 public autoAllocateThreshold; // Mints over this amount automatically rebase. 18 decimals. uint256 public rebaseThreshold; OUSD oUSD; /** * @dev Verifies that the rebasing is not paused. */ modifier whenNotRebasePaused() { require(!rebasePaused, "Rebasing paused"); _; } /*************************************** Configuration ****************************************/ /** * @dev Set address of price provider. * @param _priceProvider Address of price provider */ function setPriceProvider(address _priceProvider) external onlyGovernor { priceProvider = _priceProvider; } /** * @dev Set a fee in basis points to be charged for a redeem. * @param _redeemFeeBps Basis point fee to be charged */ function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor { redeemFeeBps = _redeemFeeBps; } /** * @dev Set a buffer of assets to keep in the Vault to handle most * redemptions without needing to spend gas unwinding assets from a Strategy. * @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18. */ function setVaultBuffer(uint256 _vaultBuffer) external onlyGovernor { vaultBuffer = _vaultBuffer; } /** * @dev Sets the minimum amount of OUSD in a mint to trigger an * automatic allocation of funds afterwords. * @param _threshold OUSD amount with 18 fixed decimals. */ function setAutoAllocateThreshold(uint256 _threshold) external onlyGovernor { autoAllocateThreshold = _threshold; } /** * @dev Set a minimum amount of OUSD in a mint or redeem that triggers a * rebase * @param _threshold OUSD amount with 18 fixed decimals. */ function setRebaseThreshold(uint256 _threshold) external onlyGovernor { rebaseThreshold = _threshold; } /** @dev Add a supported asset to the contract, i.e. one that can be * to mint OUSD. * @param _asset Address of asset */ function supportAsset(address _asset) external onlyGovernor { require(!assets[_asset].isSupported, "Asset already supported"); assets[_asset] = Asset({ isSupported: true }); allAssets.push(_asset); emit AssetSupported(_asset); } /** * @dev Add a strategy to the Vault. * @param _addr Address of the strategy to add * @param _targetWeight Target percentage of asset allocation to strategy */ function addStrategy(address _addr, uint256 _targetWeight) external onlyGovernor { require(!strategies[_addr].isSupported, "Strategy already added"); strategies[_addr] = Strategy({ isSupported: true, targetWeight: _targetWeight }); allStrategies.push(_addr); emit StrategyAdded(_addr); } /** * @dev Remove a strategy from the Vault. Removes all invested assets and * returns them to the Vault. * @param _addr Address of the strategy to remove */ function removeStrategy(address _addr) external onlyGovernor { require(strategies[_addr].isSupported, "Strategy not added"); // Initialize strategyIndex with out of bounds result so function will // revert if no valid index found uint256 strategyIndex = allStrategies.length; for (uint256 i = 0; i < allStrategies.length; i++) { if (allStrategies[i] == _addr) { strategyIndex = i; break; } } assert(strategyIndex < allStrategies.length); allStrategies[strategyIndex] = allStrategies[allStrategies.length - 1]; allStrategies.length--; // Liquidate all assets IStrategy strategy = IStrategy(_addr); strategy.liquidate(); emit StrategyRemoved(_addr); } /** * @notice Set the weights for multiple strategies. * @param _strategyAddresses Array of strategy addresses * @param _weights Array of corresponding weights, with 18 decimals. * For ex. 100%=1e18, 30%=3e17. */ function setStrategyWeights( address[] calldata _strategyAddresses, uint256[] calldata _weights ) external onlyGovernor { require( _strategyAddresses.length == _weights.length, "Parameter length mismatch" ); for (uint256 i = 0; i < _strategyAddresses.length; i++) { strategies[_strategyAddresses[i]].targetWeight = _weights[i]; } emit StrategyWeightsUpdated(_strategyAddresses, _weights); } /*************************************** Core ****************************************/ /** * @dev Deposit a supported asset and mint OUSD. * @param _asset Address of the asset being deposited * @param _amount Amount of the asset being deposited */ function mint(address _asset, uint256 _amount) external { require(!depositPaused, "Deposits are paused"); require(assets[_asset].isSupported, "Asset is not supported"); require(_amount > 0, "Amount must be greater than 0"); uint256[] memory assetPrices; // For now we have to live with the +1 oracle call because we need to // know the priceAdjustedDeposit before we decide wether or not to grab // assets. This will not effect small non-rebase/allocate mints uint256 priceAdjustedDeposit = _amount.mulTruncateScale( IMinMaxOracle(priceProvider) .priceMin(Helpers.getSymbol(_asset)) .scaleBy(int8(10)), // 18-8 because oracles have 8 decimals precision 10**Helpers.getDecimals(_asset) ); if ( (priceAdjustedDeposit > rebaseThreshold && !rebasePaused) || (priceAdjustedDeposit >= autoAllocateThreshold) ) { assetPrices = _getAssetPrices(false); } // Rebase must happen before any transfers occur. if (priceAdjustedDeposit > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } // Transfer the deposited coins to the vault IERC20 asset = IERC20(_asset); asset.safeTransferFrom(msg.sender, address(this), _amount); // Mint matching OUSD oUSD.mint(msg.sender, priceAdjustedDeposit); emit Mint(msg.sender, priceAdjustedDeposit); if (priceAdjustedDeposit >= autoAllocateThreshold) { allocate(assetPrices); } } /** * @dev Mint for multiple assets in the same call. * @param _assets Addresses of assets being deposited * @param _amounts Amount of each asset at the same index in the _assets * to deposit. */ function mintMultiple( address[] calldata _assets, uint256[] calldata _amounts ) external { require(_assets.length == _amounts.length, "Parameter length mismatch"); uint256 priceAdjustedTotal = 0; uint256[] memory assetPrices = _getAssetPrices(false); for (uint256 i = 0; i < allAssets.length; i++) { for (uint256 j = 0; j < _assets.length; j++) { if (_assets[j] == allAssets[i]) { if (_amounts[j] > 0) { uint256 assetDecimals = Helpers.getDecimals( allAssets[i] ); priceAdjustedTotal += _amounts[j].mulTruncateScale( assetPrices[i], 10**assetDecimals ); } } } } // Rebase must happen before any transfers occur. if (priceAdjustedTotal > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } for (uint256 i = 0; i < _assets.length; i++) { IERC20 asset = IERC20(_assets[i]); asset.safeTransferFrom(msg.sender, address(this), _amounts[i]); } oUSD.mint(msg.sender, priceAdjustedTotal); emit Mint(msg.sender, priceAdjustedTotal); if (priceAdjustedTotal >= autoAllocateThreshold) { allocate(assetPrices); } } /** * @dev Withdraw a supported asset and burn OUSD. * @param _amount Amount of OUSD to burn */ function redeem(uint256 _amount) public { uint256[] memory assetPrices = _getAssetPrices(false); if (_amount > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } _redeem(_amount, assetPrices); } function _redeem(uint256 _amount, uint256[] memory assetPrices) internal { require(_amount > 0, "Amount must be greater than 0"); uint256 feeAdjustedAmount; if (redeemFeeBps > 0) { uint256 redeemFee = _amount.mul(redeemFeeBps).div(10000); feeAdjustedAmount = _amount.sub(redeemFee); } else { feeAdjustedAmount = _amount; } // Calculate redemption outputs uint256[] memory outputs = _calculateRedeemOutputs(feeAdjustedAmount); // Send outputs for (uint256 i = 0; i < allAssets.length; i++) { if (outputs[i] == 0) continue; IERC20 asset = IERC20(allAssets[i]); if (asset.balanceOf(address(this)) >= outputs[i]) { // Use Vault funds first if sufficient asset.safeTransfer(msg.sender, outputs[i]); } else { address strategyAddr = _selectWithdrawStrategyAddr( allAssets[i], outputs[i], assetPrices ); if (strategyAddr != address(0)) { // Nothing in Vault, but something in Strategy, send from there IStrategy strategy = IStrategy(strategyAddr); strategy.withdraw(msg.sender, allAssets[i], outputs[i]); } else { // Cant find funds anywhere revert("Liquidity error"); } } } oUSD.burn(msg.sender, _amount); // Until we can prove that we won't affect the prices of our assets // by withdrawing them, this should be here. // It's possible that a strategy was off on its asset total, perhaps // a reward token sold for more or for less than anticipated. if (_amount > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } emit Redeem(msg.sender, _amount); } /** * @notice Withdraw a supported asset and burn all OUSD. */ function redeemAll() external { uint256[] memory assetPrices = _getAssetPrices(false); //unfortunately we have to do balanceOf twice if (oUSD.balanceOf(msg.sender) > rebaseThreshold && !rebasePaused) { rebase(assetPrices); } _redeem(oUSD.balanceOf(msg.sender), assetPrices); } /** * @notice Allocate unallocated funds on Vault to strategies. * @dev Allocate unallocated funds on Vault to strategies. **/ function allocate() public { uint256[] memory assetPrices = _getAssetPrices(false); allocate(assetPrices); } /** * @notice Allocate unallocated funds on Vault to strategies. * @dev Allocate unallocated funds on Vault to strategies. **/ function allocate(uint256[] memory assetPrices) internal { uint256 vaultValue = _totalValueInVault(assetPrices); // Nothing in vault to allocate if (vaultValue == 0) return; uint256 strategiesValue = _totalValueInStrategies(assetPrices); // We have a method that does the same as this, gas optimisation uint256 totalValue = vaultValue + strategiesValue; // We want to maintain a buffer on the Vault so calculate a percentage // modifier to multiply each amount being allocated by to enforce the // vault buffer uint256 vaultBufferModifier; if (strategiesValue == 0) { // Nothing in Strategies, allocate 100% minus the vault buffer to // strategies vaultBufferModifier = 1e18 - vaultBuffer; } else { vaultBufferModifier = vaultBuffer.mul(totalValue).div(vaultValue); if (1e18 > vaultBufferModifier) { // E.g. 1e18 - (1e17 * 10e18)/5e18 = 8e17 // (5e18 * 8e17) / 1e18 = 4e18 allocated from Vault vaultBufferModifier = 1e18 - vaultBufferModifier; } else { // We need to let the buffer fill return; } } if (vaultBufferModifier == 0) return; // Iterate over all assets in the Vault and allocate the the appropriate // strategy for (uint256 i = 0; i < allAssets.length; i++) { IERC20 asset = IERC20(allAssets[i]); uint256 assetBalance = asset.balanceOf(address(this)); // No balance, nothing to do here if (assetBalance == 0) continue; // Multiply the balance by the vault buffer modifier and truncate // to the scale of the asset decimals uint256 allocateAmount = assetBalance.mulTruncate( vaultBufferModifier ); // Get the target Strategy to maintain weightings address depositStrategyAddr = _selectDepositStrategyAddr( address(asset), assetPrices ); if (depositStrategyAddr != address(0) && allocateAmount > 0) { IStrategy strategy = IStrategy(depositStrategyAddr); // Transfer asset to Strategy and call deposit method to // mint or take required action asset.safeTransfer(address(strategy), allocateAmount); strategy.deposit(address(asset), allocateAmount); } } } /** * @dev Calculate the total value of assets held by the Vault and all * strategies and update the supply of oUSD */ function rebase() public whenNotRebasePaused returns (uint256) { uint256[] memory assetPrices = _getAssetPrices(false); rebase(assetPrices); } /** * @dev Calculate the total value of assets held by the Vault and all * strategies and update the supply of oUSD */ function rebase(uint256[] memory assetPrices) internal whenNotRebasePaused returns (uint256) { if (oUSD.totalSupply() == 0) return 0; return oUSD.changeSupply(_totalValue(assetPrices)); } /** * @dev Determine the total value of assets held by the vault and its * strategies. * @return uint256 value Total value in USD (1e18) */ function totalValue() external returns (uint256 value) { uint256[] memory assetPrices = _getAssetPrices(false); value = _totalValue(assetPrices); } /** * @dev Internal Calculate the total value of the assets held by the * vault and its strategies. * @return uint256 value Total value in USD (1e18) */ function _totalValue(uint256[] memory assetPrices) internal view returns (uint256 value) { return _totalValueInVault(assetPrices) + _totalValueInStrategies(assetPrices); } /** * @dev Internal to calculate total value of all assets held in Vault. * @return uint256 Total value in ETH (1e18) */ function _totalValueInVault(uint256[] memory assetPrices) internal view returns (uint256 value) { value = 0; for (uint256 y = 0; y < allAssets.length; y++) { IERC20 asset = IERC20(allAssets[y]); uint256 assetDecimals = Helpers.getDecimals(allAssets[y]); uint256 balance = asset.balanceOf(address(this)); if (balance > 0) { value += balance.mulTruncateScale( assetPrices[y], 10**assetDecimals ); } } } /** * @dev Internal to calculate total value of all assets held in Strategies. * @return uint256 Total value in ETH (1e18) */ function _totalValueInStrategies(uint256[] memory assetPrices) internal view returns (uint256 value) { value = 0; for (uint256 i = 0; i < allStrategies.length; i++) { value += _totalValueInStrategy(allStrategies[i], assetPrices); } } /** * @dev Internal to calculate total value of all assets held by strategy. * @param _strategyAddr Address of the strategy * @return uint256 Total value in ETH (1e18) */ function _totalValueInStrategy( address _strategyAddr, uint256[] memory assetPrices ) internal view returns (uint256 value) { value = 0; IStrategy strategy = IStrategy(_strategyAddr); for (uint256 y = 0; y < allAssets.length; y++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[y]); if (strategy.supportsAsset(allAssets[y])) { uint256 balance = strategy.checkBalance(allAssets[y]); if (balance > 0) { value += balance.mulTruncateScale( assetPrices[y], 10**assetDecimals ); } } } } /** * @dev Calculate difference in percent of asset allocation for a strategy. * @param _strategyAddr Address of the strategy * @return int256 Difference between current and target. 18 decimals. For ex. 10%=1e17. */ function _strategyWeightDifference( address _strategyAddr, uint256[] memory assetPrices ) internal view returns (int256 difference) { difference = int256(strategies[_strategyAddr].targetWeight) - int256( _totalValueInStrategy(_strategyAddr, assetPrices).divPrecisely( _totalValue(assetPrices) ) ); } /** * @dev Select a strategy for allocating an asset to. * @param _asset Address of asset * @return address Address of the target strategy */ function _selectDepositStrategyAddr( address _asset, uint256[] memory assetPrices ) internal view returns (address depositStrategyAddr) { depositStrategyAddr = address(0); int256 maxDifference = 0; for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.supportsAsset(_asset)) { int256 diff = _strategyWeightDifference( allStrategies[i], assetPrices ); if (diff >= maxDifference) { maxDifference = diff; depositStrategyAddr = allStrategies[i]; } } } } /** * @dev Select a strategy for withdrawing an asset from. * @param _asset Address of asset * @return address Address of the target strategy for withdrawal */ function _selectWithdrawStrategyAddr( address _asset, uint256 _amount, uint256[] memory assetPrices ) internal view returns (address withdrawStrategyAddr) { withdrawStrategyAddr = address(0); int256 minDifference = 1e18; for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if ( strategy.supportsAsset(_asset) && strategy.checkBalance(_asset) > _amount ) { int256 diff = _strategyWeightDifference( allStrategies[i], assetPrices ); if (diff <= minDifference) { minDifference = diff; withdrawStrategyAddr = allStrategies[i]; } } } } /** * @notice Get the balance of an asset held in Vault and all strategies. * @param _asset Address of asset * @return uint256 Balance of asset in decimals of asset */ function checkBalance(address _asset) external view returns (uint256) { return _checkBalance(_asset); } /** * @notice Get the balance of an asset held in Vault and all strategies. * @param _asset Address of asset * @return uint256 Balance of asset in decimals of asset */ function _checkBalance(address _asset) internal view returns (uint256 balance) { IERC20 asset = IERC20(_asset); balance = asset.balanceOf(address(this)); for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.supportsAsset(_asset)) { balance += strategy.checkBalance(_asset); } } } /** * @notice Get the balance of all assets held in Vault and all strategies. * @return uint256 Balance of all assets (1e18) */ function _checkBalance() internal view returns (uint256 balance) { balance = 0; for (uint256 i = 0; i < allAssets.length; i++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[i]); balance += _checkBalance(allAssets[i]).scaleBy( int8(18 - assetDecimals) ); } } /** * @notice Calculate the outputs for a redeem function, i.e. the mix of * coins that will be returned */ function calculateRedeemOutputs(uint256 _amount) external returns (uint256[] memory) { return _calculateRedeemOutputs(_amount); } /** * @notice Calculate the outputs for a redeem function, i.e. the mix of * coins that will be returned. * @return Array of amounts respective to the supported assets */ function _calculateRedeemOutputs(uint256 _amount) internal returns (uint256[] memory outputs) { uint256[] memory assetPrices = _getAssetPrices(true); uint256 totalBalance = _checkBalance(); uint256 totalOutputValue = 0; // Running total of USD value of assets uint256 assetCount = getAssetCount(); // Initialise arrays // Price of each asset in USD in 1e18 outputs = new uint256[](assetCount); for (uint256 i = 0; i < allAssets.length; i++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[i]); // Get the proportional amount of this token for the redeem in 1e18 uint256 proportionalAmount = _checkBalance(allAssets[i]) .scaleBy(int8(18 - assetDecimals)) .mul(_amount) .div(totalBalance); if (proportionalAmount > 0) { // Running USD total of all coins in the redeem outputs in 1e18 totalOutputValue += proportionalAmount.mulTruncate( assetPrices[i] ); // Save the output amount in the decimals of the asset outputs[i] = proportionalAmount.scaleBy( int8(assetDecimals - 18) ); } } // USD difference in amount of coins calculated due to variations in // price in 1e18 int256 outputValueDiff = int256(_amount - totalOutputValue); // Make up the difference by adding/removing an equal proportion of // each coin according to its USD value for (uint256 i = 0; i < outputs.length; i++) { if (outputs[i] == 0) continue; if (outputValueDiff < 0) { outputs[i] -= uint256(-outputValueDiff).mul(outputs[i]).div( totalOutputValue ); } else if (outputValueDiff > 0) { outputs[i] += uint256(outputValueDiff).mul(outputs[i]).div( totalOutputValue ); } } } /** * @notice Get an array of the supported asset prices in USD. * @return uint256[] Array of asset prices in USD (1e18) */ function _getAssetPrices(bool useMax) internal returns (uint256[] memory assetPrices) { assetPrices = new uint256[](getAssetCount()); IMinMaxOracle oracle = IMinMaxOracle(priceProvider); // Price from Oracle is returned with 8 decimals // _amount is in assetDecimals for (uint256 i = 0; i < allAssets.length; i++) { string memory symbol = Helpers.getSymbol(allAssets[i]); // Get all the USD prices of the asset in 1e18 if (useMax) { assetPrices[i] = oracle.priceMax(symbol).scaleBy(int8(18 - 8)); } else { assetPrices[i] = oracle.priceMin(symbol).scaleBy(int8(18 - 8)); } } } /*************************************** Pause ****************************************/ /** * @dev Set the deposit paused flag to true to prevent rebasing. */ function pauseRebase() external onlyGovernor { rebasePaused = true; } /** * @dev Set the deposit paused flag to true to allow rebasing. */ function unpauseRebase() external onlyGovernor { rebasePaused = false; } /** * @dev Set the deposit paused flag to true to prevent deposits. */ function pauseDeposits() external onlyGovernor { depositPaused = true; emit DepositsPaused(); } /** * @dev Set the deposit paused flag to false to enable deposits. */ function unpauseDeposits() external onlyGovernor { depositPaused = false; emit DepositsUnpaused(); } /*************************************** Utils ****************************************/ /** * @dev Return the number of assets suppported by the Vault. */ function getAssetCount() public view returns (uint256) { return allAssets.length; } /** * @dev Return all asset addresses in order */ function getAllAssets() external view returns (address[] memory) { return allAssets; } /** * @dev Return the number of strategies active on the Vault. */ function getStrategyCount() public view returns (uint256) { return allStrategies.length; } /** * @dev Get the total APR of the Vault and all Strategies. */ function getAPR() external returns (uint256) { if (getStrategyCount() == 0) return 0; uint256[] memory assetPrices = _getAssetPrices(true); uint256 totalAPR = 0; // Get the value from strategies for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.getAPR() > 0) { totalAPR += _totalValueInStrategy(allStrategies[i], assetPrices) .divPrecisely(_totalValue(assetPrices)) .mulTruncate(strategy.getAPR()); } } return totalAPR; } /** * @dev Transfer token to governor. Intended for recovering tokens stuck in * contract, i.e. mistaken sends. * @param _asset Address for the asset * @param _amount Amount of the asset to transfer */ function transferToken(address _asset, uint256 _amount) external onlyGovernor { IERC20(_asset).transfer(governor(), _amount); } /** * @dev Collect reward tokens from all strategies. */ function collectRewardTokens() external onlyGovernor { for (uint256 i = 0; i < allStrategies.length; i++) { collectRewardTokens(allStrategies[i]); } } /** * @dev Collect reward tokens from a single strategy and transfer them to Vault. * @param _strategyAddr Address of the strategy to collect rewards from */ function collectRewardTokens(address _strategyAddr) public onlyGovernor { IStrategy strategy = IStrategy(_strategyAddr); strategy.collectRewardToken(); } /** * @dev Determines if an asset is supported by the vault. * @param _asset Address of the asset */ function isSupportedAsset(address _asset) external view returns (bool) { return assets[_asset].isSupported; } function _priceUSDMint(string memory symbol) internal returns (uint256) { // Price from Oracle is returned with 8 decimals // scale to 18 so 18-8=10 return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10); } /** * @dev Returns the total price in 18 digit USD for a given asset. * Using Min since min is what we use for mint pricing * @param symbol String symbol of the asset * @return uint256 USD price of 1 of the asset */ function priceUSDMint(string calldata symbol) external returns (uint256) { return _priceUSDMint(symbol); } /** * @dev Returns the total price in 18 digit USD for a given asset. * Using Max since max is what we use for redeem pricing * @param symbol String symbol of the asset * @return uint256 USD price of 1 of the asset */ function _priceUSDRedeem(string memory symbol) internal returns (uint256) { // Price from Oracle is returned with 8 decimals // scale to 18 so 18-8=10 return IMinMaxOracle(priceProvider).priceMax(symbol).scaleBy(10); } /** * @dev Returns the total price in 18 digit USD for a given asset. * Using Max since max is what we use for redeem pricing * @param symbol String symbol of the asset * @return uint256 USD price of 1 of the asset */ function priceUSDRedeem(string calldata symbol) external returns (uint256) { // Price from Oracle is returned with 8 decimals // scale to 18 so 18-8=10 return _priceUSDRedeem(symbol); } }
Set the weights for multiple strategies. _strategyAddresses Array of strategy addresses _weights Array of corresponding weights, with 18 decimals. For ex. 100%=1e18, 30%=3e17./
function setStrategyWeights( address[] calldata _strategyAddresses, uint256[] calldata _weights ) external onlyGovernor { require( _strategyAddresses.length == _weights.length, "Parameter length mismatch" ); for (uint256 i = 0; i < _strategyAddresses.length; i++) { strategies[_strategyAddresses[i]].targetWeight = _weights[i]; } emit StrategyWeightsUpdated(_strategyAddresses, _weights); }
1,233,148
./full_match/5/0x285633333615b13e665Be0e714d85C1cEf0A19F1/sources/browser/Symbio.sol
The fallback function: If the contract's controller has not been set to 0, then the `proxyPayment` method is called which relays the ether and creates tokens as described in the token controller contract
function () external payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount );
1,952,616
pragma solidity ^0.5.10; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../interfaces/IERC223ReceivingContract.sol"; import "../interfaces/IDetherToken.sol"; import "../interfaces/IZoneFactory.sol"; import "../interfaces/IZone.sol"; import "../interfaces/ITeller.sol"; contract Zone is IERC223ReceivingContract { // ------------------------------------------------ // // Library init // // ------------------------------------------------ using SafeMath for uint; // ------------------------------------------------ // // Enums // // ------------------------------------------------ enum AuctionState { Started, Ended } // ------------------------------------------------ // // Structs // // ------------------------------------------------ struct ZoneOwner { address addr; uint startTime; uint staked; uint balance; uint lastTaxTime; uint auctionId; } struct Auction { uint startTime; uint endTime; AuctionState state; address highestBidder; } mapping(uint => Auction) private auctionIdToAuction; // ------------------------------------------------ // // Variables Public // // ------------------------------------------------ uint public constant MIN_STAKE = 100 ether; // DTH, which is also 18 decimals! uint public constant BID_PERIOD = 48 hours; // mainnet params uint public constant COOLDOWN_PERIOD = 24 hours; // mainnet params uint public constant ENTRY_FEE_PERCENTAGE = 4; // in % uint public constant TAX_PERCENTAGE = 4; // 0,04% daily / around 15% yearly uint public constant MIN_RAISE = 6; // everybid should be more than x% that the previous highestbid bool private inited; IDetherToken public dth; IZoneFactory public zoneFactory; ITeller public teller; ZoneOwner public zoneOwner; address public taxCollector; bytes2 public country; bytes6 public geohash; mapping(address => uint) public withdrawableDth; uint public currentAuctionId; // starts at 0, first auction will get id 1, etc. // auctionId bidder dthAmount mapping(uint => mapping(address => uint)) public auctionBids; // ------------------------------------------------ // // Modifiers // // ------------------------------------------------ modifier updateState { _processState(); _; } modifier onlyWhenZoneHasOwner { require(zoneOwner.addr != address(0), "zone has no owner"); _; } modifier onlyWhenCallerIsZoneOwner { require(msg.sender == zoneOwner.addr, "caller is not zoneowner"); _; } modifier onlyWhenZoneHasNoOwner { require(zoneOwner.addr == address(0), "can not claim zone with owner"); _; } // ------------------------------------------------ // // Constructor // // ------------------------------------------------ // executed by ZoneFactory.sol when this Zone does not yet exist (= not yet deployed) function init( bytes2 _countryCode, bytes6 _geohash, address _zoneOwner, uint _dthAmount, address _dth, // address _geo, address _zoneFactory, address _taxCollector, address _teller ) external { require(inited == false, "contract already initialized"); require(_dthAmount >= MIN_STAKE, "zone dth stake shoulld be at least minimum (100DTH)"); country = _countryCode; geohash = _geohash; dth = IDetherToken(_dth); zoneFactory = IZoneFactory(_zoneFactory); taxCollector = _taxCollector; zoneOwner.addr = _zoneOwner; zoneOwner.startTime = now; zoneOwner.staked = _dthAmount; zoneOwner.balance = _dthAmount; zoneOwner.lastTaxTime = now; zoneOwner.auctionId = 0; // was not gained by winning an auction inited = true; currentAuctionId = 0; teller = ITeller(_teller); } // ------------------------------------------------ // // Functions Getters Public // // ------------------------------------------------ function ownerAddr() external view returns (address) { return zoneOwner.addr; } function calcHarbergerTax(uint _startTime, uint _endTime, uint _dthAmount) public view returns (uint taxAmount, uint keepAmount) { // TODO use smaller uint variables, hereby preventing under/overflows, so no need for SafeMath // source: https://programtheblockchain.com/posts/2018/09/19/implementing-harberger-tax-deeds/ taxAmount = _dthAmount.mul(_endTime.sub(_startTime)).mul(TAX_PERCENTAGE).div(10000).div(1 days); keepAmount = _dthAmount.sub(taxAmount); } function calcEntryFee(uint _value) public view returns (uint burnAmount, uint bidAmount) { burnAmount = _value.mul(ENTRY_FEE_PERCENTAGE).div(100); // 4% bidAmount = _value.sub(burnAmount); // 96% } function auctionExists(uint _auctionId) external view returns (bool) { // if aucton does not exist we should get back zero, otherwise this field // will contain a block.timestamp, set whe creating an Auction, in constructor() and bid() return auctionIdToAuction[_auctionId].startTime > 0; } /// @notice get current zone owner data function getZoneOwner() external view returns (address, uint, uint, uint, uint, uint) { return ( zoneOwner.addr, // address of current owner zoneOwner.startTime, // time this address became owner zoneOwner.staked, // "price you sell at" zoneOwner.balance, // will decrease whenever harberger taxes are paid zoneOwner.lastTaxTime, // time until taxes have been paid zoneOwner.auctionId // if gained by winning auction, the auction id, otherwise zero ); } /// @notice get a specific auction function getAuction(uint _auctionId) public view returns (uint, uint, uint, uint, address, uint) { require(_auctionId > 0 && _auctionId <= currentAuctionId, "auction does not exist"); Auction memory auction = auctionIdToAuction[_auctionId]; uint highestBid = auctionBids[_auctionId][auction.highestBidder]; // If auction is ongoing, for current zone owner his existing zone stake is added to his bid if (auction.state == AuctionState.Started && auction.highestBidder == zoneOwner.addr) { highestBid = highestBid.add(zoneOwner.staked); } return ( _auctionId, uint(auction.state), auction.startTime, auction.endTime, auction.highestBidder, highestBid ); } /// @notice get the last auction function getLastAuction() external view returns (uint, uint, uint, uint, address, uint) { return getAuction(currentAuctionId); } // ------------------------------------------------ // // Functions Utils // // ------------------------------------------------ function toBytes1(bytes memory _bytes, uint _start) private pure returns (bytes1) { require(_bytes.length >= (_start + 1), " not long enough"); bytes1 tempBytes1; assembly { tempBytes1 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes1; } // ------------------------------------------------ // // Functions Setters Private // // ------------------------------------------------ function _removeZoneOwner(bool fromRelease) private { // if we call this function from release() we shouldn't update withdrawableDth as we already send dth if (!fromRelease) { withdrawableDth[zoneOwner.addr] = withdrawableDth[zoneOwner.addr].add(zoneOwner.balance); } if (teller.hasTeller()) { teller.removeTellerByZone(); } zoneFactory.changeOwner(address(0), zoneOwner.addr, address(0)); delete zoneOwner; } /* * calculate harberger taxes and send dth to taxCollector and referrer (if exist) */ function _handleTaxPayment() private { // processState ensured that: no running auction + there is a zone owner if (zoneOwner.lastTaxTime >= now) { return; // short-circuit: multiple txes in 1 block OR many blocks but in same Auction } (uint taxAmount, uint keepAmount) = calcHarbergerTax(zoneOwner.lastTaxTime, now, zoneOwner.staked); if (taxAmount > zoneOwner.balance) { // zone owner does not have enough balance, remove him as zone owner uint oldZoneOwnerBalance = zoneOwner.balance; _removeZoneOwner(false); require(dth.transfer(taxCollector, oldZoneOwnerBalance)); } else { // zone owner can pay due taxes zoneOwner.balance = zoneOwner.balance.sub(taxAmount); zoneOwner.lastTaxTime = now; (address referrer, uint refFee) = teller.getReferrer(); if (referrer != address(0x00) && refFee > 0) { uint referralFee = taxAmount.mul(refFee).div(1000) ; // to avoid Dos with revert if referrer is contract bytes memory payload = abi.encodeWithSignature("transfer(address,uint256)", referrer, referralFee); address(dth).call(payload); // require(dth.transfer(referrer, referralFee)); require(dth.transfer(taxCollector, taxAmount - referralFee)); } else { require(dth.transfer(taxCollector, taxAmount)); } } } /* * Called when auction is ended by _processState() * update the state with new owner and new bid */ function _endAuction() private { Auction storage lastAuction = auctionIdToAuction[currentAuctionId]; lastAuction.state = AuctionState.Ended; uint highestBid = auctionBids[currentAuctionId][lastAuction.highestBidder]; uint auctionEndTime = auctionIdToAuction[currentAuctionId].endTime; address highestBidder = lastAuction.highestBidder; if (zoneOwner.addr == highestBidder) { // current zone owner won the auction, extend his zone ownershp zoneOwner.staked = zoneOwner.staked.add(highestBid); zoneOwner.balance = zoneOwner.balance.add(highestBid); // need to set it since it might've been zero zoneOwner.auctionId = currentAuctionId; // the (last) auctionId that gave the zoneOwner zone ownership } else { // we need to update the zone owner _removeZoneOwner(false); zoneFactory.changeOwner(highestBidder, zoneOwner.addr, address(this)); zoneOwner.addr = highestBidder; zoneOwner.startTime = auctionEndTime; zoneOwner.staked = highestBid; // entry fee is already deducted when user calls bid() zoneOwner.balance = highestBid; zoneOwner.auctionId = currentAuctionId; // the auctionId that gave the zoneOwner zone ownership } // (new) zone owner needs to pay taxes from the moment he acquires zone ownership until now (uint taxAmount, uint keepAmount) = calcHarbergerTax(auctionEndTime, now, zoneOwner.staked); zoneOwner.balance = zoneOwner.balance.sub(taxAmount); zoneOwner.lastTaxTime = now; zoneFactory.removeActiveBidder(highestBidder); zoneFactory.removeCurrentZoneBidders(); zoneFactory.emitAuctionEnded(geohash, highestBidder, currentAuctionId, highestBid); } function processState() external /* onlyByTellerContract */ { _processState(); } /// @notice private function to update the current auction state function _processState() private { if (currentAuctionId > 0 && auctionIdToAuction[currentAuctionId].state == AuctionState.Started) { // while uaction is running, no taxes need to be paid // handling of taxes around change of zone ownership are handled inside _endAuction if (now >= auctionIdToAuction[currentAuctionId].endTime) _endAuction(); } else { // no running auction, currentAuctionId could be zero if (zoneOwner.addr != address(0)) _handleTaxPayment(); } } function _joinAuction(address _sender, uint _dthAmount) private { Auction storage lastAuction = auctionIdToAuction[currentAuctionId]; //------------------------------------------------------------------------------// // there is a running auction, lets see if we can join the auction with our bid // //------------------------------------------------------------------------------// require(zoneFactory.activeBidderToZone(_sender) == address(this) || zoneFactory.activeBidderToZone(_sender) == address(0), "sender is currently involved in another auction"); require(zoneFactory.ownerToZone(_sender) == address(0) || zoneFactory.ownerToZone(_sender) == address(this), "sender own already another zone"); uint currentHighestBid = auctionBids[currentAuctionId][lastAuction.highestBidder]; if (_sender == zoneOwner.addr) { uint dthAddedBidsAmount = auctionBids[currentAuctionId][_sender].add(_dthAmount); // the current zone owner's stake also counts in his bid require(zoneOwner.staked.add(dthAddedBidsAmount) >= currentHighestBid.add(currentHighestBid.mul(MIN_RAISE).div(100)), "bid + already staked is less than current highest + MIN_RAISE"); auctionBids[currentAuctionId][_sender] = dthAddedBidsAmount; } else { // _sender is not the current zone owner if (auctionBids[currentAuctionId][_sender] == 0) { // this is the first bid of this challenger, deduct entry fee (uint burnAmount, uint bidAmount) = calcEntryFee(_dthAmount); require(bidAmount >= currentHighestBid.add(currentHighestBid.mul(MIN_RAISE).div(100)), "bid is less than current highest + MIN_RAISE"); auctionBids[currentAuctionId][_sender] = bidAmount; require(dth.transfer(taxCollector, burnAmount)); } else { // not the first bid, no entry fee uint newUserTotalBid = auctionBids[currentAuctionId][_sender].add(_dthAmount); require(newUserTotalBid >= currentHighestBid.add(currentHighestBid.mul(MIN_RAISE).div(100)), "bid is less than current highest + MIN_RAISE"); auctionBids[currentAuctionId][_sender] = newUserTotalBid; } } // it worked, _sender placed a bid lastAuction.highestBidder = _sender; zoneFactory.fillCurrentZoneBidder(_sender); zoneFactory.emitBid(geohash, _sender, currentAuctionId, _dthAmount); } function _createAuction(address _sender, uint _dthAmount) private { require(zoneFactory.activeBidderToZone(_sender) == address(0), "sender is currently involved in an auction (Zone)"); require(zoneFactory.ownerToZone(_sender) == address(0), "sender own already a zone"); (uint burnAmount, uint bidAmount) = calcEntryFee(_dthAmount); require(bidAmount > zoneOwner.staked.add(zoneOwner.staked.mul(MIN_RAISE).div(100)), "bid is lower than current zone stake"); // save the new Auction uint newAuctionId = ++currentAuctionId; auctionIdToAuction[newAuctionId] = Auction({ state: AuctionState.Started, startTime: now, endTime: now.add(BID_PERIOD), highestBidder: _sender // caller (challenger) }); auctionBids[newAuctionId][_sender] = bidAmount; require(dth.transfer(taxCollector, burnAmount)); // zoneFactory.fillCurrentZoneBidder(_sender); zoneFactory.fillCurrentZoneBidder(zoneOwner.addr); zoneFactory.emitAuctionCreated(geohash, _sender, newAuctionId, _dthAmount); } /// @notice private function to update the current auction state function _bid(address _sender, uint _dthAmount) // GAS COST +/- 223.689 private onlyWhenZoneHasOwner { if (currentAuctionId > 0 && auctionIdToAuction[currentAuctionId].state == AuctionState.Started) { _joinAuction(_sender, _dthAmount); } else { // there currently is no running auction if (zoneOwner.auctionId == 0) { // current zone owner did not become owner by winning an auction, but by creating this zone or caliming it when it was free require(now > zoneOwner.startTime.add(COOLDOWN_PERIOD), "cooldown period did not end yet"); } else { // current zone owner became owner by winning an auction (which has ended) require(now > auctionIdToAuction[currentAuctionId].endTime.add(COOLDOWN_PERIOD), "cooldown period did not end yet"); } _createAuction(_sender, _dthAmount); } } function _claimFreeZone(address _sender, uint _dthAmount) // GAS COSt +/- 177.040 private onlyWhenZoneHasNoOwner { require(_dthAmount >= MIN_STAKE, "need at least minimum zone stake amount (100 DTH)"); require(zoneFactory.ownerToZone(_sender) == address(0), "sender own already one zone"); require(zoneFactory.activeBidderToZone(_sender) == address(0), "sender is currently involved in an auction (Zone)"); // NOTE: empty zone claim will not have entry fee deducted, its not bidding it's taking immediately zoneFactory.changeOwner(_sender, zoneOwner.addr, address(this)); zoneOwner.addr = _sender; zoneOwner.startTime = now; zoneOwner.staked = _dthAmount; zoneOwner.balance = _dthAmount; zoneOwner.lastTaxTime = now; zoneOwner.auctionId = 0; // since it was not gained wby winning an auction zoneFactory.emitClaimFreeZone(geohash, _sender, _dthAmount); } function _topUp(address _sender, uint _dthAmount) // GAS COST +/- 104.201 private onlyWhenZoneHasOwner { // require(_sender == zoneOwner.addr, "caller is not zoneowner"); require(currentAuctionId == 0 || auctionIdToAuction[currentAuctionId].state == AuctionState.Ended, "cannot top up while auction running"); uint oldBalance = zoneOwner.balance; uint newBalance = oldBalance.add(_dthAmount); zoneOwner.balance = newBalance; // a zone owner can currently keep calling this to increase his dth balance inside the zone // without a change in his sell price (= zone.staked) or tax amount he needs to pay } // ------------------------------------------------ // // Functions Setters Public // // ------------------------------------------------ /// @notice ERC223 receiving function called by Dth contract when Eth is sent to this contract /// @param _from Who send DTH to this contract /// @param _value How much DTH was sent to this contract /// @param _data Additional bytes data sent function tokenFallback(address _from, uint _value, bytes memory _data) public // onlyWhenZoneEnabled { require(inited == true, "contract not yet initialized"); require(msg.sender == address(dth), "can only be called by dth contract"); // require caller neither zone owner, neither active bidder bytes1 func = toBytes1(_data, 0); // require(func == bytes1(0x40) || func == bytes1(0x41) || func == bytes1(0x42) || func == bytes1(0x43), "did not match Zone function"); _processState(); if (func == bytes1(0x41)) { // claimFreeZone _claimFreeZone(_from, _value); } else if (func == bytes1(0x42)) { // bid _bid(_from, _value); } else if (func == bytes1(0x43)) { // topUp _topUp(_from, _value); } } /// @notice release zone ownership /// @dev can only be called by current zone owner, when there is no running auction function release() // GAS COST +/- 72.351 external updateState onlyWhenCallerIsZoneOwner { // allow also when country is disabled, otherwise no way for zone owner to get their eth/dth back require(currentAuctionId == 0 || auctionIdToAuction[currentAuctionId].state == AuctionState.Ended, "cannot release while auction running"); uint ownerBalance = zoneOwner.balance; _removeZoneOwner(true); // if msg.sender is a contract, the DTH ERC223 contract will try to call tokenFallback // on msg.sender, this could lead to a reentrancy. But we prevent this by resetting // zoneOwner before we do dth.transfer(msg.sender) require(dth.transfer(msg.sender, ownerBalance)); zoneFactory.emitReleaseZone(geohash, msg.sender); } // offer three different withdraw functions, single auction, multiple auctions, all auctions /// @notice withdraw losing bids from a specific auction /// @param _auctionId The auction id function withdrawFromAuction(uint _auctionId) // GAS COST +/- 125.070 external updateState { // even when country is disabled, otherwise users cannot withdraw their bids require(_auctionId > 0 && _auctionId <= currentAuctionId, "auctionId does not exist"); require(auctionIdToAuction[_auctionId].state == AuctionState.Ended, "cannot withdraw while auction is active"); require(auctionIdToAuction[_auctionId].highestBidder != msg.sender, "auction winner can not withdraw"); require(auctionBids[_auctionId][msg.sender] > 0, "nothing to withdraw"); uint withdrawAmount = auctionBids[_auctionId][msg.sender]; auctionBids[_auctionId][msg.sender] = 0; if (withdrawableDth[msg.sender] > 0) { withdrawAmount = withdrawAmount.add(withdrawableDth[msg.sender]); withdrawableDth[msg.sender] = 0; } zoneFactory.removeActiveBidder(msg.sender); require(dth.transfer(msg.sender, withdrawAmount)); } /// @notice withdraw from a given list of auction ids function withdrawFromAuctions(uint[] calldata _auctionIds) // GAS COST +/- 127.070 external updateState { // even when country is disabled, can withdraw require(currentAuctionId > 0, "there are no auctions"); require(_auctionIds.length > 0, "auctionIds list is empty"); require(_auctionIds.length <= currentAuctionId, "auctionIds list is longer than allowed"); uint withdrawAmountTotal = 0; for (uint idx = 0; idx < _auctionIds.length; idx++) { uint auctionId = _auctionIds[idx]; require(auctionId > 0 && auctionId <= currentAuctionId, "auctionId does not exist"); require(auctionIdToAuction[auctionId].state == AuctionState.Ended, "cannot withdraw from running auction"); require(auctionIdToAuction[auctionId].highestBidder != msg.sender, "auction winner can not withdraw"); uint withdrawAmount = auctionBids[auctionId][msg.sender]; if (withdrawAmount > 0) { // if user supplies the same auctionId multiple times in auctionIds, // only the first one will get a withdrawal amount auctionBids[auctionId][msg.sender] = 0; withdrawAmountTotal = withdrawAmountTotal.add(withdrawAmount); } } if (withdrawableDth[msg.sender] > 0) { withdrawAmountTotal = withdrawAmountTotal.add(withdrawableDth[msg.sender]); withdrawableDth[msg.sender] = 0; } zoneFactory.removeActiveBidder(msg.sender); require(withdrawAmountTotal > 0, "nothing to withdraw"); require(dth.transfer(msg.sender, withdrawAmountTotal)); } // - bids in past auctions // - zone owner stake function withdrawDth() external updateState { uint dthWithdraw = withdrawableDth[msg.sender]; require(dthWithdraw > 0, "nothing to withdraw"); zoneFactory.removeActiveBidder(msg.sender); if (dthWithdraw > 0) { withdrawableDth[msg.sender] = 0; require(dth.transfer(msg.sender, dthWithdraw)); } } }
get current zone owner data
function getZoneOwner() external view returns (address, uint, uint, uint, uint, uint) { return ( ); }
5,454,348
//Address: 0x5f391f8253475bffa27b2f8544994f9717ab310d //Contract name: CromIco //Balance: 0.94901046 Ether //Verification Date: 11/16/2017 //Transacion Count: 27 // CODE STARTS HERE pragma solidity ^0.4.15; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant 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() { 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ClaimableTokens is Ownable { address public claimedTokensWallet; function ClaimableTokens(address targetWallet) { claimedTokensWallet = targetWallet; } function claimTokens(address tokenAddress) public onlyOwner { require(tokenAddress != 0x0); ERC20 claimedToken = ERC20(tokenAddress); uint balance = claimedToken.balanceOf(this); claimedToken.transfer(claimedTokensWallet, balance); } } contract CromToken is Ownable, ERC20, ClaimableTokens { using SafeMath for uint256; string public constant name = "CROM Token"; string public constant symbol = "CROM"; uint8 public constant decimals = 0; uint256 public constant INITIAL_SUPPLY = 10 ** 7; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function CromToken() Ownable() ClaimableTokens(msg.sender) { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = totalSupply; } function transfer(address to, uint256 value) public returns (bool success) { require(to != 0x0); require(balances[msg.sender] >= value); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } function allowance(address owner, address spender) public constant returns (uint256 remaining) { return allowed[owner][spender]; } function balanceOf(address who) public constant returns (uint256) { return balances[who]; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(to != 0x0); require(balances[from] >= value); require(value <= allowed[from][msg.sender]); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); Transfer(from, to, value); return true; } } contract CromIco is Ownable, ClaimableTokens { using SafeMath for uint256; CromToken public token; // start and end timestamps where investments are allowed (both inclusive) uint public preStartTime; uint public startTime; uint public endTime; // address where funds are collected address public targetWallet; bool public targetWalletVerified; // caps definitions uint256 public constant SOFT_CAP = 8000 ether; uint256 public constant HARD_CAP = 56000 ether; // token price uint256 public constant TOKEN_PRICE = 10 finney; uint public constant BONUS_BATCH = 2 * 10 ** 6; uint public constant BONUS_PERCENTAGE = 25; uint256 public constant MINIMAL_PRE_ICO_INVESTMENT = 10 ether; // ICO duration uint public constant PRE_DURATION = 14 days; uint public constant DURATION = 14 days; // contributions per individual mapping (address => uint256) public balanceOf; // wallets allowed to take part in the pre ico mapping (address => bool) public preIcoMembers; // total amount of funds raised uint256 public amountRaised; uint256 public tokensSold; bool public paused; enum Stages { WalletUnverified, BeforeIco, Payable, AfterIco } enum PayableStages { PreIco, PublicIco } event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); // Constructor function CromIco(address tokenAddress, address beneficiaryWallet) Ownable() ClaimableTokens(beneficiaryWallet) { token = CromToken(tokenAddress); preStartTime = 1510920000; startTime = preStartTime + PRE_DURATION; endTime = startTime + DURATION; targetWallet = beneficiaryWallet; targetWalletVerified = false; paused = false; } modifier atStage(Stages stage) { require(stage == getCurrentStage()); _; } // fallback function can be used to buy tokens function() payable atStage(Stages.Payable) { buyTokens(); } // low level token purchase function function buyTokens() internal { require(msg.sender != 0x0); require(msg.value > 0); require(!paused); uint256 weiAmount = msg.value; // calculate token amount to be transferred uint256 tokens = calculateTokensAmount(weiAmount); require(tokens > 0); require(token.balanceOf(this) >= tokens); if (PayableStages.PreIco == getPayableStage()) { require(preIcoMembers[msg.sender]); require(weiAmount.add(balanceOf[msg.sender]) >= MINIMAL_PRE_ICO_INVESTMENT); require(tokensSold.add(tokens) <= BONUS_BATCH); } amountRaised = amountRaised.add(weiAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(weiAmount); tokensSold = tokensSold.add(tokens); token.transfer(msg.sender, tokens); TokenPurchase(msg.sender, weiAmount, tokens); } function verifyTargetWallet() public atStage(Stages.WalletUnverified) { require(msg.sender == targetWallet); targetWalletVerified = true; } // add a list of wallets to be allowed to take part in pre ico function addPreIcoMembers(address[] members) public onlyOwner { for (uint i = 0; i < members.length; i++) { preIcoMembers[members[i]] = true; } } // remove a list of wallets to be allowed to take part in pre ico function removePreIcoMembers(address[] members) public onlyOwner { for (uint i = 0; i < members.length; i++) { preIcoMembers[members[i]] = false; } } // @return true if the ICO is in pre ICO phase function isPreIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPreIco = PayableStages.PreIco == getPayableStage(); return isPayable && isPreIco; } // @return true if the public ICO is in progress function isPublicIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPublic = PayableStages.PublicIco == getPayableStage(); return isPayable && isPublic; } // @return true if ICO has ended function hasEnded() public constant returns (bool) { return Stages.AfterIco == getCurrentStage(); } // @return true if the soft cap has been reached function softCapReached() public constant returns (bool) { return amountRaised >= SOFT_CAP; } // withdraw the contributed funds if the ICO has // ended and the goal has not been reached function withdrawFunds() public atStage(Stages.AfterIco) returns(bool) { require(!softCapReached()); require(balanceOf[msg.sender] > 0); uint256 balance = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(balance); return true; } // transfer the raised funds to the target wallet if // the ICO is over and the goal has been reached function finalizeIco() public onlyOwner atStage(Stages.AfterIco) { require(softCapReached()); targetWallet.transfer(this.balance); } function withdrawUnsoldTokens() public onlyOwner atStage(Stages.AfterIco) { token.transfer(targetWallet, token.balanceOf(this)); } function pause() public onlyOwner { require(!paused); paused = true; } function resume() public onlyOwner { require(paused); paused = false; } function changeTargetWallet(address wallet) public onlyOwner { targetWallet = wallet; targetWalletVerified = false; } function calculateTokensAmount(uint256 funds) internal returns (uint256) { uint256 tokens = funds.div(TOKEN_PRICE); if (tokensSold < BONUS_BATCH) { if (tokensSold.add(tokens) > BONUS_BATCH) { uint256 bonusBaseTokens = BONUS_BATCH.mul(100).div(125).sub(tokensSold); tokens = tokens.add(bonusBaseTokens.mul(BONUS_PERCENTAGE).div(100)); } else { tokens = tokens.mul(BONUS_PERCENTAGE + 100).div(100); } } return tokens; } function getCurrentStage() internal constant returns (Stages) { if (!targetWalletVerified) { return Stages.WalletUnverified; } else if (now < preStartTime) { return Stages.BeforeIco; } else if (now < endTime && amountRaised < HARD_CAP) { return Stages.Payable; } else { return Stages.AfterIco; } } function getPayableStage() internal constant returns (PayableStages) { if (now < startTime) { return PayableStages.PreIco; } else { return PayableStages.PublicIco; } } }
return true if the public ICO is in progress
function isPublicIcoActive() public constant returns (bool) { bool isPayable = Stages.Payable == getCurrentStage(); bool isPublic = PayableStages.PublicIco == getPayableStage(); return isPayable && isPublic; }
1,031,418
./full_match/42220/0xaBb380Bd683971BDB426F0aa2BF2f111aA7824c2/sources/contracts/MarketPlace/MarketPlaceNFTAPI.sol
check if this contract has approved to transfer this erc721 token/
function _isTokenApproved(uint256 tokenId) public view returns (bool) { if(isSupport1555 == false){ try _erc721.getApproved(tokenId) returns (address tokenOperator) { return tokenOperator == address(this); return false; } return true; } }
16,314,874
// SPDX-License-Identifier: MIT pragma solidity >=0.6 <0.7.0; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Pollen * @dev The main token for the Pollen DAO * @author gtlewis * @author scorpion9979 * @author vkonst */ contract Pollen_v1 is OwnableUpgradeSafe, ERC20SnapshotUpgradeSafe { /** * @dev Reserved for possible storage structure changes */ uint256[50] private __gap; /** * @notice Initializes the contract and sets the Pollen token name and symbol (external) * @dev Sets the contract `owner` account to the deploying account */ function initialize() external initializer { __Ownable_init(); __ERC20_init_unchained("Pollen", "PLN"); __ERC20Snapshot_init_unchained(); } /** * @notice Mints tokens to the owner account (external) * @param amount The amount of tokens to mint * Requirements: the caller must be the owner * See {ERC20-_mint}. */ function mint(uint256 amount) external onlyOwner { _mint(_msgSender(), amount); } /** * @notice Destroys `amount` tokens from the caller (external) * @param amount The amount of tokens to mint * See {ERC20-_burn}. */ function burn(uint256 amount) external { _burn(_msgSender(), amount); } /** * @notice Destroys `amount` tokens from `account`, deducting from the caller's allowance * Requirements: the caller must have allowance for `accounts`'s tokens of at least `amount` */ function burnFrom(address account, uint256 amount) external { uint256 decreasedAllowance = allowance(account, _msgSender()) .sub(amount, "Pollen: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @notice Creates a new snapshot and returns its snapshot id (external) * Requirements: the caller must be the owner */ function snapshot() external onlyOwner returns (uint256) { return super._snapshot(); } }
Mints tokens to the owner account (external) amount The amount of tokens to mint Requirements: the caller must be the owner See {ERC20-_mint}./
function mint(uint256 amount) external onlyOwner { _mint(_msgSender(), amount); }
13,094,848
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import { FixedPoint96 } from "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; import { FullMath } from "@uniswap/v3-core/contracts/libraries/FullMath.sol"; import { PerpV2 } from "../integration/lib/PerpV2.sol"; import { IAccountBalance } from "../../interfaces/external/perp-v2/IAccountBalance.sol"; import { IClearingHouse } from "../../interfaces/external/perp-v2/IClearingHouse.sol"; import { IExchange } from "../../interfaces/external/perp-v2/IExchange.sol"; import { IVault } from "../../interfaces/external/perp-v2/IVault.sol"; import { IQuoter } from "../../interfaces/external/perp-v2/IQuoter.sol"; import { IMarketRegistry } from "../../interfaces/external/perp-v2/IMarketRegistry.sol"; import { IController } from "../../interfaces/IController.sol"; import { IDebtIssuanceModule } from "../../interfaces/IDebtIssuanceModule.sol"; import { IModuleIssuanceHook } from "../../interfaces/IModuleIssuanceHook.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; /** * @title PerpLeverageModule * @author Set Protocol * @notice Smart contract that enables leveraged trading using the PerpV2 protocol. Each SetToken can only manage a single Perp account * represented as a positive equity external position whose value is the net Perp account value denominated in the collateral token * deposited into the Perp Protocol. This module only allows Perp positions to be collateralized by one asset, USDC, set on deployment of * this contract (see collateralToken) however it can take positions simultaneuosly in multiple base assets. * * Upon issuance and redemption positions are not EXACTLY replicated like for other position types since a trade is necessary to enter/exit * the position on behalf of the issuer/redeemer. Any cost of entering/exiting the position (slippage) is carried by the issuer/redeemer. * Any pending funding costs or PnL is carried by the current token holders. To be used safely this module MUST issue using the * SlippageIssuanceModule or else issue and redeem transaction could be sandwich attacked. * * NOTE: The external position unit is only updated on an as-needed basis during issuance/redemption. It does not reflect the current * value of the Set's perpetual position. The current value can be calculated from getPositionNotionalInfo. */ contract PerpV2LeverageModule is ModuleBase, ReentrancyGuard, Ownable, IModuleIssuanceHook { using PerpV2 for ISetToken; using PreciseUnitMath for int256; using SignedSafeMath for int256; using AddressArrayUtils for address[]; /* ============ Structs ============ */ struct ActionInfo { ISetToken setToken; address baseToken; // Virtual token minted by the Perp protocol bool isBaseToQuote; // When true, `baseToken` is being sold, when false, bought bool isExactInput; // When true, `amount` is the swap input, when false, the swap output int256 amount; // Quantity in 10**18 decimals uint256 oppositeAmountBound; // vUSDC pay or receive quantity bound (see `_createAndValidateActionInfoNotionalNotional` for details) } struct PositionNotionalInfo { address baseToken; // Virtual token minted by the Perp protocol int256 baseBalance; // Base position notional quantity in 10**18 decimals. When negative, position is short int256 quoteBalance; // vUSDC "debt" notional quantity minted to open position. When positive, position is short } struct PositionUnitInfo { address baseToken; // Virtual token minted by the Perp protocol int256 baseUnit; // Base position unit. When negative, position is short int256 quoteUnit; // vUSDC "debt" position unit. When positive, position is short } struct AccountInfo { int256 collateralBalance; // Quantity of collateral deposited in Perp vault in 10**18 decimals int256 owedRealizedPnl; // USDC quantity of profit and loss in 10**18 decimals not yet settled to vault int256 pendingFundingPayments; // USDC quantity of pending funding payments in 10**18 decimals int256 netQuoteBalance; // USDC quantity of net quote balance for all open positions in Perp account } /* ============ Events ============ */ /** * @dev Emitted on trade * @param _setToken Instance of SetToken * @param _baseToken Virtual token minted by the Perp protocol * @param _deltaBase Change in baseToken position size resulting from trade * @param _deltaQuote Change in vUSDC position size resulting from trade * @param _protocolFee Quantity in collateral decimals sent to fee recipient during lever trade * @param _isBuy True when baseToken is being bought, false when being sold */ event PerpTrade( ISetToken indexed _setToken, address indexed _baseToken, uint256 _deltaBase, uint256 _deltaQuote, uint256 _protocolFee, bool _isBuy ); /** * @dev Emitted on deposit (not issue or redeeem) * @param _setToken Instance of SetToken * @param _collateralToken Token being deposited as collateral (USDC) * @param _amountDeposited Amount of collateral being deposited into Perp */ event CollateralDeposited( ISetToken indexed _setToken, IERC20 _collateralToken, uint256 _amountDeposited ); /** * @dev Emitted on withdraw (not issue or redeeem) * @param _setToken Instance of SetToken * @param _collateralToken Token being withdrawn as collateral (USDC) * @param _amountWithdrawn Amount of collateral being withdrawn from Perp */ event CollateralWithdrawn( ISetToken indexed _setToken, IERC20 _collateralToken, uint256 _amountWithdrawn ); /** * @dev Emitted on updateAllowedSetToken() * @param _setToken SetToken being whose allowance to initialize this module is being updated * @param _added true if added false if removed */ event SetTokenStatusUpdated( ISetToken indexed _setToken, bool indexed _added ); /** * @dev Emitted on updateAnySetAllowed() * @param _anySetAllowed true if any set is allowed to initialize this module, false otherwise */ event AnySetAllowedUpdated( bool indexed _anySetAllowed ); /* ============ Constants ============ */ // String identifying the DebtIssuanceModule in the IntegrationRegistry. Note: Governance must add DefaultIssuanceModule as // the string as the integration name string constant internal DEFAULT_ISSUANCE_MODULE_NAME = "DefaultIssuanceModule"; // 0 index stores protocol fee % on the controller, charged in the _executeTrade function uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0; /* ============ State Variables ============ */ // PerpV2 contract which provides getters for base, quote, and owedRealizedPnl balances IAccountBalance public immutable perpAccountBalance; // PerpV2 contract which provides a trading API IClearingHouse public immutable perpClearingHouse; // PerpV2 contract which manages trading logic. Provides getters for UniswapV3 pools and pending funding balances IExchange public immutable perpExchange; // PerpV2 contract which handles deposits and withdrawals. Provides getter for collateral balances IVault public immutable perpVault; // PerpV2 contract which makes it possible to simulate a trade before it occurs IQuoter public immutable perpQuoter; // PerpV2 contract which provides a getter for baseToken UniswapV3 pools IMarketRegistry public immutable perpMarketRegistry; // Token (USDC) used as a vault deposit, Perp currently only supports USDC as it's setllement and collateral token IERC20 public immutable collateralToken; // Decimals of collateral token. We set this in the constructor for later reading uint8 public immutable collateralDecimals; // Mapping of SetTokens to an array of virtual token addresses the Set has open positions for. // Array is automatically updated when new positions are opened or old positions are zeroed out. mapping(ISetToken => address[]) public positions; // Mapping of SetToken to boolean indicating if SetToken is on allow list. Updateable by governance mapping(ISetToken => bool) public allowedSetTokens; // Boolean that returns if any SetToken can initialize this module. If false, then subject to allow list. // Updateable by governance. bool public anySetAllowed; /* ============ Constructor ============ */ /** * @dev Sets external PerpV2 Protocol addresses. * @param _controller Address of controller contract * @param _perpVault Address of Perp Vault contract * @param _perpQuoter Address of Perp Quoter contract * @param _perpMarketRegistry Address of Perp MarketRegistry contract */ constructor( IController _controller, IVault _perpVault, IQuoter _perpQuoter, IMarketRegistry _perpMarketRegistry ) public ModuleBase(_controller) { // Use temp variables to initialize immutables address tempCollateralToken = IVault(_perpVault).getSettlementToken(); collateralToken = IERC20(tempCollateralToken); collateralDecimals = ERC20(tempCollateralToken).decimals(); perpAccountBalance = IAccountBalance(IVault(_perpVault).getAccountBalance()); perpClearingHouse = IClearingHouse(IVault(_perpVault).getClearingHouse()); perpExchange = IExchange(IVault(_perpVault).getExchange()); perpVault = _perpVault; perpQuoter = _perpQuoter; perpMarketRegistry = _perpMarketRegistry; } /* ============ External Functions ============ */ /** * @dev MANAGER ONLY: Allows manager to buy or sell perps to change exposure to the underlying baseToken. * Providing a positive value for `_baseQuantityUnits` buys vToken on UniswapV3 via Perp's ClearingHouse, * Providing a negative value sells the token. `_receiveQuoteQuantityUnits` defines a min-receive-like slippage * bound for the amount of vUSDC quote asset the trade will either pay or receive as a result of the action. * * NOTE: This method doesn't update the externalPositionUnit because it is a function of UniswapV3 virtual * token market prices and needs to be generated on the fly to be meaningful. * * As a user when levering, e.g increasing the magnitude of your position, you'd trade as below * | ----------------------------------------------------------------------------------------------- | * | Type | Action | Goal | `receiveQuoteQuantity` | `baseQuantityUnits` | * | ----- |-------- | ------------------------- | --------------------------- | ------------------- | * | Long | Buy | pay least amt. of vQuote | upper bound of input quote | positive | * | Short | Sell | get most amt. of vQuote | lower bound of output quote | negative | * | ----------------------------------------------------------------------------------------------- | * * As a user when delevering, e.g decreasing the magnitude of your position, you'd trade as below * | ----------------------------------------------------------------------------------------------- | * | Type | Action | Goal | `receiveQuoteQuantity` | `baseQuantityUnits` | * | ----- |-------- | ------------------------- | --------------------------- | ------------------- | * | Long | Sell | get most amt. of vQuote | upper bound of input quote | negative | * | Short | Buy | pay least amt. of vQuote | lower bound of output quote | positive | * | ----------------------------------------------------------------------------------------------- | * * @param _setToken Instance of the SetToken * @param _baseToken Address virtual token being traded * @param _baseQuantityUnits Quantity of virtual token to trade in position units * @param _receiveQuoteQuantityUnits Max/min of vQuote asset to pay/receive when buying or selling */ function trade( ISetToken _setToken, address _baseToken, int256 _baseQuantityUnits, uint256 _receiveQuoteQuantityUnits ) external nonReentrant onlyManagerAndValidSet(_setToken) { ActionInfo memory actionInfo = _createAndValidateActionInfo( _setToken, _baseToken, _baseQuantityUnits, _receiveQuoteQuantityUnits ); (uint256 deltaBase, uint256 deltaQuote) = _executeTrade(actionInfo); uint256 protocolFee = _accrueProtocolFee(_setToken, deltaQuote); _updatePositionList(_setToken, _baseToken); emit PerpTrade( _setToken, _baseToken, deltaBase, deltaQuote, protocolFee, _baseQuantityUnits > 0 ); } /** * @dev MANAGER ONLY: Deposits default position collateral token into the PerpV2 Vault, increasing * the size of the Perp account external position. This method is useful for establishing initial * collateralization ratios, e.g the flow when setting up a 2X external position would be to deposit * 100 units of USDC and execute a lever trade for ~200 vUSDC worth of vToken with the difference * between these made up as automatically "issued" margin debt in the PerpV2 system. * * @param _setToken Instance of the SetToken * @param _collateralQuantityUnits Quantity of collateral to deposit in position units */ function deposit( ISetToken _setToken, uint256 _collateralQuantityUnits ) public nonReentrant onlyManagerAndValidSet(_setToken) { require(_collateralQuantityUnits > 0, "Deposit amount is 0"); require(_setToken.totalSupply() > 0, "SetToken supply is 0"); uint256 notionalDepositedQuantity = _depositAndUpdatePositions(_setToken, _collateralQuantityUnits); emit CollateralDeposited(_setToken, collateralToken, notionalDepositedQuantity); } /** * @dev MANAGER ONLY: Withdraws collateral token from the PerpV2 Vault to a default position on * the SetToken. This method is useful when adjusting the overall composition of a Set which has * a Perp account external position as one of several components. * * NOTE: Within PerpV2, `withdraw` settles `owedRealizedPnl` and any pending funding payments * to the Perp vault prior to transfer. * * @param _setToken Instance of the SetToken * @param _collateralQuantityUnits Quantity of collateral to withdraw in position units */ function withdraw( ISetToken _setToken, uint256 _collateralQuantityUnits ) public nonReentrant onlyManagerAndValidSet(_setToken) { require(_collateralQuantityUnits > 0, "Withdraw amount is 0"); require(_setToken.totalSupply() > 0, "SetToken supply is 0"); uint256 notionalWithdrawnQuantity = _withdrawAndUpdatePositions(_setToken, _collateralQuantityUnits); emit CollateralWithdrawn(_setToken, collateralToken, notionalWithdrawnQuantity); } /** * @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the * allowed list or anySetAllowed needs to be true. * * @param _setToken Instance of the SetToken to initialize */ function initialize( ISetToken _setToken ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { if (!anySetAllowed) { require(allowedSetTokens[_setToken], "Not allowed SetToken"); } // Initialize module before trying register _setToken.initializeModule(); // Get debt issuance module registered to this module and require that it is initialized require(_setToken.isInitializedModule( getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)), "Issuance not initialized" ); // Try if register exists on any of the modules including the debt issuance module address[] memory modules = _setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).registerToIssuanceModule(_setToken) {} catch {} } } /** * @dev MANAGER ONLY: Removes this module from the SetToken, via call by the SetToken. Deletes * position mappings associated with SetToken. * * NOTE: Function will revert if there is greater than a position unit amount of USDC left in the PerpV2 vault. */ function removeModule() external override onlyValidAndInitializedSet(ISetToken(msg.sender)) { ISetToken setToken = ISetToken(msg.sender); // We can end up with a dust amount of USDC in the Perp account that we should ignore. require( _fromPreciseUnitToDecimals(_getCollateralBalance(setToken), collateralDecimals) <= 1, "Collateral balance remaining" ); delete positions[setToken]; // Should already be empty // Try if unregister exists on any of the modules address[] memory modules = setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).unregisterFromIssuanceModule(setToken) {} catch {} } } /** * @dev MANAGER ONLY: Add registration of this module on the debt issuance module for the SetToken. * * Note: if the debt issuance module is not added to SetToken before this module is initialized, then * this function needs to be called if the debt issuance module is later added and initialized to prevent state * inconsistencies * * @param _setToken Instance of the SetToken * @param _debtIssuanceModule Debt issuance module address to register */ function registerToModule(ISetToken _setToken, IDebtIssuanceModule _debtIssuanceModule) external onlyManagerAndValidSet(_setToken) { require(_setToken.isInitializedModule(address(_debtIssuanceModule)), "Issuance not initialized"); _debtIssuanceModule.registerToIssuanceModule(_setToken); } /** * @dev GOVERNANCE ONLY: Enable/disable ability of a SetToken to initialize this module. * * @param _setToken Instance of the SetToken * @param _status Bool indicating if _setToken is allowed to initialize this module */ function updateAllowedSetToken(ISetToken _setToken, bool _status) external onlyOwner { require(controller.isSet(address(_setToken)) || allowedSetTokens[_setToken], "Invalid SetToken"); allowedSetTokens[_setToken] = _status; emit SetTokenStatusUpdated(_setToken, _status); } /** * @dev GOVERNANCE ONLY: Toggle whether ANY SetToken is allowed to initialize this module. * * @param _anySetAllowed Bool indicating if ANY SetToken is allowed to initialize this module */ function updateAnySetAllowed(bool _anySetAllowed) external onlyOwner { anySetAllowed = _anySetAllowed; emit AnySetAllowedUpdated(_anySetAllowed); } /** * @dev MODULE ONLY: Hook called prior to issuance. Only callable by valid module. Should only be called ONCE * during issue. Trades into current positions and sets the collateralToken's externalPositionUnit so that * issuance module can transfer in the right amount of collateral accounting for accrued fees/pnl and slippage * incurred during issuance. Any pending funding payments and accrued owedRealizedPnl are attributed to current * Set holders. * * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of Set to issue */ function moduleIssueHook( ISetToken _setToken, uint256 _setTokenQuantity ) external override onlyModule(_setToken) { if (_setToken.totalSupply() == 0) return; int256 newExternalPositionUnit = _executeModuleIssuanceHook(_setToken, _setTokenQuantity, false); // Set collateralToken externalPositionUnit such that DIM can use it for transfer calculation _setToken.editExternalPositionUnit( address(collateralToken), address(this), newExternalPositionUnit ); } /** * @dev MODULE ONLY: Hook called prior to redemption in the issuance module. Trades out of existing * positions to make redemption capital withdrawable from PerpV2 vault. Sets the `externalPositionUnit` * equal to the realizable value of account in position units (as measured by the trade outcomes for * this redemption). Any `owedRealizedPnl` and pending funding payments are socialized in this step so * that redeemer pays/receives their share of them. Should only be called ONCE during redeem. * * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken to redeem */ function moduleRedeemHook( ISetToken _setToken, uint256 _setTokenQuantity ) external override onlyModule(_setToken) { if (_setToken.totalSupply() == 0) return; int256 newExternalPositionUnit = _executeModuleRedemptionHook(_setToken, _setTokenQuantity, false); // Set USDC externalPositionUnit such that DIM can use it for transfer calculation _setToken.editExternalPositionUnit( address(collateralToken), address(this), newExternalPositionUnit ); } /** * @dev MODULE ONLY: Hook called prior to looping through each component on issuance. Deposits * collateral into Perp protocol from SetToken default position. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken to issue * @param _component Address of deposit collateral component */ function componentIssueHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external override onlyModule(_setToken) { if (_isEquity) { int256 externalPositionUnit = _setToken.getExternalPositionRealUnit(address(_component), address(this)); // Use preciseMulCeil here to ensure correct collateralization if there are rounding errors. uint256 usdcTransferInNotionalQuantity = _setTokenQuantity.preciseMulCeil(externalPositionUnit.toUint256()); _deposit(_setToken, usdcTransferInNotionalQuantity); } } /** * @dev MODULE ONLY: Hook called prior to looping through each component on redemption. Withdraws * collateral from Perp protocol to SetToken default position *without* updating the default position unit. * Called by issuance module's `resolveEquityPositions` method which immediately transfers the collateral * component from SetToken to redeemer after this hook executes. * * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken to redeem * @param _component Address of deposit collateral component */ function componentRedeemHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external override onlyModule(_setToken) { if (_isEquity) { int256 externalPositionUnit = _setToken.getExternalPositionRealUnit(address(_component), address(this)); uint256 usdcTransferOutNotionalQuantity = _setTokenQuantity.preciseMul(externalPositionUnit.toUint256()); _withdraw(_setToken, usdcTransferOutNotionalQuantity); } } /* ============ External Getter Functions ============ */ /** * @dev Gets the positive equity collateral externalPositionUnit that would be calculated for * issuing a quantity of SetToken, representing the amount of collateral that would need to * be transferred in per SetToken. * * @param _setToken Instance of SetToken * @param _setTokenQuantity Number of sets to issue * * @return equityAdjustments array containing a single element and an empty debtAdjustments array */ function getIssuanceAdjustments( ISetToken _setToken, uint256 _setTokenQuantity ) external returns (int256[] memory, int256[] memory) { address[] memory components = _setToken.getComponents(); if (positions[_setToken].length > 0) { int256 newExternalPositionUnit = _executeModuleIssuanceHook(_setToken, _setTokenQuantity, true); return _formatAdjustments(_setToken, components, newExternalPositionUnit); } else { return _formatAdjustments(_setToken, components, 0); } } /** * @dev Gets the positive equity collateral externalPositionUnit that would be calculated for * redeeming a quantity of SetToken representing the amount of collateral returned per SetToken. * * @param _setToken Instance of SetToken * @param _setTokenQuantity Number of sets to issue * * @return equityAdjustments array containing a single element and an empty debtAdjustments array */ function getRedemptionAdjustments( ISetToken _setToken, uint256 _setTokenQuantity ) external returns (int256[] memory, int256[] memory _) { address[] memory components = _setToken.getComponents(); if (positions[_setToken].length > 0) { int256 newExternalPositionUnit = _executeModuleRedemptionHook(_setToken, _setTokenQuantity, true); return _formatAdjustments(_setToken, components, newExternalPositionUnit); } else { return _formatAdjustments(_setToken, components, 0); } } /** * @dev Returns a PositionUnitNotionalInfo array representing all positions open for the SetToken. * * @param _setToken Instance of SetToken * * @return PositionUnitInfo array, in which each element has properties: * * + baseToken: address, * + baseBalance: baseToken balance as notional quantity (10**18) * + quoteBalance: USDC quote asset balance as notional quantity (10**18) */ function getPositionNotionalInfo(ISetToken _setToken) public view returns (PositionNotionalInfo[] memory) { PositionNotionalInfo[] memory positionInfo = new PositionNotionalInfo[](positions[_setToken].length); for(uint i = 0; i < positions[_setToken].length; i++){ positionInfo[i] = PositionNotionalInfo({ baseToken: positions[_setToken][i], baseBalance: perpAccountBalance.getBase( address(_setToken), positions[_setToken][i] ), quoteBalance: perpAccountBalance.getQuote( address(_setToken), positions[_setToken][i] ) }); } return positionInfo; } /** * @dev Returns a PositionUnitInfo array representing all positions open for the SetToken. * * @param _setToken Instance of SetToken * * @return PositionUnitInfo array, in which each element has properties: * * + baseToken: address, * + baseUnit: baseToken balance as position unit (10**18) * + quoteUnit: USDC quote asset balance as position unit (10**18) */ function getPositionUnitInfo(ISetToken _setToken) public view returns (PositionUnitInfo[] memory) { int256 totalSupply = _setToken.totalSupply().toInt256(); PositionUnitInfo[] memory positionInfo = new PositionUnitInfo[](positions[_setToken].length); for(uint i = 0; i < positions[_setToken].length; i++){ positionInfo[i] = PositionUnitInfo({ baseToken: positions[_setToken][i], baseUnit: perpAccountBalance.getBase( address(_setToken), positions[_setToken][i] ).preciseDiv(totalSupply), quoteUnit: perpAccountBalance.getQuote( address(_setToken), positions[_setToken][i] ).preciseDiv(totalSupply) }); } return positionInfo; } /** * @dev Gets Perp account info for SetToken. Returns an AccountInfo struct containing account wide * (rather than position specific) balance info * * @param _setToken Instance of the SetToken * * @return accountInfo struct with properties for: * * + collateral balance (10**18, regardless of underlying collateral decimals) * + owed realized Pnl` (10**18) * + pending funding payments (10**18) */ function getAccountInfo(ISetToken _setToken) public view returns (AccountInfo memory accountInfo) { (int256 owedRealizedPnl,, ) = perpAccountBalance.getPnlAndPendingFee(address(_setToken)); (int256 netQuoteBalance, ) = perpAccountBalance.getNetQuoteBalanceAndPendingFee(address(_setToken)); // NOTE: pendingFundingPayments are represented as in the Perp system as "funding owed" // e.g a positive number is a debt which gets subtracted from owedRealizedPnl on settlement. // We are flipping its sign here to reflect its settlement value. accountInfo = AccountInfo({ collateralBalance: _getCollateralBalance(_setToken), owedRealizedPnl: owedRealizedPnl, pendingFundingPayments: perpExchange.getAllPendingFundingPayment(address(_setToken)).mul(-1), netQuoteBalance: netQuoteBalance }); } /** * @dev Gets the mid-point price of a virtual asset from UniswapV3 markets maintained by Perp Protocol * * @param _baseToken) Address of virtual token to price * @return price Mid-point price of virtual token in UniswapV3 AMM market */ function getAMMSpotPrice(address _baseToken) public view returns (uint256 price) { address pool = perpMarketRegistry.getPool(_baseToken); (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); uint256 priceX96 = _formatSqrtPriceX96ToPriceX96(sqrtPriceX96); return _formatX96ToX10_18(priceX96); } /* ============ Internal Functions ============ */ /** * @dev MODULE ONLY: Hook called prior to issuance. Only callable by valid module. * * NOTE: OwedRealizedPnl and PendingFunding values can be either positive or negative * * OwedRealizedPnl * --------------- * Accrues when trades execute and result in a profit or loss per the table * below. Each withdrawal zeros out `owedRealizedPnl`, settling it to the vault. * * | -------------------------------------------------- | * | Position Type | AMM Spot Price | Action | Value | * | ------------- | -------------- | ------ | ------- | * | Long | Rises | Sell | Positive | * | Long | Falls | Sell | Negative | * | Short | Rises | Buy | Negative | * | Short | Falls | Buy | Positive | * | -------------------------------------------------- | * * * PendingFunding * -------------- * The direction of this flow is determined by the difference between virtual asset UniV3 spot prices and * their parent asset's broader market price (as represented by a Chainlink oracle), per the table below. * Each trade zeroes out `pendingFunding`, settling it to owedRealizedPnl. * * | --------------------------------------- | * | Position Type | Oracle Price | Value | * | ------------- | ------------ | -------- | * | Long | Below AMM | Negative | * | Long | Above AMM | Positive | * | Short | Below AMM | Positive | * | Short | Above AMM | Negative | * | --------------------------------------- | * * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of Set to issue * @param _isSimulation If true, trading is only simulated (to return issuance adjustments) */ function _executeModuleIssuanceHook( ISetToken _setToken, uint256 _setTokenQuantity, bool _isSimulation ) internal returns (int256) { // From perp: // accountValue = collateral <--- // + owedRealizedPnl } totalCollateralValue // + pendingFundingPayment <--- // + sum_over_market(positionValue_market) // + netQuoteBalance AccountInfo memory accountInfo = getAccountInfo(_setToken); int256 usdcAmountIn = accountInfo.collateralBalance .add(accountInfo.owedRealizedPnl) .add(accountInfo.pendingFundingPayments) .add(accountInfo.netQuoteBalance) .preciseDiv(_setToken.totalSupply().toInt256()) .preciseMul(_setTokenQuantity.toInt256()); PositionUnitInfo[] memory positionInfo = getPositionUnitInfo(_setToken); for(uint i = 0; i < positionInfo.length; i++) { // baseUnit, +ve existing long position, -ve for existing short position int256 baseTradeNotionalQuantity = positionInfo[i].baseUnit.preciseMul(_setTokenQuantity.toInt256()); ActionInfo memory actionInfo = _createAndValidateActionInfoNotional( _setToken, positionInfo[i].baseToken, baseTradeNotionalQuantity, 0 ); int256 spotPrice = getAMMSpotPrice(positionInfo[i].baseToken).toInt256(); // idealDeltaQuote, +ve for existing long position, -ve for existing short position int256 idealDeltaQuote = baseTradeNotionalQuantity.preciseMul(spotPrice); // Execute or simulate trade. // `deltaQuote` is always a positive number (, uint256 deltaQuote) = _isSimulation ? _simulateTrade(actionInfo) : _executeTrade(actionInfo); // Calculate slippage quantity as a positive value // When long, trade slippage results in more quote required, deltaQuote > idealDeltaQuote // When short, trade slippage results in less quote receivied, abs(idealDeltaQuote) > abs(deltaQuote) int256 slippageQuantity = baseTradeNotionalQuantity >= 0 ? deltaQuote.toInt256().sub(idealDeltaQuote) : _abs(idealDeltaQuote).sub(deltaQuote.toInt256()); // slippage is borne by the issuer usdcAmountIn = usdcAmountIn.add(idealDeltaQuote).add(slippageQuantity); } // Return value in collateral decimals (e.g USDC = 6) return _fromPreciseUnitToDecimals( usdcAmountIn.preciseDiv(_setTokenQuantity.toInt256()), collateralDecimals ); } /** * @dev Hook called prior to redemption. Only callable by valid module. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of Set to redeem * @param _isSimulation If true, trading is only simulated (to return issuance adjustments) */ function _executeModuleRedemptionHook( ISetToken _setToken, uint256 _setTokenQuantity, bool _isSimulation ) internal returns (int256) { int256 realizedPnl = 0; PositionNotionalInfo[] memory positionInfo = getPositionNotionalInfo(_setToken); AccountInfo memory accountInfo = getAccountInfo(_setToken); // Calculate already accrued PnL from non-issuance/redemption sources (ex: levering) int256 totalFundingAndCarriedPnL = accountInfo.pendingFundingPayments.add(accountInfo.owedRealizedPnl); int256 owedRealizedPnlPositionUnit = totalFundingAndCarriedPnL.preciseDiv(_setToken.totalSupply().toInt256()); for (uint256 i = 0; i < positionInfo.length; i++) { // Calculate amount to trade int256 basePositionUnit = positionInfo[i].baseBalance.preciseDiv(_setToken.totalSupply().toInt256()); int256 baseTradeNotionalQuantity = basePositionUnit.preciseMul(_setTokenQuantity.toInt256()); // Calculate amount quote debt will be reduced by int256 reducedOpenNotional = _getReducedOpenNotional( _setTokenQuantity.toInt256(), basePositionUnit, positionInfo[i] ); // Trade, inverting notional quantity sign because we are reducing position ActionInfo memory actionInfo = _createAndValidateActionInfoNotional( _setToken, positionInfo[i].baseToken, baseTradeNotionalQuantity.mul(-1), 0 ); // Execute or simulate trade. // `deltaQuote` is always a positive number (,uint256 deltaQuote) = _isSimulation ? _simulateTrade(actionInfo) : _executeTrade(actionInfo); // Calculate realized PnL for and add to running total. // When basePositionUnit is positive, position is long. realizedPnl = basePositionUnit >= 0 ? realizedPnl.add(reducedOpenNotional.add(deltaQuote.toInt256())) : realizedPnl.add(reducedOpenNotional.sub(deltaQuote.toInt256())); } // Calculate amount of collateral to withdraw int256 collateralPositionUnit = _getCollateralBalance(_setToken).preciseDiv(_setToken.totalSupply().toInt256()); int256 usdcToWithdraw = collateralPositionUnit.preciseMul(_setTokenQuantity.toInt256()) .add(owedRealizedPnlPositionUnit.preciseMul(_setTokenQuantity.toInt256())) .add(realizedPnl); return _fromPreciseUnitToDecimals( usdcToWithdraw.preciseDiv(_setTokenQuantity.toInt256()), collateralDecimals ); } /** * @dev Invoke deposit from SetToken using PerpV2 library. Creates a collateral deposit in Perp vault * Updates the collateral token default position unit. This function is called directly by * the componentIssue hook, skipping external position unit setting because that method is assumed * to be the end of a call sequence (e.g manager will not need to read the updated value) */ function _deposit(ISetToken _setToken, uint256 _collateralNotionalQuantity) internal { _setToken.invokeApprove( address(collateralToken), address(perpVault), _collateralNotionalQuantity ); _setToken.invokeDeposit(perpVault, collateralToken, _collateralNotionalQuantity); } /** * Approves and deposits collateral units into Perp vault and additionally sets collateral token externalPositionUnit * so Manager contracts have a value they can base calculations for further trading on within the same transaction. * * NOTE: This flow is only used when invoking the external `deposit` function - it converts collateral * quantity units into a notional quantity. */ function _depositAndUpdatePositions( ISetToken _setToken, uint256 _collateralQuantityUnits ) internal returns (uint256) { uint256 initialCollateralPositionBalance = collateralToken.balanceOf(address(_setToken)); uint256 collateralNotionalQuantity = _collateralQuantityUnits.preciseMul(_setToken.totalSupply()); _deposit(_setToken, collateralNotionalQuantity); _setToken.calculateAndEditDefaultPosition( address(collateralToken), _setToken.totalSupply(), initialCollateralPositionBalance ); _setToken.editExternalPosition( address(collateralToken), address(this), _calculateExternalPositionUnit(_setToken), "" ); return collateralNotionalQuantity; } /** * @dev Invoke withdraw from SetToken using PerpV2 library. Withdraws collateral token from Perp vault * into a default position. This function is called directly by _accrueFee and _moduleRedeemHook, * skipping position unit state updates because the funds withdrawn to SetToken are immediately * forwarded to `feeRecipient` and SetToken owner respectively. */ function _withdraw(ISetToken _setToken, uint256 _collateralNotionalQuantity) internal { if (_collateralNotionalQuantity == 0) return; _setToken.invokeWithdraw(perpVault, collateralToken, _collateralNotionalQuantity); } /** * Withdraws collateral units from Perp vault to SetToken and additionally sets both the collateralToken * externalPositionUnit (so Manager contracts have a value they can base calculations for further * trading on within the same transaction), and the collateral token default position unit. * * NOTE: This flow is only used when invoking the external `withdraw` function - it converts * a collateral units quantity into a notional quantity before invoking withdraw. */ function _withdrawAndUpdatePositions( ISetToken _setToken, uint256 _collateralQuantityUnits ) internal returns (uint256) { uint256 initialCollateralPositionBalance = collateralToken.balanceOf(address(_setToken)); uint256 collateralNotionalQuantity = _collateralQuantityUnits.preciseMul(_setToken.totalSupply()); _withdraw(_setToken, collateralNotionalQuantity); _setToken.calculateAndEditDefaultPosition( address(collateralToken), _setToken.totalSupply(), initialCollateralPositionBalance ); _setToken.editExternalPosition( address(collateralToken), address(this), _calculateExternalPositionUnit(_setToken), "" ); return collateralNotionalQuantity; } /** * @dev Formats Perp Protocol openPosition call and executes via SetToken (and PerpV2 lib) * @return uint256 The base position delta resulting from the trade * @return uint256 The quote asset position delta resulting from the trade */ function _executeTrade(ActionInfo memory _actionInfo) internal returns (uint256, uint256) { IClearingHouse.OpenPositionParams memory params = IClearingHouse.OpenPositionParams({ baseToken: _actionInfo.baseToken, isBaseToQuote: _actionInfo.isBaseToQuote, isExactInput: _actionInfo.isExactInput, amount: _actionInfo.amount.toUint256(), oppositeAmountBound: _actionInfo.oppositeAmountBound, deadline: PreciseUnitMath.maxUint256(), sqrtPriceLimitX96: 0, referralCode: bytes32(0) }); return _actionInfo.setToken.invokeOpenPosition(perpClearingHouse, params); } /** * @dev Formats Perp Periphery Quoter.swap call and executes via SetToken (and PerpV2 lib) * @return uint256 The base position delta resulting from the trade * @return uint256 The quote asset position delta resulting from the trade */ function _simulateTrade(ActionInfo memory _actionInfo) internal returns (uint256, uint256) { IQuoter.SwapParams memory params = IQuoter.SwapParams({ baseToken: _actionInfo.baseToken, isBaseToQuote: _actionInfo.isBaseToQuote, isExactInput: _actionInfo.isExactInput, amount: _actionInfo.amount.toUint256(), sqrtPriceLimitX96: 0 }); IQuoter.SwapResponse memory swapResponse = _actionInfo.setToken.invokeSwap(perpQuoter, params); return (swapResponse.deltaAvailableBase, swapResponse.deltaAvailableQuote); } /** * @dev Calculates protocol fee on module and pays protocol fee from SetToken * @return uint256 Total protocol fee paid in underlying collateral decimals e.g (USDC = 6) */ function _accrueProtocolFee( ISetToken _setToken, uint256 _exchangedQuantity ) internal returns(uint256) { uint256 protocolFee = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity); uint256 protocolFeeInCollateralDecimals = _fromPreciseUnitToDecimals( protocolFee, collateralDecimals ); _withdraw(_setToken, protocolFeeInCollateralDecimals); payProtocolFeeFromSetToken(_setToken, address(collateralToken), protocolFeeInCollateralDecimals); return protocolFeeInCollateralDecimals; } /** * @dev Construct the ActionInfo struct for trading. This method takes POSITION UNIT amounts and passes to * _createAndValidateActionInfoNotional to create the struct. If the _baseTokenQuantity is zero then revert. * * @param _setToken Instance of the SetToken * @param _baseToken Address of base token being traded into/out of * @param _baseTokenUnits Quantity of baseToken to trade in PositionUnits * @param _quoteReceiveUnits Quantity of quote to receive if selling base and pay if buying, in PositionUnits * * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfo( ISetToken _setToken, address _baseToken, int256 _baseTokenUnits, uint256 _quoteReceiveUnits ) internal view returns(ActionInfo memory) { require(_baseTokenUnits != 0, "Amount is 0"); uint256 totalSupply = _setToken.totalSupply(); return _createAndValidateActionInfoNotional( _setToken, _baseToken, _baseTokenUnits.preciseMul(totalSupply.toInt256()), _quoteReceiveUnits.preciseMul(totalSupply) ); } /** * @dev Construct the ActionInfo struct for trading. This method takes NOTIONAL token amounts and creates * the struct. If the _baseTokenQuantity is less than zero then we are selling the baseToken. * * | ---------------------------------------------------------------------------------------------| * | Action | isShort | isB2Q | Exact In / Out | Amount | Opposit Bound Description | * | ------- |---------|--------|-----------------------|-----------|---------------------------- | * | Sell | true | true | exact input (true) | baseToken | Min quote to receive | * | Buy | false | false | exact output (false) | baseToken | Max quote to pay | * |----------------------------------------------------------------------------------------------| * * @param _setToken Instance of the SetToken * @param _baseToken Address of base token being traded into/out of * @param _baseTokenQuantity Notional quantity of baseToken to trade * @param _quoteReceiveQuantity Notional quantity of quote to receive if selling base and pay if buying * * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfoNotional( ISetToken _setToken, address _baseToken, int256 _baseTokenQuantity, uint256 _quoteReceiveQuantity ) internal pure returns(ActionInfo memory) { // NOT checking that _baseTokenQuantity != 0 here because for places this is directly called // (issue/redeem hooks) we know they position cannot be 0. We check in _createAndValidateActionInfo // that quantity is 0 for inputs to trade. bool isShort = _baseTokenQuantity < 0; return ActionInfo({ setToken: _setToken, baseToken: _baseToken, isBaseToQuote: isShort, isExactInput: isShort, amount: _abs(_baseTokenQuantity), oppositeAmountBound: _quoteReceiveQuantity }); } /** * @dev Update position address array if a token has been newly added or completely sold off * during lever/delever */ function _updatePositionList(ISetToken _setToken, address _baseToken) internal { int256 baseBalance = perpAccountBalance.getBase(address(_setToken), _baseToken); address[] memory positionList = positions[_setToken]; if (positionList.contains(_baseToken) && baseBalance == 0) { positions[_setToken].removeStorage(_baseToken); } else if (!positionList.contains(_baseToken)) { positions[_setToken].push(_baseToken); } } /** * @dev Gets the ratio by which redemption will reduce open notional quote balance. This value * is used to calculate realizedPnl of the asset sale in _executeModuleRedeemHook */ function _getReducedOpenNotional( int256 _setTokenQuantity, int256 _basePositionUnit, PositionNotionalInfo memory _positionInfo ) internal pure returns (int256) { // From perp formulas: closeRatio = abs(baseTradeNotional) / abs(baseBalance) int256 baseTradeNotionalQuantity = _setTokenQuantity.preciseMul(_basePositionUnit); int256 closeRatio = _abs(baseTradeNotionalQuantity).preciseDiv(_abs(_positionInfo.baseBalance)); return _positionInfo.quoteBalance.preciseMul(closeRatio); } /** * @dev Calculates the sum of collateralToken denominated market-prices of assets and debt for the Perp account per * SetToken */ function _calculateExternalPositionUnit(ISetToken _setToken) internal view returns (int256) { PositionNotionalInfo[] memory positionInfo = getPositionNotionalInfo(_setToken); AccountInfo memory accountInfo = getAccountInfo(_setToken); int256 totalPositionValue = 0; for (uint i = 0; i < positionInfo.length; i++ ) { int256 spotPrice = getAMMSpotPrice(positionInfo[i].baseToken).toInt256(); totalPositionValue = totalPositionValue.add( positionInfo[i].baseBalance.preciseMul(spotPrice) ); } int256 externalPositionUnitInPrecisionDecimals = totalPositionValue .add(accountInfo.collateralBalance) .add(accountInfo.netQuoteBalance) .add(accountInfo.owedRealizedPnl) .add(accountInfo.pendingFundingPayments) .preciseDiv(_setToken.totalSupply().toInt256()); return _fromPreciseUnitToDecimals( externalPositionUnitInPrecisionDecimals, collateralDecimals ); } // @dev Retrieves collateral balance as an an 18 decimal vUSDC quote value function _getCollateralBalance(ISetToken _setToken) internal view returns (int256) { int256 balance = perpVault.getBalance(address(_setToken)); return _toPreciseUnitsFromDecimals(balance, collateralDecimals); } /** * @dev Returns issuance or redemption adjustments in the format expected by `SlippageIssuanceModule`. * The last recorded externalPositionUnit (current) is subtracted from a dynamically generated * externalPositionUnit (new) and set in an `equityAdjustments` array which is the same length as * the SetToken's components array, at the same index the collateral token occupies in the components * array. All other values are left unset (0). An empty-value components length debtAdjustments * array is also returned. */ function _formatAdjustments( ISetToken _setToken, address[] memory _components, int256 _newExternalPositionUnit ) internal view returns (int256[] memory, int256[] memory) { int256[] memory equityAdjustments = new int256[](_components.length); int256[] memory debtAdjustments = new int256[](_components.length); (uint256 index, bool isIn) = _components.indexOf(address(collateralToken)); if (isIn) { int256 currentExternalPositionUnit = _setToken.getExternalPositionRealUnit( address(collateralToken), address(this) ); equityAdjustments[index] = _newExternalPositionUnit.sub(currentExternalPositionUnit); } return (equityAdjustments, debtAdjustments); } /** * @dev Converts a UniswapV3 sqrtPriceX96 value to a priceX96 value. This method is borrowed from * PerpProtocol's `lushan` repo, in lib/PerpMath and used by `getAMMSpotPrice` while generating a * PRECISE_UNIT vAsset market price */ function _formatSqrtPriceX96ToPriceX96(uint160 sqrtPriceX96) internal pure returns (uint256) { return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96); } /** * @dev Converts a UniswapV3 X96 format price into a PRECISE_UNIT price. This method is borrowed from * PerpProtocol's `lushan` repo, in lib/PerpMath and used by `getAMMSpotPrice` while generating a * PRECISE_UNIT vAsset market price */ function _formatX96ToX10_18(uint256 valueX96) internal pure returns (uint256) { return FullMath.mulDiv(valueX96, 1 ether, FixedPoint96.Q96); } /** * @dev Converts a uint256 PRECISE_UNIT quote quantity into an alternative decimal format. In Perp all * assets are 18 decimal quantities we need to represent as 6 decimal USDC quantities when setting * position units or withdrawing from Perp's Vault contract. * * This method is borrowed from PerpProtocol's `lushan` repo in lib/SettlementTokenMath */ function _fromPreciseUnitToDecimals(uint256 amount, uint8 decimals) internal pure returns (uint256) { return amount.div(10**(18 - uint(decimals))); } /** * @dev Converts an int256 PRECISE_UNIT quote quantity into an alternative decimal format. In Perp all * assets are 18 decimal quantities we need to represent as 6 decimal USDC quantities when setting * position units or withdrawing from Perp's Vault contract. * * This method is borrowed from PerpProtocol's `lushan` repo in lib/SettlementTokenMath */ function _fromPreciseUnitToDecimals(int256 amount, uint8 decimals) internal pure returns (int256) { return amount.div(int256(10**(18 - uint(decimals)))); } /** * @dev Converts an arbitrarily decimalized quantity into a PRECISE_UNIT quantity. In Perp the vault * balance is represented as a 6 decimals USDC quantity which we need to consume in PRECISE_UNIT * format when calculating values like the external position unit and current leverage. */ function _toPreciseUnitsFromDecimals(int256 amount, uint8 decimals) internal pure returns (int256) { return amount.mul(int256(10**(18 - (uint(decimals))))); } function _abs(int x) internal pure returns (int) { return x >= 0 ? x : x.mul(-1); } }
Converts a uint256 PRECISE_UNIT quote quantity into an alternative decimal format. In Perp all assets are 18 decimal quantities we need to represent as 6 decimal USDC quantities when setting position units or withdrawing from Perp's Vault contract. This method is borrowed from PerpProtocol's `lushan` repo in lib/SettlementTokenMath/
function _fromPreciseUnitToDecimals(uint256 amount, uint8 decimals) internal pure returns (uint256) { return amount.div(10**(18 - uint(decimals))); }
7,220,975
./full_match/43113/0x0bC8cc281561e2b64B4027437A9E20A53c0F70E7/sources/contracts/sol.sol
first 32 bytes, after the length prefix second 32 bytes final byte (first byte of the next 32 bytes)
function splitSignature(bytes memory sig) public pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(sig.length == 66, "invalid signature length"); assembly { First 32 bytes stores the length of the signature add(sig, 32) = pointer of sig + 32 effectively, skips first 32 bytes of signature mload(p) loads next 32 bytes starting at the memory address p into memory r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) }
7,137,776
./full_match/42220/0x9F4116AdFd83c30dBAA5146D17d1f5A9a56b1502/sources/contracts/lbp/LBPManagerFactory.sol
Set LBPManager contract which works as a base for clones. _masterCopy The address of the new LBPManager basis./
function setMasterCopy(address _masterCopy) external onlyOwner validAddress(_masterCopy) { emit MastercopyChanged(masterCopy, _masterCopy); masterCopy = _masterCopy; }
16,336,753
./full_match/11155111/0x1b502402EB8fD08e657a4a2Bd6424AEc899D3c38/sources/contracts/libraries/InteractionLogic.sol
Emits the `Collected` event that signals that a successful collect action has occurred. This is done through this function to prevent stack too deep compilation error. collector The address collecting the publication. profileId The token ID of the profile that the collect was initiated towards, useful to differentiate mirrors. pubId The publication ID that the collect was initiated towards, useful to differentiate mirrors. rootProfileId The profile token ID of the profile whose publication is being collected. rootPubId The publication ID of the publication being collected. data The data passed to the collect module./
function _emitCollectedEvent( address collector, uint256 profileId, uint256 pubId, uint256 rootProfileId, uint256 rootPubId, bytes calldata data ) private { emit Events.Collected( collector, profileId, pubId, rootProfileId, rootPubId, data, block.timestamp ); }
3,800,459
./full_match/1/0x467a2B91f231D930F5eeB6B982C7666E81DA8626/sources/contracts/nft/ZKSeaNFT.sol
Update withdrawal info, while the caller need deal with the transfer
function onWithdraw(address target, uint64 globalId) external onlyZksCore returns (address, uint256) { require(globalId > 0, "ZKSeaNFT: invalid withdraw id"); bytes28 key = packWithdrawKey(target, globalId); require(toWithdraw[key], "ZKSeaNFT: invalid withdraw key"); toWithdraw[key] = false; L1Info memory info = infoMapL1[globalId]; return (info.tokenContract, info.tokenId); }
3,857,727
./partial_match/97/0x8F299669251f2b7828de18046829Daca7b7406a0/sources/MFXToken.sol
Destroys `amount` tokens from `account`, deducting from the caller's allowance. See {BEP20-_burn} and {BEP20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least `amount`./
function burnFrom(address account, uint256 amount) public virtual returns (bool) { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "BEP20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); return true; }
11,488,532
pragma solidity ^0.5.2; contract ModExp { // address constant MODEXP_BUILTIN = 0x0000000000000000000000000000000000000005; function modexp(uint256 b, uint256 e, uint256 m) internal returns(uint256 result) { assembly { let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem,0x20), 0x20) mstore(add(freemem,0x40), 0x20) mstore(add(freemem,0x60), b) mstore(add(freemem,0x80), e) mstore(add(freemem,0xA0), m) let _ := call(39240, 0x0000000000000000000000000000000000000005, 0, freemem, 0xC0, freemem, 0x20) result := mload(freemem) } } } // Library for secp256r1, forked from https://github.com/tls-n/tlsnutils/blob/master/contracts/ECMath.sol contract p256Lib is ModExp { //curve parameters secp256r1 uint256 constant A = 115792089210356248762697446949407573530086143415290314195533631308867097853948; uint256 constant B = 41058363725152142129326129780047268409114441015993725554835256314039467401291; uint256 constant GX = 48439561293906451759052585252797914202762949526041747995844080717082404635286; uint256 constant GY = 36134250956749795798585127919587881956611106672985015071877198253568414405109; uint256 constant P = 115792089210356248762697446949407573530086143415290314195533631308867097853951; uint256 constant N = 115792089210356248762697446949407573529996955224135760342422259061068512044369; uint256 constant H = 1; function verify(uint256 e, uint256 r, uint256 s, uint256 qx, uint256 qy) public returns(bool) { uint256 w = invmod(s, N); (uint ret1, uint ret2, uint ret3) = assemblyShamir(mulmod(e, w, N), mulmod(r, w, N), qx, qy); uint256 zInv2 = modexp(ret3, P - 3, P); uint256 x = mulmod(ret1, zInv2, P); // JtoA(comb)[0]; return r == x; } function recover(uint256 e, uint8 v, uint256 r, uint256 s) public returns(uint256[2] memory) { uint256 eInv = N - e; uint256 rInv = invmod(r, N); uint256 srInv = mulmod(rInv, s, N); uint256 eInvrInv = mulmod(rInv, eInv, N); uint256 ry = decompressPoint(r, v); (uint r0, uint r1, uint r2) = assemblyShamir(eInvrInv, srInv, r, ry); uint[3] memory q = [r0, r1, r2]; return JtoA(q); } function assemblyShamir(uint256 u1, uint256 u2, uint256 qx, uint256 qy) internal pure returns(uint r0, uint r1, uint r2) { assembly{ let z0, z1 , z2 := ecAdd(48439561293906451759052585252797914202762949526041747995844080717082404635286,36134250956749795798585127919587881956611106672985015071877198253568414405109,1,qx,qy,1) let mask := exp(2,255) { let compare := or(u1, u2) for {} eq(and(compare, mask), 0) {} { mask := div(mask, 2) } } //Scope because we don't need compare long term switch iszero(eq(and(u1, mask), 0)) case 1 { switch iszero(eq(and(u2, mask), 0)) case 1 { r0 := z0 r1 := z1 r2 := z2 } default { r0 := 48439561293906451759052585252797914202762949526041747995844080717082404635286 r1 := 36134250956749795798585127919587881956611106672985015071877198253568414405109 r2 := 1 } } default { r0 := qx r1 := qy r2 := 1 } mask := div(mask, 2) for {} iszero(eq(mask, 0)) {mask := div(mask, 2)} { r0,r1,r2 := double(r0,r1,r2) switch iszero(eq(and(u1,mask), 0)) case 1 { switch iszero(eq(and(u2,mask), 0)) case 1 { r0, r1, r2 := ecAdd(z0,z1,z2,r0,r1,r2) } default { r0, r1, r2 := ecAdd(48439561293906451759052585252797914202762949526041747995844080717082404635286, 36134250956749795798585127919587881956611106672985015071877198253568414405109, 1, r0, r1, r2) } } default { if iszero(eq(and(u2, mask), 0)) { r0, r1, r2 := ecAdd(qx, qy, 1, r0, r1, r2) } } } function ecAdd(_p0, _p1, _p2, _q0, _q1, _q2) -> _r0, _r1, _r2 { let _u2 := 0 let _u1 := 0 { let _z2 := mulmod(_q2,_q2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) _u1 := mulmod(_p0, _z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let _s1 := mulmod(_p1, mulmod(_z2, _q2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) _z2 := mulmod(_p2, _p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) _u2 := mulmod(_q0, _z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let _s2 := mulmod(_q1, mulmod(_z2, _p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) switch eq(_u1, _u2) case 1 { if iszero(eq(_s1, _s2)) { //Return Point at infinity _r0 := 1 _r1 := 1 _r2 := 0 } if eq(_s1,_s2){ //returns the double point _r0,_r1,_r2 := double(_p0, _p1, _p2) } } default { _u2 := addmod(_u2, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, _u1), 115792089210356248762697446949407573530086143415290314195533631308867097853951) _z2 := mulmod(_u2, _u2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let _t2 := mulmod(_u1, _z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) _z2 := mulmod(_u2, _z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) _s2 := addmod(_s2, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951 , _s1) , 115792089210356248762697446949407573530086143415290314195533631308867097853951) // Uses s2, t2, z2 _r0 := addmod(addmod(mulmod(_s2, _s2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, _z2) , 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(2, _t2, 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) //Uses s2, t2, r0, s1 _r1 := addmod(mulmod(_s2, addmod(_t2, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, _r0), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(_s1, _z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) //Uses u2, p2, q2, /* r2 := mulmod(u2, mulmod(p2, q2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) */ } } //We have cleared the context block so cleared the stack and avoided the inaccessable stack error // assembly needs a command to delete local varibles so I can manualy clear the stack if iszero(eq(_u1, _u2)) { //If we don't check we will overwrite the other valid case _r2 := mulmod(_u2, mulmod(_p2, _q2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) } } function double(_p0, _p1, _p2) -> _r0, _r1, _r2 { if eq(_p1, 0) { _r0 := 0x1 _r1 := 0x1 _r2 := 0x0 } let _z2 := mulmod(_p2, _p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let _m := addmod(mulmod(115792089210356248762697446949407573530086143415290314195533631308867097853948, mulmod(_z2, _z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), mulmod(3, mulmod(_p0, _p0, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) let _y2 := mulmod(_p1, _p1, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let _s := mulmod(4, mulmod(_p0, _y2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) _r0 := addmod(mulmod(_m, _m, 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub( 115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(_s, 2, 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) _r2 := mulmod(2, mulmod(_p1, _p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) _r1 := addmod( mulmod(_m, addmod(_s, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, _r0), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(8,mulmod(_y2, _y2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) } } } function getSqrY(uint256 x) private pure returns(uint256) { //return y^2=x^3+Ax+B return addmod(mulmod(x, mulmod(x, x, P), P), addmod(mulmod(A, x, P), B, P), P); } //function checks if point (x, y) is on curve, x and y affine coordinate parameters function isPoint(uint256 x, uint256 y) public pure returns(bool) { //point fulfills y^2=x^3+Ax+B? return mulmod(y, y, P) == getSqrY(x); } function decompressPoint(uint256 x, uint8 yBit) private returns(uint256) { //return sqrt(x^3+Ax+B) uint256 absy = modexp(getSqrY(x), 1+(P-3)/4, P); return yBit == 0 ? absy : -absy; } function assemblyAdd(uint[3] memory _p, uint256[3] memory _q) private pure returns(uint256[3] memory r){ assembly{ let p_0 := mload(_p) let p_1 := mload(add(_p, 0x20)) let p_2 := mload(add(_p, 0x40)) let q_0 := mload(_q) let q_1 := mload(add(_q, 0x20)) let q_2 := mload(add(_q, 0x40)) ecAdd(p_0, p_1, p_2, q_0, q_1, q_2, r) function ecAdd(p0, p1, p2, q0, q1, q2, _r) { let z2 := mulmod(q2,q2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let u1 := mulmod(p0, z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let s1 := mulmod(p1, mulmod(z2, q2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) z2 := mulmod(p2, p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let u2 := mulmod(q0, z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let s2 := mulmod(q1, mulmod(z2, p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) if eq(u1, u2) { if iszero(eq(s1, s2)) { //Return Point at infinity mstore(_r, 0x1) mstore(add(_r,0x20), 0x1) mstore(add(_r,0x40), 0x0) } if eq(s1,s2){ {let x,y,z := double(p0, p1, p2)} } } u2 := addmod(u2, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, u1), 115792089210356248762697446949407573530086143415290314195533631308867097853951) z2 := mulmod(u2, u2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let t2 := mulmod(u1, z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) z2 := mulmod(u2, z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) s2 := addmod(s2, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951 ,s1) , 115792089210356248762697446949407573530086143415290314195533631308867097853951) let r0 := addmod(addmod(mulmod(s2, s2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, z2) , 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(2, t2, 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) mstore(_r, r0) mstore(add(_r,0x20), addmod(mulmod(s2, addmod(t2, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, r0), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(s1, z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951)) mstore(add(_r,0x40), mulmod(u2, mulmod(p2, q2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951)) } function double(p0, p1, p2) -> r0,r1,r2 { if eq(p1, 0) { r0 := 0x1 r1 := 0x1 r2 := 0x0 } let P := 115792089210356248762697446949407573530086143415290314195533631308867097853951 let A := 115792089210356248762697446949407573530086143415290314195533631308867097853948 let z2 := mulmod(p2, p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let m := addmod(mulmod(115792089210356248762697446949407573530086143415290314195533631308867097853948, mulmod(z2, z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), mulmod(3, mulmod(p0, p0, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) let y2 := mulmod(p1, p1, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let s := mulmod(4, mulmod(p0, y2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) r0 := addmod(mulmod(m,m, 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub( 115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(s, 2, 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) r2 := mulmod(2, mulmod(p1, p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) r1 := addmod( mulmod(m, addmod(s, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, r0), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(8,mulmod(y2, y2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) } } } function assemblyDouble(uint[3] memory _p) private pure returns(uint[3] memory _r) { assembly{ let p0 := mload(add(_p, 0x00)) let p1 := mload(add(_p, 0x20)) let p2 := mload(add(_p, 0x40)) if eq(p1, 0) { mstore(add(_r,0x00), 0x1) mstore(add(_r,0x20), 0x1) mstore(add(_r,0x40), 0x0) } let P := 115792089210356248762697446949407573530086143415290314195533631308867097853951 let A := 115792089210356248762697446949407573530086143415290314195533631308867097853948 let z2 := mulmod(p2, p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let m := addmod(mulmod(115792089210356248762697446949407573530086143415290314195533631308867097853948, mulmod(z2, z2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), mulmod(3, mulmod(p0, p0, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) let y2 := mulmod(p1, p1, 115792089210356248762697446949407573530086143415290314195533631308867097853951) let s := mulmod(4, mulmod(p0, y2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) let r0 := addmod(mulmod(m,m, 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub( 115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(s, 2, 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) let r2 := mulmod(2, mulmod(p1, p2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951) let r1 := addmod( mulmod(m, addmod(s, sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, r0), 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951), sub(115792089210356248762697446949407573530086143415290314195533631308867097853951, mulmod(8,mulmod(y2, y2, 115792089210356248762697446949407573530086143415290314195533631308867097853951), 115792089210356248762697446949407573530086143415290314195533631308867097853951)), 115792089210356248762697446949407573530086143415290314195533631308867097853951) //mstore(add(_p,0x20), r0) //mstore(add(_p,0x40), r1) //mstore(add(_p,0x60), r2) mstore(add(_r,0x00), r0) mstore(add(_r,0x20), r1) mstore(add(_r,0x40), r2) } } //jacobian to affine coordinates transformation function JtoA(uint256[3] memory p) private returns(uint256[2] memory Pnew) { uint zInv = invmod(p[2], P); uint zInv2 = mulmod(zInv, zInv, P); Pnew[0] = mulmod(p[0], zInv2, P); Pnew[1] = mulmod(p[1], mulmod(zInv, zInv2, P), P); } //computing inverse by using fermat's theorem function invmod(uint256 _a, uint _p) internal returns(uint256 invA) { invA = modexp(_a, _p - 2, _p); } //@ Dev - The orginal code which was assemblifed /* //We lay out memory starting at zero 32 bytes public key X 32 bytes public function calcPointShamir(uint256 u1, uint256 u2, uint256 qx, uint256 qy) private pure returns(uint[3] memory R) { uint256[3] memory G = [GX, GY, 1]; uint256[3] memory Q = [qx, qy, 1]; uint256[3] memory Z = assemblyAdd(Q, G); uint256 mask = 2**255; // Skip leading zero bits uint256 or = u1 | u2; while (or & mask == 0) { mask = mask / 2; } // Initialize output if (u1 & mask != 0) { if (u2 & mask != 0) { R = Z; } else { R = G; } } else { R = Q; } while (true) { mask = mask / 2; if (mask == 0) { break; } R = ecdouble(R); if (u1 & mask != 0) { if (u2 & mask != 0) { R = ecadd(Z, R); } else { R = ecadd(G, R); } } else { if (u2 & mask != 0) { R = ecadd(Q, R); } } } } // point addition for elliptic curve in jacobian coordinates // formula from https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates function ecadd(uint256[3] memory _p, uint256[3] memory _q) private pure returns(uint256[3] memory R) { // if (_q[0] == 0 && _q[1] == 0 && _q[2] == 0) { // return _p; // } uint256 z2 = mulmod(_q[2], _q[2], P); uint256 u1 = mulmod(_p[0], z2, P); uint256 s1 = mulmod(_p[1], mulmod(z2, _q[2], P), P); z2 = mulmod(_p[2], _p[2], P); uint256 u2 = mulmod(_q[0], z2, P); uint256 s2 = mulmod(_q[1], mulmod(z2, _p[2], P), P); if (u1 == u2) { if (s1 != s2) { //return point at infinity return [uint256(1), 1, 0]; } else { return ecdouble(_p); } } u2 = addmod(u2, P - u1, P); z2 = mulmod(u2, u2, P); uint256 t2 = mulmod(u1, z2, P); z2 = mulmod(u2, z2, P); s2 = addmod(s2, P - s1, P); R[0] = addmod(addmod(mulmod(s2, s2, P), P - z2, P), P - mulmod(2, t2, P), P); R[1] = addmod(mulmod(s2, addmod(t2, P - R[0], P), P), P - mulmod(s1, z2, P), P); R[2] = mulmod(u2, mulmod(_p[2], _q[2], P), P); } //point doubling for elliptic curve in jacobian coordinates //formula from https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates function ecdouble(uint256[3] memory _p) private pure returns(uint256[3] memory R) { if (_p[1] == 0) { //return point at infinity return [uint256(1), 1, 0]; } uint256 z2 = mulmod(_p[2], _p[2], P); uint256 m = addmod(mulmod(A, mulmod(z2, z2, P), P), mulmod(3, mulmod(_p[0], _p[0], P), P), P); uint256 y2 = mulmod(_p[1], _p[1], P); uint256 s = mulmod(4, mulmod(_p[0], y2, P), P); R[0] = addmod(mulmod(m, m, P), P - mulmod(s, 2, P), P); R[2] = mulmod(2, mulmod(_p[1], _p[2], P), P); // consider R might alias _p R[1] = addmod(mulmod(m, addmod(s, P - R[0], P), P), P - mulmod(8, mulmod(y2, y2, P), P), P); }*/ }
point addition for elliptic curve in jacobian coordinates formula from https:en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates if (_q[0] == 0 && _q[1] == 0 && _q[2] == 0) { return _p; }
function ecadd(uint256[3] memory _p, uint256[3] memory _q) private pure returns(uint256[3] memory R) { uint256 z2 = mulmod(_q[2], _q[2], P); uint256 u1 = mulmod(_p[0], z2, P); uint256 s1 = mulmod(_p[1], mulmod(z2, _q[2], P), P); z2 = mulmod(_p[2], _p[2], P); uint256 u2 = mulmod(_q[0], z2, P); uint256 s2 = mulmod(_q[1], mulmod(z2, _p[2], P), P); if (u1 == u2) { if (s1 != s2) { return [uint256(1), 1, 0]; } else { return ecdouble(_p); } } u2 = addmod(u2, P - u1, P); z2 = mulmod(u2, u2, P); uint256 t2 = mulmod(u1, z2, P); z2 = mulmod(u2, z2, P); s2 = addmod(s2, P - s1, P); R[0] = addmod(addmod(mulmod(s2, s2, P), P - z2, P), P - mulmod(2, t2, P), P); R[1] = addmod(mulmod(s2, addmod(t2, P - R[0], P), P), P - mulmod(s1, z2, P), P); R[2] = mulmod(u2, mulmod(_p[2], _q[2], P), P); if (u1 == u2) { if (s1 != s2) { return [uint256(1), 1, 0]; } else { return ecdouble(_p); } } u2 = addmod(u2, P - u1, P); z2 = mulmod(u2, u2, P); uint256 t2 = mulmod(u1, z2, P); z2 = mulmod(u2, z2, P); s2 = addmod(s2, P - s1, P); R[0] = addmod(addmod(mulmod(s2, s2, P), P - z2, P), P - mulmod(2, t2, P), P); R[1] = addmod(mulmod(s2, addmod(t2, P - R[0], P), P), P - mulmod(s1, z2, P), P); R[2] = mulmod(u2, mulmod(_p[2], _q[2], P), P); if (u1 == u2) { if (s1 != s2) { return [uint256(1), 1, 0]; } else { return ecdouble(_p); } } u2 = addmod(u2, P - u1, P); z2 = mulmod(u2, u2, P); uint256 t2 = mulmod(u1, z2, P); z2 = mulmod(u2, z2, P); s2 = addmod(s2, P - s1, P); R[0] = addmod(addmod(mulmod(s2, s2, P), P - z2, P), P - mulmod(2, t2, P), P); R[1] = addmod(mulmod(s2, addmod(t2, P - R[0], P), P), P - mulmod(s1, z2, P), P); R[2] = mulmod(u2, mulmod(_p[2], _q[2], P), P); }
13,113,487
./full_match/421611/0xA58a23d4846617807e43420d21EA0127d9d9Fa0e/sources/contracts-link/test/TestPaymasterConfigurableMisbehavior.sol
leaving withdrawal public and unprotected
function withdrawAllBalance() public returns (uint256) { require(address(relayHub) != address(0), "relay hub address not set"); uint256 balance = relayHub.balanceOf(address(this)); relayHub.withdraw(balance, payable(address(this))); return balance; } IPaymaster.GasAndDataLimits private limits = super.getGasAndDataLimits();
13,220,861
import "Rounder.sol"; contract Rebalancer is Rounder { uint constant cheapRebGas = 6969; uint constant rebGas = 13830; //automated rebalance function function rebalance(address _sendRemainderTo) external { //need at least 1 eth to ensure balance is properly rounded //need to specify a remainder address if(msg.value < 1 ether || _sendRemainderTo == 0) throw; //calculates amount the contract needs to send back to sender for a rounded balance uint amtToSendForRounding = calcAmtToSend(rebGas); if(! msg.sender.send(amtToSendForRounding)) throw; //send whatever remains to specified remainder address if(! _sendRemainderTo.send(msg.value - amtToSendForRounding)) throw; } //'safer' variant of the automated rebalance function //ensures the set remainder account has a balance before sending //should help avoid mistyping addresses function saferRebalance(address _sendRemainderTo) external { //same initial checks + ensure the remainder balance isnt empty if(msg.value < 1 ether || _sendRemainderTo == 0 || _sendRemainderTo.balance == 0) throw; uint amtToSendForRounding = calcAmtToSend(rebGas); if(! msg.sender.send(amtToSendForRounding)) throw; if(! _sendRemainderTo.send(msg.value - amtToSendForRounding)) throw; } //constant function for users that would just like to send directly from their address to another //returns the wei amount that needs to be sent to round down the balance function returnManualRebalance(address _acctToRound, uint _gasPrice) public constant returns (uint) { return calcExactRebalance(_acctToRound.balance - (21000 * _gasPrice)); } //Intra-contract helper functions //function for calculating amount that needs to be sent for rounding function calcAmtToSend(uint _futureGas) private constant returns (uint) { uint figureDiff = findFigures(msg.sender.balance) - 18; uint roundedUpBalance = uintCeil(msg.sender.balance, figureDiff); return roundedUpBalance - msg.sender.balance - (msg.gas * tx.gasprice) + (_futureGas * tx.gasprice); } function calcExactRebalance(uint _bal) private constant returns (uint) { uint figureDiff = findFigures(_bal) - 18; return (_bal - uintFloor(_bal, figureDiff)); } }
'safer' variant of the automated rebalance functionensures the set remainder account has a balance before sendingshould help avoid mistyping addressessame initial checks + ensure the remainder balance isnt empty
function saferRebalance(address _sendRemainderTo) external { if(msg.value < 1 ether || _sendRemainderTo == 0 || _sendRemainderTo.balance == 0) throw; uint amtToSendForRounding = calcAmtToSend(rebGas); if(! msg.sender.send(amtToSendForRounding)) throw; if(! _sendRemainderTo.send(msg.value - amtToSendForRounding)) throw; }
956,874
// File: contracts/TrueReward/utilities/FractionalExponents.sol pragma solidity ^0.5.13; contract FractionalExponents { uint256 private constant one336 = 1; //inject NONSTANDARD NAMING uint32 private constant max_weight381 = 1000000; //inject NONSTANDARD NAMING uint8 private constant min_precision573 = 32; //inject NONSTANDARD NAMING uint8 private constant max_precision428 = 127; //inject NONSTANDARD NAMING uint256 private constant fixed_1483 = 0x080000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 private constant fixed_2341 = 0x100000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 private constant max_num179 = 0x200000000000000000000000000000000; //inject NONSTANDARD NAMING uint256 private constant ln2_numerator275 = 0x3f80fe03f80fe03f80fe03f80fe03f8; //inject NONSTANDARD NAMING uint256 private constant ln2_denominator179 = 0x5b9de1d10bf4103d647b0955897ba80; //inject NONSTANDARD NAMING uint256 private constant opt_log_max_val934 = 0x15bf0a8b1457695355fb8ac404e7a79e3; //inject NONSTANDARD NAMING uint256 private constant opt_exp_max_val839 = 0x800000000000000000000000000000000; //inject NONSTANDARD NAMING uint256[128] private maxExpArray; function BANCORFORMULA872() public { //inject NONSTANDARD NAMING maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } function POWER707(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) public view returns (uint256, uint8) { //inject NONSTANDARD NAMING assert(_baseN < max_num179); uint256 baseLog; uint256 base = _baseN * fixed_1483 / _baseD; if (base < opt_log_max_val934) { baseLog = OPTIMALLOG175(base); } else { baseLog = GENERALLOG620(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < opt_exp_max_val839) { return (OPTIMALEXP683(baseLogTimesExp), max_precision428); } else { uint8 precision = FINDPOSITIONINMAXEXPARRAY394(baseLogTimesExp); return (GENERALEXP531(baseLogTimesExp >> (max_precision428 - precision), precision), precision); } } function GENERALLOG620(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= fixed_2341) { uint8 count = FLOORLOG2195(x / fixed_1483); x >>= count; // now x < 2 res = count * fixed_1483; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > fixed_1483) { for (uint8 i = max_precision428; i > 0; --i) { x = (x * x) / fixed_1483; // now 1 < x < 4 if (x >= fixed_2341) { x >>= 1; // now 1 < x < 2 res += one336 << (i - 1); } } } return res * ln2_numerator275 / ln2_denominator179; } function FLOORLOG2195(uint256 _n) internal pure returns (uint8) { //inject NONSTANDARD NAMING uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (one336 << s)) { _n >>= s; res |= s; } } } return res; } function FINDPOSITIONINMAXEXPARRAY394(uint256 _x) internal view returns (uint8) { //inject NONSTANDARD NAMING uint8 lo = min_precision573; uint8 hi = max_precision428; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; assert(false); return 0; } function GENERALEXP531(uint256 _x, uint8 _precision) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (one336 << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } function OPTIMALLOG175(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) { res += 0x40000000000000000000000000000000; x = x * fixed_1483 / 0xd3094c70f034de4b96ff7d5b6f99fcd8; } if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) { res += 0x20000000000000000000000000000000; x = x * fixed_1483 / 0xa45af1e1f40c333b3de1db4dd55f29a7; } if (x >= 0x910b022db7ae67ce76b441c27035c6a1) { res += 0x10000000000000000000000000000000; x = x * fixed_1483 / 0x910b022db7ae67ce76b441c27035c6a1; } if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) { res += 0x08000000000000000000000000000000; x = x * fixed_1483 / 0x88415abbe9a76bead8d00cf112e4d4a8; } if (x >= 0x84102b00893f64c705e841d5d4064bd3) { res += 0x04000000000000000000000000000000; x = x * fixed_1483 / 0x84102b00893f64c705e841d5d4064bd3; } if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) { res += 0x02000000000000000000000000000000; x = x * fixed_1483 / 0x8204055aaef1c8bd5c3259f4822735a2; } if (x >= 0x810100ab00222d861931c15e39b44e99) { res += 0x01000000000000000000000000000000; x = x * fixed_1483 / 0x810100ab00222d861931c15e39b44e99; } if (x >= 0x808040155aabbbe9451521693554f733) { res += 0x00800000000000000000000000000000; x = x * fixed_1483 / 0x808040155aabbbe9451521693554f733; } z = y = x - fixed_1483; w = y * y / fixed_1483; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / fixed_1483; res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / fixed_1483; res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / fixed_1483; res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / fixed_1483; res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / fixed_1483; res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / fixed_1483; res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / fixed_1483; res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; return res; } function OPTIMALEXP683(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; z = z * y / fixed_1483; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / fixed_1483; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / fixed_1483; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / fixed_1483; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / fixed_1483; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / fixed_1483; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / fixed_1483; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / fixed_1483; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / fixed_1483; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / fixed_1483; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / fixed_1483; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / fixed_1483; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / fixed_1483; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / fixed_1483; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / fixed_1483; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / fixed_1483; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / fixed_1483; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / fixed_1483; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / fixed_1483; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + fixed_1483; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) { res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; } if ((x & 0x020000000000000000000000000000000) != 0) { res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; } if ((x & 0x040000000000000000000000000000000) != 0) { res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; } if ((x & 0x080000000000000000000000000000000) != 0) { res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; } if ((x & 0x100000000000000000000000000000000) != 0) { res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; } if ((x & 0x200000000000000000000000000000000) != 0) { res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; } if ((x & 0x400000000000000000000000000000000) != 0) { res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; } return res; } }
inject NONSTANDARD NAMING
function GENERALEXP531(uint256 _x, uint8 _precision) internal pure returns (uint256) {
5,410,459
/** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.10; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol"; import "./compound/ICErc20.sol"; import "./DrawManager.sol"; import "fixidity/contracts/FixidityLib.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract Pool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; uint256 private constant ETHER_IN_WEI = 1000000000000000000; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event Paused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event Unpaused(address indexed sender); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State drawState; /** * A structure containing the administrators */ Roles.Role admins; /** * Whether the contract is paused */ bool public paused; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary ) public initializer { require(_owner != address(0), "owner cannot be the null address"); require(_cToken != address(0), "money market address is zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw(nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Commits the current draw. */ function commit() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin unlessPaused { require(currentCommittedDrawId() == 0, "there is a committed draw"); if (currentOpenDrawId() != 0) { commit(); } open(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin unlessPaused { require(currentCommittedDrawId() != 0, "a draw has not been committed"); reward(lastSecret, _salt); commit(); open(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret and a hash of the Draw's opened block and the gross winnings. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw */ function reward(bytes32 _secret, bytes32 _salt) internal { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "secret does not match"); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings = underlyingBalance.sub(accountedBalance); // derive entropy from the revealed secret and the hash of the openedBlock and gross winnings bytes32 entropy = _secret ^ keccak256(abi.encodePacked(draw.openedBlock, grossWinnings)); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Update balance of the winner balances[winningAddress] = balances[winningAddress].add(netWinnings); // Enter their winnings into the next draw drawState.deposit(winningAddress, netWinnings); // Updated the accounted total accountedBalance = underlyingBalance; } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } // Destroy the draw now that it's complete delete draws[drawId]; emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public nonReentrant unlessPaused { // Deposit the funds _deposit(_amount); emit SponsorshipDeposited(msg.sender, _amount); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw nonReentrant unlessPaused { // Update the user's eligibility drawState.deposit(msg.sender, _amount); // Deposit the funds _deposit(_amount); emit Deposited(msg.sender, _amount); } /** * @notice Transfers tokens from the sender into the Compound cToken contract and updates the accountedBalance. * @param _amount The amount of the token underlying the cToken to deposit. */ function _deposit(uint256 _amount) internal { require(_amount > 0, "deposit is not greater than zero"); // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "token transfer failed"); // Update the user's balance balances[msg.sender] = balances[msg.sender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "could not approve money market spend"); require(cToken.mint(_amount) == 0, "could not supply money market"); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant { uint balance = balances[msg.sender]; require(balance > 0, "balance has already been withdrawn"); // Update the user's balance balances[msg.sender] = 0; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(balance); } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(uint256 _amount) internal { require(_amount > 0, "withdrawal is not greater than zero"); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "could not redeem from compound"); require(token().transfer(msg.sender, _amount), "could not transfer winnings"); emit Withdrawn(msg.sender, _amount); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) public view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) public view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance, including both committed Draw balance and open Draw balance. * @param _addr The address of the user to check. * @return The users's current balance. */ function balanceOf(address _addr) public view returns (uint256) { return balances[_addr]; } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply; } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction >= 0, "fee must be zero or greater"); require(_feeFraction <= ETHER_IN_WEI, "fee fraction must be 1 or less"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "beneficiary should not be 0x0"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "admin does not exist"); admins.remove(_admin); emit AdminRemoved(_admin); } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() internal view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } function pause() public unlessPaused onlyAdmin { paused = true; emit Paused(msg.sender); } function unpause() public whenPaused onlyAdmin { paused = false; emit Unpaused(msg.sender); } modifier onlyAdmin() { require(admins.has(msg.sender), "must be an admin"); _; } modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "there is no open draw"); _; } modifier whenPaused() { require(paused, "contract is not paused"); _; } modifier unlessPaused() { require(!paused, "contract is paused"); _; } }
Sets the fee beneficiary for subsequent Draws. Can only be called by admins. _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address./
function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); }
930,211
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract Kyc { address public admin; struct Customer { address custAddress; string jsonHash; string photoHash; string citizenship_front_hash; string citizenship_back_hash; uint d; uint n; address[] organization; bool kycStatus; } struct Organization { string name; address ethAddress; } struct kycRequest{ address ethAddress; uint req_count; kycRequestList[] kycrequestlist; } struct kycRequestList{ uint req_count; address Address; } struct kycRequestCust{ kycRequestList[] kycrequestlist; address custAddress; } constructor() { admin = msg.sender; } mapping(address => Customer) customers; mapping(address => Organization) organizations; mapping(address => kycRequest) kycrequestsbyorg; mapping(address => kycRequestCust) kycrequestsbycust; event orgAdded(string name,address ethAddress); event orgRemoved(address ethAddress); event customerAdded(address custAddress,bool kycStatus); event customerUpdated(address custAddress,bool kycStatus); event requestAdded(uint reqid,address ethAddress, address custAddress,bool isAllowed); event requestRemoved(uint reqid,address ethAddress); event accessGiven(uint reqid,address custAddress,address ethAddress,bool isAllowed); event accessRevoked(address custAddress,address ethAddress); event kycRemoved(address custAddress,address ethAddress); // Checks whether the requestor is admin modifier isAdmin { require( admin == msg.sender, "Admin only" ); _; } // Checks wheter the org exists or not modifier isOrgValid { require( organizations[msg.sender].ethAddress == msg.sender, "Org not exist" ); _; } //Check if Org has access to the user KYC function findOrg(address _custaddress,address ethAddress) internal view returns(bool){ uint i = 0; for(i;i<customers[_custaddress].organization.length;i++){ if(customers[_custaddress].organization[i]==ethAddress){ return true; } } return false; } //Find the index of Org in KYC.organization array function findOrgIndex(address _custaddress,address ethAddress) internal view returns(uint){ uint i = 0; for(i;i<customers[_custaddress].organization.length;i++){ if(customers[_custaddress].organization[i]==ethAddress){ return i; } } } function findRequestIndex(address _custaddress,address _ethAddress) internal view returns(uint){ uint i = 0; for(i;i<kycrequestsbycust[_custaddress].kycrequestlist.length;i++){ if(kycrequestsbycust[_custaddress].kycrequestlist[i].Address==_ethAddress){ return i; } } } //Check if request exist function findRequest(address _custaddress) internal view returns(bool){ uint i=0; for(i;i<kycrequestsbyorg[msg.sender].req_count;i++){ if(kycrequestsbyorg[msg.sender].kycrequestlist[i].Address==_custaddress){ return true; } } return false; } //Add organization ONLY BY ADMIN function addOrg(string memory _name,address _ethAddress) public isAdmin returns(bool) { require(organizations[_ethAddress].ethAddress!=_ethAddress,"Org already added"); organizations[_ethAddress]=Organization(_name,_ethAddress); kycrequestsbyorg[_ethAddress].ethAddress=_ethAddress; kycrequestsbyorg[_ethAddress].req_count=0; emit orgAdded(_name,_ethAddress); return true; } //Remove Organization ONLY BY ADMIN function removeOrg(address _ethAddress) public isAdmin returns(bool) { require(organizations[_ethAddress].ethAddress==_ethAddress,"Org doesnt exist"); delete organizations[_ethAddress]; emit orgRemoved(_ethAddress); return true; } //Return Organization Info if it exists function viewOrg(address _ethAddress)public isAdmin view returns(Organization memory){ require(organizations[_ethAddress].ethAddress==_ethAddress,"Org doesnt exist"); return organizations[_ethAddress]; } function getYourOrgDetail() public isOrgValid view returns(Organization memory){ return organizations[msg.sender]; } function validOrg() public view returns(bool){ if(organizations[msg.sender].ethAddress==msg.sender){ return true; } else{ return false; } } function validAdmin() public view returns(bool){ if(admin==msg.sender){ return true; } else{ return false; } } function validCust() public view returns(bool){ if(customers[msg.sender].custAddress==msg.sender){ return true; } else{ return false; } } function writeKYC( address _custaddress, string memory _jsonHash, string memory _photohash, string memory _citizenship_front_hash, string memory _citizenship_back_hash, bool _kycStatus, uint _d, uint _n) internal { require(bytes(_jsonHash).length > 0); require(bytes(_photohash).length > 0); require(bytes(_citizenship_back_hash).length > 0); require(bytes(_citizenship_front_hash).length > 0); customers[_custaddress].custAddress=_custaddress; customers[_custaddress].jsonHash=_jsonHash; customers[_custaddress].photoHash=_photohash; customers[_custaddress].citizenship_front_hash=_citizenship_front_hash; customers[_custaddress].citizenship_back_hash=_citizenship_back_hash; customers[_custaddress].kycStatus=_kycStatus; customers[_custaddress].d=_d; customers[_custaddress].n=_n; kycrequestsbycust[_custaddress].custAddress=_custaddress; } //Register User KYC by registered Orgs function registerKYC( address _custaddress, string memory _jsonHash, string memory _photohash, string memory _citizenship_front_hash, string memory _citizenship_back_hash, bool _kycStatus, uint _d, uint _n) public isOrgValid returns(bool){ require(customers[_custaddress].custAddress!=_custaddress,"User already exists"); writeKYC(_custaddress,_jsonHash,_photohash,_citizenship_front_hash,_citizenship_back_hash,_kycStatus,_d,_n); requestKYC(_custaddress); emit customerAdded(_custaddress,_kycStatus); return true; } //View User KYC by Authorized Orgs function viewKYC(address _custaddress) public view returns( bool, string memory, string memory, string memory, string memory, uint, uint) { require(findOrg(_custaddress,msg.sender),"User hasnt given their consent"); return(customers[_custaddress].kycStatus,customers[_custaddress].jsonHash,customers[_custaddress].photoHash,customers[_custaddress].citizenship_front_hash,customers[_custaddress].citizenship_back_hash,customers[_custaddress].d,customers[_custaddress].n); } function viewYourKYC() public view returns(Customer memory){ require(validCust(),'Customer not valid'); return customers[msg.sender]; } function viewOrgWithAccess() public view returns(address[] memory){ require(customers[msg.sender].custAddress==msg.sender,"You dont have authority"); return customers[msg.sender].organization; } function viewRequestCust() public view returns(kycRequestList[] memory){ require(validCust(),'Customer not valid'); kycRequestList[] memory ret = new kycRequestList[](kycrequestsbycust[msg.sender].kycrequestlist.length); uint j = 0; for (uint i = 0; i < kycrequestsbycust[msg.sender].kycrequestlist.length; i++) { ret[j] = kycrequestsbycust[msg.sender].kycrequestlist[i]; j++; } return (ret); } //Update User KYC by registered and authorized orgs function updateKYC( address _custaddress, string memory _jsonHash, string memory _photohash, string memory _citizenship_front_hash, string memory _citizenship_back_hash, bool _kycStatus, uint _d, uint _n) public isOrgValid returns(bool){ require(customers[_custaddress].custAddress==_custaddress,"User doesn't exist"); require(findOrg(_custaddress,msg.sender),"You dont have access to this user"); writeKYC(_custaddress,_jsonHash,_photohash,_citizenship_front_hash,_citizenship_back_hash,_kycStatus,_d,_n); emit customerUpdated(_custaddress,_kycStatus); return true; } //Request User KYC by Orgs function requestKYC(address _custaddress) public isOrgValid returns(bool){ require(customers[_custaddress].custAddress==_custaddress,"Customer doesnt exists"); require(findOrg(_custaddress,msg.sender)==false,"Already have access"); require(findRequest(_custaddress)==false,"Request Already Exists"); kycrequestsbyorg[msg.sender].kycrequestlist.push(kycRequestList(kycrequestsbyorg[msg.sender].req_count,_custaddress)); kycrequestsbycust[_custaddress].kycrequestlist.push(kycRequestList(kycrequestsbyorg[msg.sender].req_count,msg.sender)); kycrequestsbyorg[msg.sender].req_count++; emit requestAdded(kycrequestsbyorg[msg.sender].req_count-1,msg.sender,_custaddress,false); return true; } function deleteRequest(uint _reqcount,address _custaddress,address _ethAddress) internal{ uint index = findRequestIndex(_custaddress,_ethAddress); kycrequestsbyorg[_ethAddress].kycrequestlist[_reqcount]=kycrequestsbyorg[_ethAddress].kycrequestlist[kycrequestsbyorg[_ethAddress].kycrequestlist.length-1]; kycrequestsbyorg[_ethAddress].kycrequestlist.pop(); kycrequestsbycust[_custaddress].kycrequestlist[index]=kycrequestsbycust[_custaddress].kycrequestlist[kycrequestsbycust[_custaddress].kycrequestlist.length-1]; kycrequestsbycust[_custaddress].kycrequestlist.pop(); if(kycrequestsbyorg[msg.sender].kycrequestlist.length!=_reqcount && kycrequestsbyorg[_ethAddress].req_count>1){ kycrequestsbyorg[_ethAddress].kycrequestlist[_reqcount].req_count=_reqcount; address add = kycrequestsbyorg[_ethAddress].kycrequestlist[_reqcount].Address; if(kycrequestsbycust[add].kycrequestlist.length>0){ index = findRequestIndex(add, _ethAddress); kycrequestsbycust[add].kycrequestlist[index].req_count=_reqcount; } } kycrequestsbyorg[_ethAddress].req_count--; emit requestRemoved(_reqcount,_ethAddress); } //Delete User KYC request by organization function deleteRequestOrg(uint _reqcount) public isOrgValid returns(bool){ require(kycrequestsbyorg[msg.sender].ethAddress==msg.sender,"You dont have authority to delete"); require(kycrequestsbyorg[msg.sender].kycrequestlist[_reqcount].req_count==_reqcount,"Request doesnt exist"); address _custaddress = kycrequestsbyorg[msg.sender].kycrequestlist[_reqcount].Address; deleteRequest(_reqcount,_custaddress,msg.sender); return true; } //Delete User KYC Request after user provides access function deleteRequestCust(uint _reqcount,address _ethAddress) public{ require(organizations[_ethAddress].ethAddress==_ethAddress,"This particular organizations doesnt exist"); require(kycrequestsbyorg[_ethAddress].kycrequestlist[_reqcount].Address==msg.sender,"User not valid"); require(kycrequestsbyorg[_ethAddress].kycrequestlist[_reqcount].req_count==_reqcount,"Request doesnt exist"); deleteRequest(_reqcount,msg.sender,_ethAddress); } //Return Array of all pending request of the orgs function listRequest() public isOrgValid view returns(kycRequestList[] memory){ kycRequestList[] memory ret = new kycRequestList[](kycrequestsbyorg[msg.sender].req_count); uint j = 0; for (uint i = 0; i < kycrequestsbyorg[msg.sender].req_count; i++) { ret[j] = kycrequestsbyorg[msg.sender].kycrequestlist[i]; j++; } return (ret); } //Give User KYC access to Org function giveAccessKYC(uint _reqcount,address _ethAddress,bool _isAllowed) public returns(bool){ require(customers[msg.sender].custAddress==msg.sender,"You dont have authority to give access"); require(kycrequestsbyorg[_ethAddress].kycrequestlist[_reqcount].Address==msg.sender,"User not valid"); require(kycrequestsbyorg[_ethAddress].kycrequestlist[_reqcount].req_count==_reqcount,"Requests not found"); if(_isAllowed == true){ if(findOrg(msg.sender,_ethAddress) == false){ customers[msg.sender].organization.push(_ethAddress); } deleteRequestCust(_reqcount,_ethAddress); emit accessGiven(_reqcount,msg.sender,_ethAddress,_isAllowed); } else{ deleteRequestCust(_reqcount,_ethAddress); } return true; } function remove(address _custaddress,address _ethAddress) internal { uint i=findOrgIndex(_custaddress,_ethAddress); customers[_custaddress].organization[i]=customers[_custaddress].organization[customers[_custaddress].organization.length-1]; customers[_custaddress].organization.pop(); } //Revoke User KYC access of Orgs function revokeAccessKYC(address _ethAddress) public returns(bool){ require(customers[msg.sender].custAddress==msg.sender,"You dont have authority to revoke access"); require(findOrg(msg.sender,_ethAddress),"You dont have access to this user"); remove(msg.sender,_ethAddress); emit accessRevoked(msg.sender,_ethAddress); return true; } //Remove User KYC by Orgs function removeKYC(address _custaddress) public isOrgValid returns (bool){ require(customers[_custaddress].custAddress==_custaddress,"User doesn't exist"); require(findOrg(_custaddress,msg.sender),"You dont have access to this user"); remove(_custaddress,msg.sender); emit kycRemoved(_custaddress,msg.sender); return true; } }
Return Array of all pending request of the orgs
function listRequest() public isOrgValid view returns(kycRequestList[] memory){ kycRequestList[] memory ret = new kycRequestList[](kycrequestsbyorg[msg.sender].req_count); uint j = 0; for (uint i = 0; i < kycrequestsbyorg[msg.sender].req_count; i++) { ret[j] = kycrequestsbyorg[msg.sender].kycrequestlist[i]; j++; } return (ret); }
13,026,463
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./utils/GovernanceControl.sol"; /** * @title Rewards contact. * * @dev Rewards contract allows to make and allocate rewards programs for voters. */ contract Rewards is Initializable, GovernanceControl { using SafeERC20Upgradeable for IERC20Upgradeable; /// Reward token, in which rewards are given. IERC20Upgradeable private _rewardToken; /// Reward per vote made during successful governance proposal. uint256 private _rewardPerVote; /// Block number of voting start for proposals, which qualify for the rewards program. uint256 private _rewardsStart; /// Total rewards allocated for stimulating voting. uint256 private _allocated; /// Treasury contract. address private _treasury; /// Returns true if claimed reward for an account by voting for a particular successful proposal. mapping(address => mapping(uint256 => bool)) private _claimed; event Deposited(address depositor, uint256 amount); event Withdrawn(address withdrawer, uint256 amount); event Claim(address claimer, uint256 proposalId, uint256 reward); event Allocated(uint256 rewards); /** * @dev Only treausry modifier. * * Requirements: * - caller must be the treasury. */ modifier onlyTreasury() { require(_msgSender() == _treasury, "Rewards: only treasury"); _; } function initialize( address governance_, address executor_, address treasury_, IERC20Upgradeable rewardToken_, uint256 rewardPerVote_ ) external initializer { __GovernanceControl_init(governance_, executor_); _treasury = treasury_; _rewardToken = rewardToken_; _rewardPerVote = rewardPerVote_; } function setRewardPerVote(uint256 rewardPerVote_) external virtual onlyGovernance { _rewardPerVote = rewardPerVote_; } function setRewardToken(IERC20Upgradeable rewardToken_) external virtual onlyGovernance { _rewardToken = rewardToken_; } function setTreasury(address treasury_) external virtual onlyGovernance { require( _treasury != address(0) && _treasury != treasury_, "Rewards: invalid treasury" ); _treasury = treasury_; } /** * @dev Allocate `rewards` with `rewardsStart_` for rewards program * * Requirements: * - can only be called from the treasury. */ function allocate(uint256 rewards, uint256 rewardsStart_) external virtual onlyTreasury { require( rewards > 0 && rewardsStart_ > _rewardsStart, "Rewards: params are invalid" ); _allocated += rewards; _rewardsStart = rewardsStart_; _rewardToken.safeTransferFrom(_msgSender(), address(this), rewards); emit Allocated(rewards); } /** * @dev Claim voting reward for `proposalId`. */ function claimVotingReward(uint256 proposalId) external virtual { require( !_claimed[_msgSender()][proposalId], "Rewards: already claimed" ); require( _rewardsStart <= _governance.proposalSnapshot(proposalId), "Rewards: not qualified" ); (uint256 votes, uint8 support) = _governance.getReceipt( proposalId, _msgSender() ); if (support == 1 && _governance.isProposalSuccessful(proposalId)) { require( _allocated >= votes * _rewardPerVote, "Rewards: not enough allocation" ); _claimed[_msgSender()][proposalId] = true; _allocated -= votes * _rewardPerVote; _rewardToken.safeTransfer(_msgSender(), votes * _rewardPerVote); } emit Claim(_msgSender(), proposalId, votes * _rewardPerVote); } function rewardPetVote() external view virtual returns (uint256) { return _rewardPerVote; } function rewardToken() external view virtual returns (address) { return address(_rewardToken); } function treasury() external view virtual returns (address) { return _treasury; } function allocated() external view virtual returns (uint256) { return _allocated; } function rewardsStart() external view virtual returns (uint256) { return _rewardsStart; } function claimed(address account, uint256 proposalId) external view virtual returns (bool) { return _claimed[account][proposalId]; } }
Claim voting reward for `proposalId`./
function claimVotingReward(uint256 proposalId) external virtual { require( !_claimed[_msgSender()][proposalId], "Rewards: already claimed" ); require( _rewardsStart <= _governance.proposalSnapshot(proposalId), "Rewards: not qualified" ); (uint256 votes, uint8 support) = _governance.getReceipt( proposalId, _msgSender() ); if (support == 1 && _governance.isProposalSuccessful(proposalId)) { require( _allocated >= votes * _rewardPerVote, "Rewards: not enough allocation" ); _claimed[_msgSender()][proposalId] = true; _allocated -= votes * _rewardPerVote; _rewardToken.safeTransfer(_msgSender(), votes * _rewardPerVote); } emit Claim(_msgSender(), proposalId, votes * _rewardPerVote); }
12,957,515
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../utilities/Initializable.sol"; import "../utilities/Context.sol"; import "../access/Ownable.sol"; import "../security/Pausable.sol"; import "../interfaces/IBEP20.sol"; import "../libraries/Address.sol"; // Implementation of the IBEP20 Interface, using Context, Pausable, Ownable, and Snapshot Extenstions. contract BEP20 is Initializable, Context, IBEP20, Pausable, Ownable { // Dev-Note: Solidity 0.8.0 added built-in support for checked math, therefore the "SafeMath" library is no longer needed. using Address for address; // Creates mapping for the collections of balances and allowances. mapping(address => uint256) public _balances; mapping(address => mapping(address => uint256)) private _allowances; // Initializes variables for the name, symbol, decimals, and the total Supply of the BEP20 token. string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; // Sets the values for {name}, {symbol}, {decimals}, and {totalSupply}. function __BEP20_init(string memory name_, string memory symbol_, uint8 decimals_, uint256 totalSupply_) internal initializer { __Context_init_unchained(); __Ownable_init(); __Pausable_init(); __BEP20_init_unchained(name_, symbol_, decimals_, totalSupply_); } // Internal function to set the values for {name}, {symbol}, {decimals}, and {totalSupply}. function __BEP20_init_unchained(string memory name_, string memory symbol_, uint8 decimals_, uint256 totalSupply_) internal initializer { _name = name_; _symbol = symbol_; _decimals = decimals_; _totalSupply = totalSupply_; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } // Allows "owner" to Pause the token transactions, used during maintenance periods or when upgrading token to new version. function pause() public onlyOwner { _pause(); } // Allows "owner" to Un-Pause the token transactions, used after maintenance periods are finished or once upgrade is complete. function unpause() public onlyOwner { _unpause(); } // Returns the token name. function name() public override view returns (string memory) { return _name; } // Returns the token symbol. function symbol() public override view returns (string memory) { return _symbol; } // Returns the token decimals. function decimals() public override view returns (uint8) { return _decimals; } // Returns the total supply of token. function totalSupply() public override view returns (uint256) { return _totalSupply; } // Returns balance of the referenced 'account' address. function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } // Returns the remaining tokens that the 'spender' address can spend on behalf of the 'owner' address through the {transferFrom} function. function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } // Atomically increases the allowance granted to `spender` by the caller. function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, (_allowances[_msgSender()][spender] + addedValue)); return true; } // Atomically decreases the allowance granted to `spender` by the caller. function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require((_allowances[_msgSender()][spender] - subtractedValue) >= 0, "BEP20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, (_allowances[_msgSender()][spender] - subtractedValue)); } return true; } // Sets 'amount' as the allowance of 'spender' then returns a boolean indicating result of operation. Emits an {Approval} event. function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } // Sets 'amount' as the allowance of 'spender' then returns a boolean indicating result of operation. Emits an {Approval} event. function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } // Transfers an 'amount' of tokens from the callers account to the referenced 'recipient' address. Emits a {Transfer} event. function transfer(address recipient, uint256 amount) public override whenNotPaused returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } // Transfers an 'amount' of tokens from the 'sender' address to the 'recipient' address. Emits a {Transfer} event. function transferFrom(address sender, address recipient, uint256 amount) public override whenNotPaused returns (bool) { _transfer(sender, recipient, amount); require(amount <= _allowances[sender][_msgSender()], "BEP20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), (_allowances[sender][_msgSender()] - amount)); } return true; } // Internal function that moves tokens `amount` from `sender` to `recipient`. function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); require(amount <= _balances[sender], "BEP20: transfer amount exceeds balance"); unchecked { _balances[sender] = _balances[sender] - amount; } _balances[recipient] = _balances[recipient] + amount; emit Transfer(sender, recipient, amount); } /* Hook that is called before any transfer of tokens. This includes minting and burning. (Though mint and burn functions are not used in the GaussGANG token) 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. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /* Hook that is called after any transfer of tokens. This includes minting and burning.(Though mint and burn functions are not used in the GaussGANG token) Calling conditions: - when `from` and `to` are both non-zero, `amount` of ``from``'s tokenshas 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. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} uint256[45] private __gap; }
Atomically increases the allowance granted to `spender` by the caller.
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, (_allowances[_msgSender()][spender] + addedValue)); return true; }
12,752,679
/* 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; import { BaseMath } from "../protocol/lib/BaseMath.sol"; import { Math } from "../protocol/lib/Math.sol"; import { ReentrancyGuard } from "../protocol/lib/ReentrancyGuard.sol"; import { Require } from "../protocol/lib/Require.sol"; import { SafeCast } from "../protocol/lib/SafeCast.sol"; import { SignedMath } from "../protocol/lib/SignedMath.sol"; import { Storage } from "../protocol/lib/Storage.sol"; import { TypedSignature } from "../protocol/lib/TypedSignature.sol"; import { P1BalanceMath } from "../protocol/v1/lib/P1BalanceMath.sol"; import { P1Types } from "../protocol/v1/lib/P1Types.sol"; /** * @title Test_Lib * @author dYdX * * @notice Exposes library functions for testing. */ /* solium-disable-next-line camelcase */ contract Test_Lib is ReentrancyGuard { // ============ BaseMath.sol ============ function base() external pure returns (uint256) { return BaseMath.base(); } function baseMul( uint256 value, uint256 basedValue ) external pure returns (uint256) { return BaseMath.baseMul(value, basedValue); } function baseMulRoundUp( uint256 value, uint256 basedValue ) external pure returns (uint256) { return BaseMath.baseMulRoundUp(value, basedValue); } // ============ Math.sol ============ function getFraction( uint256 target, uint256 numerator, uint256 denominator ) external pure returns (uint256) { return Math.getFraction(target, numerator, denominator); } function getFractionRoundUp( uint256 target, uint256 numerator, uint256 denominator ) external pure returns (uint256) { return Math.getFractionRoundUp(target, numerator, denominator); } function min( uint256 a, uint256 b ) external pure returns (uint256) { return Math.min(a, b); } function max( uint256 a, uint256 b ) external pure returns (uint256) { return Math.max(a, b); } // ============ Require.sol ============ function that( bool must, string calldata requireReason, address addr ) external pure { Require.that( must, requireReason, addr ); } // ============ SafeCast.sol ============ function toUint128( uint256 value ) external pure returns (uint128) { return SafeCast.toUint128(value); } function toUint120( uint256 value ) external pure returns (uint120) { return SafeCast.toUint120(value); } function toUint32( uint256 value ) external pure returns (uint32) { return SafeCast.toUint32(value); } // ============ SignedMath.sol ============ function add( SignedMath.Int calldata sint, uint256 value ) external pure returns (SignedMath.Int memory) { return SignedMath.add(sint, value); } function sub( SignedMath.Int calldata sint, uint256 value ) external pure returns (SignedMath.Int memory) { return SignedMath.sub(sint, value); } function signedAdd( SignedMath.Int calldata augend, SignedMath.Int calldata addend ) external pure returns (SignedMath.Int memory) { return SignedMath.signedAdd(augend, addend); } function signedSub( SignedMath.Int calldata minuend, SignedMath.Int calldata subtrahend ) external pure returns (SignedMath.Int memory) { return SignedMath.signedSub(minuend, subtrahend); } // ============ Storage.sol ============ function load( bytes32 slot ) external view returns (bytes32) { return Storage.load(slot); } function store( bytes32 slot, bytes32 value ) external { Storage.store(slot, value); } // ============ TypedSignature.sol ============ function recover( bytes32 hash, bytes calldata signatureBytes ) external pure returns (address) { TypedSignature.Signature memory signature = abi.decode( signatureBytes, (TypedSignature.Signature) ); return TypedSignature.recover(hash, signature); } // ============ P1BalanceMath.sol ============ function copy( P1Types.Balance calldata balance ) external pure returns (P1Types.Balance memory) { return P1BalanceMath.copy(balance); } function addToMargin( P1Types.Balance calldata balance, uint256 amount ) external pure returns (P1Types.Balance memory) { // Copy to memory, modify in place, and return the memory object. P1Types.Balance memory _balance = balance; P1BalanceMath.addToMargin(_balance, amount); return _balance; } function subFromMargin( P1Types.Balance calldata balance, uint256 amount ) external pure returns (P1Types.Balance memory) { // Copy to memory, modify in place, and return the memory object. P1Types.Balance memory _balance = balance; P1BalanceMath.subFromMargin(_balance, amount); return _balance; } function addToPosition( P1Types.Balance calldata balance, uint256 amount ) external pure returns (P1Types.Balance memory) { // Copy to memory, modify in place, and return the memory object. P1Types.Balance memory _balance = balance; P1BalanceMath.addToPosition(_balance, amount); return _balance; } function subFromPosition( P1Types.Balance calldata balance, uint256 amount ) external pure returns (P1Types.Balance memory) { // Copy to memory, modify in place, and return the memory object. P1Types.Balance memory _balance = balance; P1BalanceMath.subFromPosition(_balance, amount); return _balance; } function getPositiveAndNegativeValue( P1Types.Balance calldata balance, uint256 price ) external pure returns (uint256, uint256) { return P1BalanceMath.getPositiveAndNegativeValue(balance, price); } function getMargin( P1Types.Balance calldata balance ) external pure returns (SignedMath.Int memory) { return P1BalanceMath.getMargin(balance); } function getPosition( P1Types.Balance calldata balance ) external pure returns (SignedMath.Int memory) { return P1BalanceMath.getPosition(balance); } function setMargin( P1Types.Balance calldata balance, SignedMath.Int calldata newMargin ) external pure returns (P1Types.Balance memory) { // Copy to memory, modify in place, and return the memory object. P1Types.Balance memory _balance = balance; P1BalanceMath.setMargin(_balance, newMargin); return _balance; } function setPosition( P1Types.Balance calldata balance, SignedMath.Int calldata newPosition ) external pure returns (P1Types.Balance memory) { // Copy to memory, modify in place, and return the memory object. P1Types.Balance memory _balance = balance; P1BalanceMath.setPosition(_balance, newPosition); return _balance; } // ============ ReentrancyGuard.sol ============ function nonReentrant1() public nonReentrant returns (uint256) { return this.nonReentrant2(); } function nonReentrant2() public nonReentrant returns (uint256) { return 0; } }
Copy to memory, modify in place, and return the memory object.
function setPosition( P1Types.Balance calldata balance, SignedMath.Int calldata newPosition ) external pure returns (P1Types.Balance memory) { P1Types.Balance memory _balance = balance; P1BalanceMath.setPosition(_balance, newPosition); return _balance; }
6,456,092
pragma solidity ^0.5.16; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => uint256) private authorizedContracts; // Airlines struct Airline { uint256 funds; bool isFunded; bool isRegistered; } uint256 registeredAirlineCount = 0; uint256 fundedAirlineCount = 0; mapping(address => Airline) private airlines; // Flights struct Flight { bool isRegistered; bytes32 flightKey; address Airline; string flightNumber; uint8 statusCode; uint256 timeStamp; string depatureLocation; string arrivalLocation; } mapping(bytes32 => Flight) public flights; bytes32[] public registeredFlights; // Insurance Claims struct InsuranceClaim { address passenger; uint256 purchaseAmount; uint256 payoutPercent; bool isCredited; } mapping(bool => InsuranceClaim[]) public creditedGroup; // Flight Insurance Claims mapping(bytes32 => InsuranceClaim[]) public flightInsuranceClaims; // Passenger Insurance Claims mapping(address => uint256) public returnedFunds; /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address airlineAddress) public { contractOwner = msg.sender; airlines[airlineAddress] = Airline(0, true, false); } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AirlineRegistered(address airline); event AirlineFunded(address airline); event FlightRegistered(bytes32 flightkeys); event ProcessedFlightStatus(bytes32 flightKey, uint8 statusCode); event PassengerInsured( bytes32 flightKey, address passenger, uint256 amount, uint256 payout ); event CreditInsuree(bytes32 flightKey, address passenger, uint256 amount); event PayInsuree(address payoutAddress, uint256 amount); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that checks if caller is authorized */ modifier requireIsCallerAuthorized() { require(authorizedContracts[msg.sender] == 1, "caller is not authorized"); _; } /** * @dev Modifier that requires an Airline is not registered yet */ modifier requireAirlineIsNotRegistered(address airline) { require(!airlines[airline].isRegistered, "Airline is already registered"); _; } /** * @dev Modifier that requires an Airline is not funded yet */ modifier requireAirlineIsNotFunded(address airline) { require(!airlines[airline].isFunded, "Airline is already funded"); _; } /** * @dev Modifier that checks if Airline is registered yet */ modifier requireAirlineIsRegistered(address airline) { require(airlines[airline].isRegistered, "Airline is not registered"); _; } /** * @dev Modifier that checks if Airline is funded yet */ modifier requireAirlineIsFunded(address airline) { require(airlines[airline].isFunded, "Airline is not funded"); _; } /** * @dev Modifier that checks Flight is not registered yet */ modifier requireFlightIsNotRegistered(bytes32 flightKey) { require(!flights[flightKey].isRegistered, "Flight is already registered"); _; } /** * @dev Modifier that checks if Flight is registered yet */ modifier requireFlightIsRegistered(bytes32 flightKey) { require(flights[flightKey].isRegistered, "Flight is not registered"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Checks if airline is registered * returns (true/false) */ function isAirlineRegistered(address airline) public view requireIsOperational returns ( // requireIsCallerAuthorized bool ) { return airlines[airline].isRegistered; } /** * @dev Checks if airline is funded * returns (true/false) */ function isAirlineFunded(address airline) public view returns (bool) { return airlines[airline].isFunded; } /** * @dev Checks if flight is registered * returns (true/false) */ function isFlightRegistered(bytes32 flightKey) public view returns (bool) { return flights[flightKey].isRegistered; } /** * @dev Checks if airline is funded * returns (true/false) */ function isFlightLanded(bytes32 flightKey) public view returns (bool) { if (flights[flightKey].statusCode > 0) { return true; } return false; } function flightInsuredForPassenger(bytes32 flightKey, address passenger) public view returns (bool) { InsuranceClaim[] memory insuranceClaims = flightInsuranceClaims[flightKey]; for (uint256 i = 0; i < insuranceClaims.length; i++) { if (insuranceClaims[i].passenger == passenger) { return true; } } } /** * @dev Gets the number of airlines already registered * returns number of registered airlines */ function getRegisteredAirlineCount() public view requireIsOperational requireIsCallerAuthorized returns (uint256) { return registeredAirlineCount; } /** * @dev Gets the number of airlines already funded * returns number of funded airlines */ function getFundedAirlineCount() public view requireIsOperational requireIsCallerAuthorized returns (uint256) { return fundedAirlineCount; } /** * @dev Gets the number of flights already registered * returns number of registered flights */ function getRegisteredFlightCount() public view requireIsOperational requireIsCallerAuthorized returns (uint256) { return registeredFlights.length; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address newAirline, address registeringAirline) external requireIsOperational requireIsCallerAuthorized requireAirlineIsNotRegistered(newAirline) requireAirlineIsFunded(registeringAirline) { airlines[newAirline] = Airline(0, true, false); registeredAirlineCount = registeredAirlineCount.add(1); emit AirlineRegistered(newAirline); } function registerFlight( bytes32 flightKey, uint256 timestamp, address airline, string memory flightNumber, string memory departureLocation, string memory arrivalLocation ) public payable requireIsOperational requireIsCallerAuthorized requireAirlineIsFunded(airline) requireFlightIsNotRegistered(flightKey) { flights[flightKey] = Flight( true, flightKey, airline, flightNumber, 0, timestamp, departureLocation, arrivalLocation ); registeredFlights.push(flightKey); emit FlightRegistered(flightKey); } /** * @dev Determines the status for flight * returns status code for flight */ function processFlightStatus( address airline, string calldata flight, uint256 timestamp, uint8 statusCode ) external requireIsOperational requireIsCallerAuthorized { bytes32 flightKey = getFlightKey(airline, flight, timestamp); require(!isFlightLanded(flightKey), "Flight has landed already."); if (flights[flightKey].statusCode == 0) { flights[flightKey].statusCode = statusCode; if (statusCode == 20) { creditInsurees(flightKey); } } emit ProcessedFlightStatus(flightKey, statusCode); } /** * @dev Buy insurance for a flight * */ function buy( bytes32 flightKey, address passenger, uint256 amount, uint256 payout ) external payable requireIsOperational requireIsCallerAuthorized { require(isFlightRegistered(flightKey), "Flight is already registered"); require(!isFlightLanded(flightKey), "Flight has already landed"); flightInsuranceClaims[flightKey].push( InsuranceClaim(passenger, amount, payout, false) ); emit PassengerInsured(flightKey, passenger, amount, payout); } /** * @dev Credits payouts to insurees */ function creditInsurees(bytes32 flightKey) internal requireIsOperational requireIsCallerAuthorized { for (uint256 i = 0; i < flightInsuranceClaims[flightKey].length; i++) { InsuranceClaim memory insuranceClaim = flightInsuranceClaims[flightKey][i]; insuranceClaim.isCredited = true; uint256 amount = insuranceClaim.purchaseAmount.mul(insuranceClaim.payoutPercent).div( 100 ); returnedFunds[insuranceClaim.passenger] = returnedFunds[ insuranceClaim.passenger ] .add(amount); emit CreditInsuree(flightKey, insuranceClaim.passenger, amount); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address payable payoutAddress) external payable requireIsOperational requireIsCallerAuthorized { uint256 amount = returnedFunds[payoutAddress]; require(address(this).balance >= amount, "Contract has insufficentt funds"); require(amount > 0, "No funds avaiable for withdraw"); returnedFunds[payoutAddress] = 0; address(uint160(address(payoutAddress))).transfer(amount); emit PayInsuree(payoutAddress, amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address airline, uint256 amount) external requireIsOperational requireIsCallerAuthorized requireAirlineIsRegistered(airline) requireAirlineIsNotFunded(airline) returns (bool) { airlines[airline].isFunded = true; airlines[airline].funds = airlines[airline].funds.add(amount); fundedAirlineCount = fundedAirlineCount.add(1); emit AirlineFunded(airline); return airlines[airline].isFunded; } function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { // fund(); } }
Add an airline to the registration queue Can only be called from FlightSuretyApp contract/
function registerAirline(address newAirline, address registeringAirline) external requireIsOperational requireIsCallerAuthorized requireAirlineIsNotRegistered(newAirline) requireAirlineIsFunded(registeringAirline) { airlines[newAirline] = Airline(0, true, false); registeredAirlineCount = registeredAirlineCount.add(1); emit AirlineRegistered(newAirline); }
5,537,537
// Sources flattened with hardhat v2.8.2 https://hardhat.org // File @openzeppelin/contracts/utils/math/SafeMath.sol@v4.4.2 // // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/external/Decimal.sol /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <emptysetsquad@protonmail.com> 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.8.4; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({value: 0}); } function one() internal pure returns (D256 memory) { return D256({value: BASE}); } function from(uint256 a) internal pure returns (D256 memory) { return D256({value: a.mul(BASE)}); } function ratio(uint256 a, uint256 b) internal pure returns (D256 memory) { return D256({value: getPartial(a, BASE, b)}); } // ============ Self Functions ============ function add(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.add(b.mul(BASE))}); } function sub(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.mul(BASE))}); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.mul(BASE), reason)}); } function mul(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.mul(b)}); } function div(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.div(b)}); } function pow(D256 memory self, uint256 b) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({value: self.value}); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: self.value.add(b.value)}); } function sub(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.value)}); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.value, reason)}); } function mul(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: getPartial(self.value, b.value, BASE)}); } function div(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: getPartial(self.value, BASE, b.value)}); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo(D256 memory a, D256 memory b) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // File @openzeppelin/contracts/access/IAccessControl.sol@v4.4.2 // // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/utils/Context.sol@v4.4.2 // // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/Strings.sol@v4.4.2 // // 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/introspection/IERC165.sol@v4.4.2 // // 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@v4.4.2 // // 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/access/AccessControl.sol@v4.4.2 // // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `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}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/core/IPermissionsRead.sol pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // File contracts/core/IPermissions.sol pragma solidity ^0.8.4; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.4.2 // // OpenZeppelin Contracts v4.4.1 (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); } // File contracts/volt/IVolt.sol pragma solidity ^0.8.4; /// @title FEI stablecoin interface /// @author Fei Protocol interface IVolt is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; } // File contracts/core/ICore.sol pragma solidity ^0.8.4; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event VoltUpdate(IERC20 indexed _volt); event VconUpdate(IERC20 indexed _vcon); // ----------- Getters ----------- function volt() external view returns (IVolt); function vcon() external view returns (IERC20); } // File contracts/refs/ICoreRef.sol pragma solidity ^0.8.4; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate( bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole ); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function volt() external view returns (IVolt); function vcon() external view returns (IERC20); function voltBalance() external view returns (uint256); function vconBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // File @openzeppelin/contracts/security/Pausable.sol@v4.4.2 // // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @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()); } } // File contracts/refs/CoreRef.sol pragma solidity ^0.8.4; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IVolt private immutable _volt; IERC20 private immutable _vcon; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _volt = ICore(coreAddress).volt(); _vcon = ICore(coreAddress).vcon(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize() internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin" ); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfThreeRoles( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFourRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFiveRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED" ); _; } modifier onlyVolt() { require(msg.sender == address(_volt), "CoreRef: Caller is not VOLT"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function volt() public view override returns (IVolt) { return _volt; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function vcon() public view override returns (IERC20) { return _vcon; } /// @notice volt balance of contract /// @return volt amount held function voltBalance() public view override returns (uint256) { return _volt.balanceOf(address(this)); } /// @notice vcon balance of contract /// @return vcon amount held function vconBalance() public view override returns (uint256) { return _vcon.balanceOf(address(this)); } function _burnVoltHeld() internal { _volt.burn(voltBalance()); } function _mintVolt(address to, uint256 amount) internal virtual { if (amount != 0) { _volt.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate( oldContractAdminRole, newContractAdminRole ); } } // File contracts/oracle/IScalingPriceOracle.sol pragma solidity ^0.8.4; /// @notice contract that receives a chainlink price feed and then linearly interpolates that rate over /// a 1 month period into the VOLT price. Interest is compounded monthly when the rate is updated /// @author Elliot Friedman interface IScalingPriceOracle { /// @notice the time frame over which all changes in CPI data are applied /// 28 days was chosen as that is the shortest length of a month function TIMEFRAME() external view returns (uint256); /// @notice the maximum allowable deviation in basis points for a new chainlink oracle update /// only allow price changes by 20% in a month. /// Any change over this threshold in either direction will be rejected function MAXORACLEDEVIATION() external view returns (uint256); /// @notice get the current scaled oracle price /// applies the change smoothly over a 28 day period /// scaled by 18 decimals function getCurrentOraclePrice() external view returns (uint256); /// @notice current amount that oracle price is inflating/deflating by monthly in basis points function monthlyChangeRateBasisPoints() external view returns (int256); /// @notice oracle price. starts off at 1 scaled up by 18 decimals function oraclePrice() external view returns (uint256); /// @notice event when the monthly change rate is updated event CPIMonthlyChangeRateUpdate( int256 oldChangeRateBasisPoints, int256 newChangeRateBasisPoints ); } // File contracts/oracle/IOraclePassThrough.sol pragma solidity ^0.8.4; /// @notice interface to get data from the Scaling Price Oracle interface IOraclePassThrough { // ----------- Getters ----------- /// @notice reference to the scaling price oracle function scalingPriceOracle() external view returns (IScalingPriceOracle); /// @notice function to get the current oracle price for the OracleRef contract function read() external view returns (Decimal.D256 memory price, bool valid); /// @notice function to get the current oracle price for the entire system function getCurrentOraclePrice() external view returns (uint256); // ----------- Governor only state changing api ----------- /// @notice function to update the pointer to the scaling price oracle /// requires approval from both VOLT and FRAX governance to sign off on the change function updateScalingPriceOracle(IScalingPriceOracle newScalingPriceOracle) external; /// @notice event emitted when the scaling price oracle is updated event ScalingPriceOracleUpdate( IScalingPriceOracle oldScalingPriceOracle, IScalingPriceOracle newScalingPriceOracle ); } // File @openzeppelin/contracts/access/Ownable.sol@v4.4.2 // // 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/oracle/OraclePassThrough.sol pragma solidity ^0.8.4; /// @notice contract that passes all price calls to the Scaling Price Oracle /// The Scaling Price Oracle can be changed if there is a decision to change how data is interpolated /// without needing all contracts in the system to be upgraded, only this contract will have to change where it points /// @author Elliot Friedman contract OraclePassThrough is IOraclePassThrough, Ownable { using Decimal for Decimal.D256; /// @notice reference to the scaling price oracle IScalingPriceOracle public override scalingPriceOracle; constructor(IScalingPriceOracle _scalingPriceOracle) Ownable() { scalingPriceOracle = _scalingPriceOracle; } /// @notice updates the oracle price /// @dev no-op, ScalingPriceOracle is updated automatically /// added for backwards compatibility with OracleRef function update() public {} // ----------- Getters ----------- /// @notice function to get the current oracle price for the OracleRef contract function read() external view override returns (Decimal.D256 memory price, bool valid) { uint256 currentPrice = scalingPriceOracle.getCurrentOraclePrice(); price = Decimal.from(currentPrice).div(1e18); valid = true; } /// @notice function to get the current oracle price for the entire system function getCurrentOraclePrice() external view override returns (uint256) { return scalingPriceOracle.getCurrentOraclePrice(); } // ----------- Governance only state changing api ----------- /// @notice function to update the pointer to the scaling price oracle /// requires approval from all parties on multisig to update function updateScalingPriceOracle(IScalingPriceOracle newScalingPriceOracle) external override onlyOwner { IScalingPriceOracle oldScalingPriceOracle = scalingPriceOracle; scalingPriceOracle = newScalingPriceOracle; emit ScalingPriceOracleUpdate( oldScalingPriceOracle, newScalingPriceOracle ); } }
interface to get data from the Scaling Price Oracle ----------- Getters ----------- ----------- Governor only state changing api -----------
interface IOraclePassThrough { function scalingPriceOracle() external view returns (IScalingPriceOracle); function read() external view returns (Decimal.D256 memory price, bool valid); function getCurrentOraclePrice() external view returns (uint256); function updateScalingPriceOracle(IScalingPriceOracle newScalingPriceOracle) external; event ScalingPriceOracleUpdate( IScalingPriceOracle oldScalingPriceOracle, IScalingPriceOracle newScalingPriceOracle ); } }
10,354,473
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract NonFungibleZine is ERC721, ERC721URIStorage, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenSupply; // Define starting contract state bytes32 merkleRoot; bool merkleSet = false; bool public earlyAccessMode = true; bool public mintingIsActive = false; bool public reservedZines = false; string public baseURI = ""; uint256 public randPrime; uint256 public timestamp; uint256 public constant maxSupply = 1000; uint256 public constant maxMints = 2; constructor() ERC721("Non-Fungible Zine", "NFZ") {} // Withdraw contract balance to creator (mnemonic seed address 0) function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } // Flip the minting from active or pause function toggleMinting() external onlyOwner { if (mintingIsActive) { mintingIsActive = false; } else { mintingIsActive = true; } } // Flip the early access mode to allow/disallow public minting vs whitelist function toggleEarlyAccessMode() external onlyOwner { if (earlyAccessMode) { earlyAccessMode = false; } else { earlyAccessMode = true; } } // Specify a randomly generated prime number (off-chain), only once function setRandPrime(uint256 _randPrime) public onlyOwner { if (randPrime == 0) { randPrime = _randPrime; } } // Specify a new IPFS URI for metadata function setBaseURI(string memory URI) public onlyOwner { baseURI = URI; } // Get total supply based upon counter function tokensMinted() public view returns (uint256) { return _tokenSupply.current(); } // Specify a merkle root hash from the gathered k/v dictionary of // addresses and their claimable amount of tokens - thanks Kiwi! // https://github.com/0xKiwi/go-merkle-distributor function setMerkleRoot(bytes32 root) external onlyOwner { merkleRoot = root; merkleSet = true; } // Return bool on if merkle root hash is set function isMerkleSet() public view returns (bool) { return merkleSet; } // Internal mint function with proper "random-ish" logic function _mintZines(uint256 numberOfTokens) private { require(randPrime > 0, "Random prime number must be specified by contract owner before minting"); require(numberOfTokens > 0, "Must mint at least 1 token"); // Specify the block timestamp of the first mint to define NFT distribution if (timestamp == 0) { timestamp = block.timestamp; } // Mint i tokens where i is specified by function invoker for(uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenIndex = tokensMinted() + 1; // Start at 1 uint256 seq = randPrime * tokenIndex; uint256 seqOffset = seq + timestamp; uint256 tokenId = (seqOffset % maxSupply) + 1; // Prevent tokenId 0 _safeMint(msg.sender, tokenId); _tokenSupply.increment(); } // Disable minting if max supply of tokens is reached if (tokensMinted() == maxSupply) { mintingIsActive = false; } } // Reserve some zines for giveaways function reserveZines() public onlyOwner { // Only allow one-time reservation if (!reservedZines) { _mintZines(20); reservedZines = true; } } // Claim and mint tokens function mintZines( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 numberOfTokens ) external { require(mintingIsActive, "Minting is not active."); require(numberOfTokens <= maxMints, "Cannot mint more than 2"); require(tokensMinted().add(numberOfTokens) <= maxSupply, "Minting would exceed max supply"); require(balanceOf(msg.sender).add(numberOfTokens) <= maxMints, "Minting would exceed maximum amount of 2 tokens per wallet."); if (earlyAccessMode) { require(merkleSet, "Merkle root not set by contract owner"); require(msg.sender == account, "Can only be claimed by the hodler"); // Verify merkle proof bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid merkle proof"); } _mintZines(numberOfTokens); } // Override the below functions from parent contracts function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return string(abi.encodePacked(baseURI, Strings.toString(tokenId))); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } } // 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/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 (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/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // 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/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.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 (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 (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.0 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @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]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (token/ERC721/ERC721.sol) 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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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); } }
Reserve some zines for giveaways Only allow one-time reservation
function reserveZines() public onlyOwner { if (!reservedZines) { _mintZines(20); reservedZines = true; } }
6,254,149
//SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // Inheritance import "../interfaces/IStakingRewards.sol"; import "../interfaces/Pausable.sol"; import "../interfaces/RewardsDistributionRecipient.sol"; import "../interfaces/OnDemandToken.sol"; import "../interfaces/MintableToken.sol"; // based on synthetix contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, Pausable { using SafeERC20 for IERC20; struct Times { uint32 periodFinish; uint32 rewardsDuration; uint32 lastUpdateTime; uint96 totalRewardsSupply; } // ========== STATE VARIABLES ========== // uint256 public immutable maxEverTotalRewards; IERC20 public immutable rewardsToken; IERC20 public immutable stakingToken; uint256 public rewardRate = 0; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; Times public timeData; bool public stopped; // ========== EVENTS ========== // event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event FarmingFinished(); // ========== MODIFIERS ========== // modifier whenActive() { require(!stopped, "farming is stopped"); _; } modifier updateReward(address account) virtual { uint256 newRewardPerTokenStored = rewardPerToken(); rewardPerTokenStored = newRewardPerTokenStored; timeData.lastUpdateTime = uint32(lastTimeRewardApplicable()); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = newRewardPerTokenStored; } _; } // ========== CONSTRUCTOR ========== // constructor( address _owner, address _rewardsDistribution, address _stakingToken, address _rewardsToken ) Owned(_owner) { require(OnDemandToken(_rewardsToken).ON_DEMAND_TOKEN(), "rewardsToken must be OnDemandToken"); stakingToken = IERC20(_stakingToken); rewardsToken = IERC20(_rewardsToken); rewardsDistribution = _rewardsDistribution; timeData.rewardsDuration = 2592000; // 30 days maxEverTotalRewards = MintableToken(_rewardsToken).maxAllowedTotalSupply(); } // ========== RESTRICTED FUNCTIONS ========== // function notifyRewardAmount( uint256 _reward ) override virtual external whenActive onlyRewardsDistribution updateReward(address(0)) { Times memory t = timeData; uint256 newRewardRate; if (block.timestamp >= t.periodFinish) { newRewardRate = _reward / t.rewardsDuration; } else { uint256 remaining = t.periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; newRewardRate = (_reward + leftover) / t.rewardsDuration; } require(newRewardRate != 0, "invalid rewardRate"); rewardRate = newRewardRate; // always increasing by _reward even if notification is in a middle of period // because leftover is included uint256 totalRewardsSupply = timeData.totalRewardsSupply + _reward; require(totalRewardsSupply <= maxEverTotalRewards, "rewards overflow"); timeData.totalRewardsSupply = uint96(totalRewardsSupply); timeData.lastUpdateTime = uint32(block.timestamp); timeData.periodFinish = uint32(block.timestamp + t.rewardsDuration); emit RewardAdded(_reward); } function setRewardsDuration(uint256 _rewardsDuration) external whenActive onlyOwner { require(_rewardsDuration != 0, "empty _rewardsDuration"); require( block.timestamp > timeData.periodFinish, "Previous period must be complete before changing the duration" ); timeData.rewardsDuration = uint32(_rewardsDuration); emit RewardsDurationUpdated(_rewardsDuration); } // when farming was started with 1y and 12tokens // and we want to finish after 4 months, we need to end up with situation // like we were starting with 4mo and 4 tokens. function finishFarming() virtual external whenActive onlyOwner { Times memory t = timeData; require(block.timestamp < t.periodFinish, "can't stop if not started or already finished"); stopped = true; if (_totalSupply != 0) { uint256 remaining = t.periodFinish - block.timestamp; timeData.rewardsDuration = uint32(t.rewardsDuration - remaining); } timeData.periodFinish = uint32(block.timestamp); emit FarmingFinished(); } // ========== MUTATIVE FUNCTIONS ========== // function exit() override external { withdraw(_balances[msg.sender]); getReward(); } function stake(uint256 amount) override external { _stake(msg.sender, amount, false); } function rescueToken(ERC20 _token, address _recipient, uint256 _amount) external onlyOwner() { if (address(_token) == address(stakingToken)) { require(_totalSupply <= stakingToken.balanceOf(address(this)) - _amount, "amount is too big to rescue"); } else if (address(_token) == address(rewardsToken)) { revert("reward token can not be rescued"); } _token.transfer(_recipient, _amount); } function periodFinish() external view returns (uint256) { return timeData.periodFinish; } function rewardsDuration() external view returns (uint256) { return timeData.rewardsDuration; } function lastUpdateTime() external view returns (uint256) { return timeData.lastUpdateTime; } function balanceOf(address account) override external view returns (uint256) { return _balances[account]; } function getRewardForDuration() override external view returns (uint256) { return rewardRate * timeData.rewardsDuration; } function version() external pure virtual returns (uint256) { return 1; } function withdraw(uint256 amount) override public { _withdraw(amount, msg.sender, msg.sender); } function getReward() override public { _getReward(msg.sender, msg.sender); } // ========== VIEWS ========== // function totalSupply() override public view returns (uint256) { return _totalSupply; } function lastTimeRewardApplicable() override public view returns (uint256) { return Math.min(block.timestamp, timeData.periodFinish); } function rewardPerToken() override public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + ( (lastTimeRewardApplicable() - timeData.lastUpdateTime) * rewardRate * 1e18 / _totalSupply ); } function earned(address account) override virtual public view returns (uint256) { return (_balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18) + rewards[account]; } function _stake(address user, uint256 amount, bool migration) internal nonReentrant notPaused updateReward(user) { require(timeData.periodFinish != 0, "Stake period not started yet"); require(amount != 0, "Cannot stake 0"); _totalSupply = _totalSupply + amount; _balances[user] = _balances[user] + amount; if (migration) { // other contract will send tokens to us, this will save ~13K gas } else { // not using safe transfer, because we working with trusted tokens require(stakingToken.transferFrom(user, address(this), amount), "token transfer failed"); } emit Staked(user, amount); } /// @param amount tokens to withdraw /// @param user address /// @param recipient address, where to send tokens, if we migrating token address can be zero function _withdraw(uint256 amount, address user, address recipient) internal nonReentrant updateReward(user) { require(amount != 0, "Cannot withdraw 0"); // not using safe math, because there is no way to overflow if stake tokens not overflow _totalSupply = _totalSupply - amount; _balances[user] = _balances[user] - amount; // not using safe transfer, because we working with trusted tokens require(stakingToken.transfer(recipient, amount), "token transfer failed"); emit Withdrawn(user, amount); } /// @param user address /// @param recipient address, where to send reward function _getReward(address user, address recipient) internal virtual nonReentrant updateReward(user) returns (uint256 reward) { reward = rewards[user]; if (reward != 0) { rewards[user] = 0; OnDemandToken(address(rewardsToken)).mint(recipient, reward); emit RewardPaid(user, reward); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.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; 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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `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 virtual { _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 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface IStakingRewards { // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; abstract contract Pausable is Owned { bool public paused; event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } constructor() { // This contract is abstract, and thus cannot be instantiated directly require(owner() != address(0), "Owner must be set"); // Paused will be false } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // Let everyone know that our pause state has changed. emit PauseChanged(paused); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; // Inheritance import "./Owned.sol"; // https://docs.synthetix.io/contracts/RewardsDistributionRecipient abstract contract RewardsDistributionRecipient is Owned { address public rewardsDistribution; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistributor"); _; } function notifyRewardAmount(uint256 reward) virtual external; function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { rewardsDistribution = _rewardsDistribution; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "./MintableToken.sol"; abstract contract OnDemandToken is MintableToken { bool constant public ON_DEMAND_TOKEN = true; mapping (address => bool) public minters; event SetupMinter(address minter, bool active); modifier onlyOwnerOrMinter() { address msgSender = _msgSender(); require(owner() == msgSender || minters[msgSender], "access denied"); _; } function setupMinter(address _minter, bool _active) external onlyOwner() { minters[_minter] = _active; emit SetupMinter(_minter, _active); } function setupMinters(address[] calldata _minters, bool[] calldata _actives) external onlyOwner() { for (uint256 i; i < _minters.length; i++) { minters[_minters[i]] = _actives[i]; emit SetupMinter(_minters[i], _actives[i]); } } function mint(address _holder, uint256 _amount) external virtual override onlyOwnerOrMinter() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/Owned.sol"; import "../interfaces/IBurnableToken.sol"; /// @author umb.network abstract contract MintableToken is Owned, ERC20, IBurnableToken { uint256 public immutable maxAllowedTotalSupply; uint256 public everMinted; modifier assertMaxSupply(uint256 _amountToMint) { _assertMaxSupply(_amountToMint); _; } // ========== CONSTRUCTOR ========== // constructor (uint256 _maxAllowedTotalSupply) { require(_maxAllowedTotalSupply != 0, "_maxAllowedTotalSupply is empty"); maxAllowedTotalSupply = _maxAllowedTotalSupply; } // ========== MUTATIVE FUNCTIONS ========== // function burn(uint256 _amount) override external { _burn(msg.sender, _amount); } // ========== RESTRICTED FUNCTIONS ========== // function mint(address _holder, uint256 _amount) virtual external onlyOwner() assertMaxSupply(_amount) { require(_amount != 0, "zero amount"); _mint(_holder, _amount); } function _assertMaxSupply(uint256 _amountToMint) internal { uint256 everMintedTotal = everMinted + _amountToMint; everMinted = everMintedTotal; require(everMintedTotal <= maxAllowedTotalSupply, "total supply limit exceeded"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract Owned is Ownable { constructor(address _owner) { transferOwnership(_owner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface IBurnableToken { function burn(uint256 _amount) external; }
amount tokens to withdraw user address recipient address, where to send tokens, if we migrating token address can be zero not using safe math, because there is no way to overflow if stake tokens not overflow not using safe transfer, because we working with trusted tokens
function _withdraw(uint256 amount, address user, address recipient) internal nonReentrant updateReward(user) { require(amount != 0, "Cannot withdraw 0"); _totalSupply = _totalSupply - amount; _balances[user] = _balances[user] - amount; require(stakingToken.transfer(recipient, amount), "token transfer failed"); emit Withdrawn(user, amount); }
405,900
./partial_match/3/0xD701E3ed119715390f0260F5103885ED6A8586EF/sources/UniMexMargin.sol
stack too deep: uint256 loss = owed.sub(swap);uint256 leftover = commitmentInTokens.sub(owed.sub(swap));IERC20(position.token).approve(address(uniswap_router), leftover);uint256 leftoverInEth = swapTokens(position.token, leftover, true, slippage);uint256 fees = (leftoverInEth.mul(8e15)).div(1e18);IERC20(position.token).approve(pool, swap.add(owed.sub(swap)));IERC20(weth).approve(pool, fees.div(2));IERC20(weth).approve(staking, fees.sub(fees.div(2)));IUniMexPool(pool).repay(swap.add(owed.sub(swap)));IUniMexPool(pool).distribute(fees.div(2));IUniMexStaking(pool).distribute(fees.sub(fees.div(2)));transferEscrowToUser(position.owner, address(0x0), position.commitment);transferToUser(position.owner, leftoverInEth.sub(fees));position.isClosed = true;
function closePosition(bytes32 tradeId, uint256 slippage) public { Position storage position = positionInfo[tradeId]; require(msg.sender == position.owner, 'UNIMEX: BORROWER_ONLY'); bool isShort = position.owedTokens > 0 ? true : false; uint256 input = isShort ? position.eths : position.tokens; uint256 owed = isShort ? position.owedTokens : position.owedEths; uint256 value = getValueOfToken(position.token, true, input); bool isClosable = isShort ? ((value < owed) || (value >= owed && value <= (owed.mul(mag.add(margin_call))).div(mag))) : ((value >= owed) || (value < owed && value > (owed.mul(mag.sub(margin_call))).div(mag))); require(isClosable, 'UNIMEX: LIQUIDATE_ONLY'); address pool = isShort ? unimex_factory.getPool(position.token) : unimex_factory.getPool(weth); if(isShort) { if(value < owed) { IERC20(weth).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, false, slippage); uint256 commitment = position.commitment; uint256 profit = swap.sub(owed); IERC20(position.token).approve(address(uniswap_router), profit); uint256 profitInEth = swapTokens(position.token, profit, true, slippage); uint256 fees = (profitInEth.mul(8e15)).div(1e18); uint256 profitInEthMinusFees = profitInEth.sub(fees); IERC20(position.token).approve(pool, owed); IUniMexPool(pool).repay(owed); IERC20(weth).approve(pool, fees.div(2)); IUniMexPool(pool).distribute(fees.div(2)); IERC20(weth).approve(staking, fees.sub(fees.div(2))); IUniMexStaking(staking).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, commitment); transferToUser(position.owner, profitInEthMinusFees); position.isClosed = true; IERC20(weth).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, false, slippage); IERC20(weth).approve(address(uniswap_router), position.commitment); uint256 commitmentInTokens = swapTokens(position.token, position.commitment, true, slippage); } if(value >= owed) { IERC20(position.token).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, true, slippage); uint256 commitment = position.commitment; uint256 profit = swap.sub(owed); uint256 fees = (profit.mul(8e15)).div(1e18); uint256 profitMinusFees = profit.sub(fees); IERC20(weth).approve(pool, owed); IUniMexPool(pool).repay(owed); IERC20(weth).approve(pool, fees.div(2)); IUniMexPool(pool).distribute(fees.div(2)); IERC20(weth).approve(staking, fees.sub(fees.div(2))); IUniMexPool(staking).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, commitment); transferToUser(position.owner, profitMinusFees); position.isClosed = true; IERC20(position.token).approve(address(uniswap_router), input); uint256 swap = swapTokens(position.token, input, true, slippage); uint256 commitment = position.commitment; uint256 loss = owed.sub(swap); uint256 leftover = commitment.sub(loss); uint256 fees = (leftover.mul(8e15)).div(1e18); IERC20(weth).approve(pool, swap.add(loss)); IUniMexPool(pool).repay(swap.add(loss)); IERC20(weth).approve(pool, fees.div(2)); IUniMexPool(pool).distribute(fees.div(2)); IERC20(weth).approve(pool, fees.sub(fees.div(2))); IUniMexStaking(staking).distribute(fees.sub(fees.div(2))); transferEscrowToUser(position.owner, position.owner, leftover.sub(fees)); position.isClosed = true; } } }
5,225,299
./partial_match/56/0x306d649856A746FfCF788f06c7a783a1ae581658/sources/WojakFarming.sol
require((user_blocks_before_claim(_pid, msg.sender) == 0, "Not long enough time staked.")
function withdraw_LP(uint256 _pid, uint amount) public nonReentrant { uint256 countPool = poolList.length; require(_pid < countPool, "Not a valid Pool"); _updatePool(_pid); UserList storage user = userList[_pid][msg.sender]; PoolList storage pool = poolList[_pid]; require(user.stakingAmount > 0, "no balance to withdraw"); _claim(_pid, msg.sender); if(amount == user.stakingAmount){ pool.totalusers -= 1; for(uint256 i = 0; i < pooldatas[_pid].length; i++) { if(pooldatas[_pid][i] == msg.sender){ delete pooldatas[_pid][i]; i = pooldatas[_pid].length; } } } pool.lptotal -= amount; user.stakingAmount -= amount; pool.lptoken.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, address(pool.lptoken) ,amount); }
11,107,029
./full_match/421613/0x152cA8Fa9B9d1B147C821f1b8d2D0D81D6893548/sources/contracts/facets/ItemsFacet.sol
Admin Functions
function mintGameItem( uint8 amount, address to, LibToken.ItemType itemType ) external pausable roleOnly(LibAccessControl.Roles.MINTER) { require(_token().requestedNftConversions[to] >= amount, 'Not enough requested NFT conversions'); if (itemType == LibToken.ItemType.EQUIPMENT) { require( _token().equipmentMintingIsEnabled, 'Equipment minting is not yet available' ); require( _token().chestMintingIsEnabled, 'Chest minting is not yet available' ); revert('Invalid item type'); } uint256[] memory mintedIds = new uint256[](amount); uint256[] memory amounts = new uint256[](amount); for (uint8 i = 0; i < amount; i++) { uint256 tokenId = _generateNftTokenId(); mintedIds[i] = tokenId; amounts[i] = 1; _token().itemTypeByTokenId[tokenId] = itemType; _token().requestedNftConversions[to]--; } _safeMintBatch(to, mintedIds, amounts, ''); }
11,575,342
// Dependency file: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT // pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol // 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; } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol // 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); } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol // pragma solidity >=0.6.2; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-periphery/contracts/interfaces/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; } // Dependency file: @openzeppelin/contracts/math/Math.sol // pragma solidity >=0.6.0 <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); } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/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"); } } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // 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; } } // Dependency file: contracts/interfaces/ISetToken.sol // pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // Dependency file: contracts/interfaces/IBasicIssuanceModule.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity >=0.6.10; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; interface IBasicIssuanceModule { function getRequiredComponentUnitsForIssue( ISetToken _setToken, uint256 _quantity ) external returns(address[] memory, uint256[] memory); function issue(ISetToken _setToken, uint256 _quantity, address _to) external; function redeem(ISetToken _token, uint256 _quantity, address _to) external; } // Dependency file: contracts/interfaces/IController.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity >=0.6.10; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Dependency file: contracts/lib/PreciseUnitMath.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol // 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; } // Dependency file: external/contracts/UniSushiV2Library.sol // pragma solidity >=0.5.0; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; library UniSushiV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // fetches and sorts the reserves for a pair function getReserves(address pair, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // Root file: contracts/exchangeIssuance/ExchangeIssuance.sol /* Copyright 2021 Index Cooperative 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.6.10; // import { Address } from "@openzeppelin/contracts/utils/Address.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; // import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; // import { Math } from "@openzeppelin/contracts/math/Math.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import { IBasicIssuanceModule } from "contracts/interfaces/IBasicIssuanceModule.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { PreciseUnitMath } from "contracts/lib/PreciseUnitMath.sol"; // import { UniSushiV2Library } from "external/contracts/UniSushiV2Library.sol"; /** * @title ExchangeIssuance * @author Index Coop * * Contract for issuing and redeeming any SetToken using ETH or an ERC20 as the paying/receiving currency. * All swaps are done using the best price found on Uniswap or Sushiswap. * */ contract ExchangeIssuance is ReentrancyGuard { using Address for address payable; using SafeMath for uint256; using PreciseUnitMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISetToken; /* ============ Enums ============ */ enum Exchange { Uniswap, Sushiswap, None } /* ============ Constants ============= */ uint256 constant private MAX_UINT96 = 2**96 - 1; address constant public ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /* ============ State Variables ============ */ address public WETH; IUniswapV2Router02 public uniRouter; IUniswapV2Router02 public sushiRouter; address public immutable uniFactory; address public immutable sushiFactory; IController public immutable setController; IBasicIssuanceModule public immutable basicIssuanceModule; /* ============ Events ============ */ event ExchangeIssue( address indexed _recipient, // The recipient address of the issued SetTokens ISetToken indexed _setToken, // The issued SetToken IERC20 indexed _inputToken, // The address of the input asset(ERC20/ETH) used to issue the SetTokens uint256 _amountInputToken, // The amount of input tokens used for issuance uint256 _amountSetIssued // The amount of SetTokens received by the recipient ); event ExchangeRedeem( address indexed _recipient, // The recipient address which redeemed the SetTokens ISetToken indexed _setToken, // The redeemed SetToken IERC20 indexed _outputToken, // The address of output asset(ERC20/ETH) received by the recipient uint256 _amountSetRedeemed, // The amount of SetTokens redeemed for output tokens uint256 _amountOutputToken // The amount of output tokens received by the recipient ); event Refund( address indexed _recipient, // The recipient address which redeemed the SetTokens uint256 _refundAmount // The amount of ETH redunded to the recipient ); /* ============ Modifiers ============ */ modifier isSetToken(ISetToken _setToken) { require(setController.isSet(address(_setToken)), "ExchangeIssuance: INVALID SET"); _; } /* ============ Constructor ============ */ constructor( address _weth, address _uniFactory, IUniswapV2Router02 _uniRouter, address _sushiFactory, IUniswapV2Router02 _sushiRouter, IController _setController, IBasicIssuanceModule _basicIssuanceModule ) public { uniFactory = _uniFactory; uniRouter = _uniRouter; sushiFactory = _sushiFactory; sushiRouter = _sushiRouter; setController = _setController; basicIssuanceModule = _basicIssuanceModule; WETH = _weth; IERC20(WETH).safeApprove(address(uniRouter), PreciseUnitMath.maxUint256()); IERC20(WETH).safeApprove(address(sushiRouter), PreciseUnitMath.maxUint256()); } /* ============ Public Functions ============ */ /** * Runs all the necessary approval functions required for a given ERC20 token. * This function can be called when a new token is added to a SetToken during a * rebalance. * * @param _token Address of the token which needs approval */ function approveToken(IERC20 _token) public { _safeApprove(_token, address(uniRouter), MAX_UINT96); _safeApprove(_token, address(sushiRouter), MAX_UINT96); _safeApprove(_token, address(basicIssuanceModule), MAX_UINT96); } /* ============ External Functions ============ */ receive() external payable { // required for weth.withdraw() to work properly require(msg.sender == WETH, "ExchangeIssuance: Direct deposits not allowed"); } /** * Runs all the necessary approval functions required for a list of ERC20 tokens. * * @param _tokens Addresses of the tokens which need approval */ function approveTokens(IERC20[] calldata _tokens) external { for (uint256 i = 0; i < _tokens.length; i++) { approveToken(_tokens[i]); } } /** * Runs all the necessary approval functions required before issuing * or redeeming a SetToken. This function need to be called only once before the first time * this smart contract is used on any particular SetToken. * * @param _setToken Address of the SetToken being initialized */ function approveSetToken(ISetToken _setToken) isSetToken(_setToken) external { address[] memory components = _setToken.getComponents(); for (uint256 i = 0; i < components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); approveToken(IERC20(components[i])); } } /** * Issues SetTokens for an exact amount of input ERC20 tokens. * The ERC20 token must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being issued * @param _inputToken Address of input token * @param _amountInput Amount of the input token / ether to spend * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput, uint256 _minSetReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _amountInput); uint256 amountEth = address(_inputToken) == WETH ? _amountInput : _swapTokenForWETH(_inputToken, _amountInput); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, amountEth); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _amountInput, setTokenAmount); return setTokenAmount; } /** * Issues SetTokens for an exact amount of input ether. * * @param _setToken Address of the SetToken to be issued * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactETH( ISetToken _setToken, uint256 _minSetReceive ) isSetToken(_setToken) external payable nonReentrant returns(uint256) { require(msg.value > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, msg.value); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), msg.value, setTokenAmount); return setTokenAmount; } /** * Issues an exact amount of SetTokens for given amount of input ERC20 tokens. * The excess amount of tokens is returned in an equivalent amount of ether. * * @param _setToken Address of the SetToken to be issued * @param _inputToken Address of the input token * @param _amountSetToken Amount of SetTokens to issue * @param _maxAmountInputToken Maximum amount of input tokens to be used to issue SetTokens. The unused * input tokens are returned as ether. * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken, uint256 _maxAmountInputToken ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0 && _maxAmountInputToken > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _maxAmountInputToken); uint256 initETHAmount = address(_inputToken) == WETH ? _maxAmountInputToken : _swapTokenForWETH(_inputToken, _maxAmountInputToken); uint256 amountEthSpent = _issueExactSetFromWETH(_setToken, _amountSetToken, initETHAmount); uint256 amountEthReturn = initETHAmount.sub(amountEthSpent); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _maxAmountInputToken, _amountSetToken); return amountEthReturn; } /** * Issues an exact amount of SetTokens using a given amount of ether. * The excess ether is returned back. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromETH( ISetToken _setToken, uint256 _amountSetToken ) isSetToken(_setToken) external payable nonReentrant returns (uint256) { require(msg.value > 0 && _amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 amountEth = _issueExactSetFromWETH(_setToken, _amountSetToken, msg.value); uint256 amountEthReturn = msg.value.sub(amountEth); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), amountEth, _amountSetToken); return amountEthReturn; } /** * Redeems an exact amount of SetTokens for an ERC20 token. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being redeemed * @param _outputToken Address of output token * @param _amountSetToken Amount SetTokens to redeem * @param _minOutputReceive Minimum amount of output token to receive * * @return outputAmount Amount of output tokens sent to the caller */ function redeemExactSetForToken( ISetToken _setToken, IERC20 _outputToken, uint256 _amountSetToken, uint256 _minOutputReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); uint256 outputAmount; if (address(_outputToken) == WETH) { require(totalEth > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); outputAmount = _liquidateComponentsForWETH(components, amountComponents, exchanges); } else { (uint256 totalOutput, Exchange outTokenExchange, ) = _getMaxTokenForExactToken(totalEth, address(WETH), address(_outputToken)); require(totalOutput > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 outputEth = _liquidateComponentsForWETH(components, amountComponents, exchanges); outputAmount = _swapExactTokensForTokens(outTokenExchange, WETH, address(_outputToken), outputEth); } _outputToken.safeTransfer(msg.sender, outputAmount); emit ExchangeRedeem(msg.sender, _setToken, _outputToken, _amountSetToken, outputAmount); return outputAmount; } /** * Redeems an exact amount of SetTokens for ETH. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken to be redeemed * @param _amountSetToken Amount of SetTokens to redeem * @param _minEthOut Minimum amount of ETH to receive * * @return amountEthOut Amount of ether sent to the caller */ function redeemExactSetForETH( ISetToken _setToken, uint256 _amountSetToken, uint256 _minEthOut ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); require(totalEth > _minEthOut, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 amountEthOut = _liquidateComponentsForWETH(components, amountComponents, exchanges); IWETH(WETH).withdraw(amountEthOut); (payable(msg.sender)).sendValue(amountEthOut); emit ExchangeRedeem(msg.sender, _setToken, IERC20(ETH_ADDRESS), _amountSetToken, amountEthOut); return amountEthOut; } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken being issued * @param _amountInput Amount of the input token to spend * @param _inputToken Address of input token. * * @return Estimated amount of SetTokens that will be received */ function getEstimatedIssueSetAmount( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput ) isSetToken(_setToken) external view returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); uint256 amountEth; if (address(_inputToken) != WETH) { // get max amount of WETH for the `_amountInput` amount of input tokens (amountEth, , ) = _getMaxTokenForExactToken(_amountInput, address(_inputToken), WETH); } else { amountEth = _amountInput; } address[] memory components = _setToken.getComponents(); (uint256 setIssueAmount, , ) = _getSetIssueAmountForETH(_setToken, components, amountEth); return setIssueAmount; } /** * Returns the amount of input ERC20 tokens required to issue an exact amount of SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return Amount of tokens needed to issue specified amount of SetTokens */ function getAmountInToIssueExactSet( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns(uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , , , ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); if (address(_inputToken) == WETH) { return totalEth; } (uint256 tokenAmount, , ) = _getMinTokenForExactToken(totalEth, address(_inputToken), address(WETH)); return tokenAmount; } /** * Returns amount of output ERC20 tokens received upon redeeming a given amount of SetToken. * * @param _setToken Address of SetToken to be redeemed * @param _amountSetToken Amount of SetToken to be redeemed * @param _outputToken Address of output token * * @return Estimated amount of ether/erc20 that will be received */ function getAmountOutOnRedeemSet( ISetToken _setToken, address _outputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); if (_outputToken == WETH) { return totalEth; } // get maximum amount of tokens for totalEth amount of ETH (uint256 tokenAmount, , ) = _getMaxTokenForExactToken(totalEth, WETH, _outputToken); return tokenAmount; } /* ============ Internal Functions ============ */ /** * Sets a max approval limit for an ERC20 token, provided the current allowance * is less than the required allownce. * * @param _token Token to approve * @param _spender Spender address to approve */ function _safeApprove(IERC20 _token, address _spender, uint256 _requiredAllowance) internal { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _requiredAllowance) { _token.safeIncreaseAllowance(_spender, MAX_UINT96 - allowance); } } /** * Issues SetTokens for an exact amount of input WETH. * * @param _setToken Address of the SetToken being issued * @param _minSetReceive Minimum amount of index to receive * @param _totalEthAmount Total amount of WETH to be used to purchase the SetToken components * * @return setTokenAmount Amount of SetTokens issued */ function _issueSetForExactWETH(ISetToken _setToken, uint256 _minSetReceive, uint256 _totalEthAmount) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges ) = _getSetIssueAmountForETH(_setToken, components, _totalEthAmount); require(setIssueAmount > _minSetReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); for (uint256 i = 0; i < components.length; i++) { _swapExactTokensForTokens(exchanges[i], WETH, components[i], amountEthIn[i]); } basicIssuanceModule.issue(_setToken, setIssueAmount, msg.sender); return setIssueAmount; } /** * Issues an exact amount of SetTokens using WETH. * Acquires SetToken components at the best price accross uniswap and sushiswap. * Uses the acquired components to issue the SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to be issued * @param _maxEther Max amount of ether that can be used to acquire the SetToken components * * @return totalEth Total amount of ether used to acquire the SetToken components */ function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[] memory amountComponents, ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); require(sumEth <= _maxEther, "ExchangeIssuance: INSUFFICIENT_INPUT_AMOUNT"); uint256 totalEth = 0; for (uint256 i = 0; i < components.length; i++) { uint256 amountEth = _swapTokensForExactTokens(exchanges[i], WETH, components[i], amountComponents[i]); totalEth = totalEth.add(amountEth); } basicIssuanceModule.issue(_setToken, _amountSetToken, msg.sender); return totalEth; } /** * Redeems a given amount of SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _amount Amount of SetToken to be redeemed */ function _redeemExactSet(ISetToken _setToken, uint256 _amount) internal returns (uint256) { _setToken.safeTransferFrom(msg.sender, address(this), _amount); basicIssuanceModule.redeem(_setToken, _amount, address(this)); } /** * Liquidates a given list of SetToken components for WETH. * * @param _components An array containing the address of SetToken components * @param _amountComponents An array containing the amount of each SetToken component * @param _exchanges An array containing the exchange on which to liquidate the SetToken component * * @return Total amount of WETH received after liquidating all SetToken components */ function _liquidateComponentsForWETH(address[] memory _components, uint256[] memory _amountComponents, Exchange[] memory _exchanges) internal returns (uint256) { uint256 sumEth = 0; for (uint256 i = 0; i < _components.length; i++) { sumEth = _exchanges[i] == Exchange.None ? sumEth.add(_amountComponents[i]) : sumEth.add(_swapExactTokensForTokens(_exchanges[i], _components[i], WETH, _amountComponents[i])); } return sumEth; } /** * Gets the total amount of ether required for purchasing each component in a SetToken, * to enable the issuance of a given amount of SetTokens. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be issued * * @return sumEth The total amount of Ether reuired to issue the set * @return amountEthIn An array containing the amount of ether to purchase each component of the SetToken * @return exchanges An array containing the exchange on which to perform the purchase * @return amountComponents An array containing the amount of each SetToken component required for issuing the given * amount of SetToken * @return pairAddresses An array containing the pair addresses of ETH/component exchange pool */ function _getAmountETHForIssuance(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns ( uint256 sumEth, uint256[] memory amountEthIn, Exchange[] memory exchanges, uint256[] memory amountComponents, address[] memory pairAddresses ) { sumEth = 0; amountEthIn = new uint256[](_components.length); amountComponents = new uint256[](_components.length); exchanges = new Exchange[](_components.length); pairAddresses = new address[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); // Get minimum amount of ETH to be spent to acquire the required amount of SetToken component uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = uint256(unit).preciseMulCeil(_amountSetToken); (amountEthIn[i], exchanges[i], pairAddresses[i]) = _getMinTokenForExactToken(amountComponents[i], WETH, _components[i]); sumEth = sumEth.add(amountEthIn[i]); } return (sumEth, amountEthIn, exchanges, amountComponents, pairAddresses); } /** * Gets the total amount of ether returned from liquidating each component in a SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be redeemed * * @return sumEth The total amount of Ether that would be obtained from liquidating the SetTokens * @return amountComponents An array containing the amount of SetToken component to be liquidated * @return exchanges An array containing the exchange on which to liquidate the SetToken components */ function _getAmountETHForRedemption(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns (uint256, uint256[] memory, Exchange[] memory) { uint256 sumEth = 0; uint256 amountEth = 0; uint256[] memory amountComponents = new uint256[](_components.length); Exchange[] memory exchanges = new Exchange[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = unit.preciseMul(_amountSetToken); // get maximum amount of ETH received for a given amount of SetToken component (amountEth, exchanges[i], ) = _getMaxTokenForExactToken(amountComponents[i], _components[i], WETH); sumEth = sumEth.add(amountEth); } return (sumEth, amountComponents, exchanges); } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountEth Total amount of ether available for the purchase of SetToken components * * @return setIssueAmount The max amount of SetTokens that can be issued * @return amountEthIn An array containing the amount ether required to purchase each SetToken component * @return exchanges An array containing the exchange on which to purchase the SetToken components */ function _getSetIssueAmountForETH(ISetToken _setToken, address[] memory _components, uint256 _amountEth) internal view returns (uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges) { uint256 sumEth; uint256[] memory unitAmountEthIn; uint256[] memory unitAmountComponents; address[] memory pairAddresses; ( sumEth, unitAmountEthIn, exchanges, unitAmountComponents, pairAddresses ) = _getAmountETHForIssuance(_setToken, _components, PreciseUnitMath.preciseUnit()); setIssueAmount = PreciseUnitMath.maxUint256(); amountEthIn = new uint256[](_components.length); for (uint256 i = 0; i < _components.length; i++) { amountEthIn[i] = unitAmountEthIn[i].mul(_amountEth).div(sumEth); uint256 amountComponent; if (exchanges[i] == Exchange.None) { amountComponent = amountEthIn[i]; } else { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(pairAddresses[i], WETH, _components[i]); amountComponent = UniSushiV2Library.getAmountOut(amountEthIn[i], reserveIn, reserveOut); } setIssueAmount = Math.min(amountComponent.preciseDiv(unitAmountComponents[i]), setIssueAmount); } return (setIssueAmount, amountEthIn, exchanges); } /** * Swaps a given amount of an ERC20 token for WETH for the best price on Uniswap/Sushiswap. * * @param _token Address of the ERC20 token to be swapped for WETH * @param _amount Amount of ERC20 token to be swapped * * @return Amount of WETH received after the swap */ function _swapTokenForWETH(IERC20 _token, uint256 _amount) internal returns (uint256) { (, Exchange exchange, ) = _getMaxTokenForExactToken(_amount, address(_token), WETH); IUniswapV2Router02 router = _getRouter(exchange); _safeApprove(_token, address(router), _amount); return _swapExactTokensForTokens(exchange, address(_token), WETH, _amount); } /** * Swap exact tokens for another token on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountIn The amount of input token to be spent * * @return The amount of output tokens */ function _swapExactTokensForTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountIn) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountIn; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapExactTokensForTokens(_amountIn, 0, path, address(this), block.timestamp)[1]; } /** * Swap tokens for exact amount of output tokens on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountOut The amount of output token required * * @return The amount of input tokens spent */ function _swapTokensForExactTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountOut) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountOut; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapTokensForExactTokens(_amountOut, PreciseUnitMath.maxUint256(), path, address(this), block.timestamp)[0]; } /** * Compares the amount of token required for an exact amount of another token across both exchanges, * and returns the min amount. * * @param _amountOut The amount of output token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The min amount of tokenA required across both exchanges * @return The Exchange on which minimum amount of tokenA is required * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMinTokenForExactToken(uint256 _amountOut, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountOut, Exchange.None, ETH_ADDRESS); } uint256 maxIn = PreciseUnitMath.maxUint256() ; uint256 uniTokenIn = maxIn; uint256 sushiTokenIn = maxIn; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if (uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { uniTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if (sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { sushiTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } // Fails if both the values are maxIn require(!(uniTokenIn == maxIn && sushiTokenIn == maxIn), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenIn <= sushiTokenIn) ? (uniTokenIn, Exchange.Uniswap, uniswapPair) : (sushiTokenIn, Exchange.Sushiswap, sushiswapPair); } /** * Compares the amount of token received for an exact amount of another token across both exchanges, * and returns the max amount. * * @param _amountIn The amount of input token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The max amount of tokens that can be received across both exchanges * @return The Exchange on which maximum amount of token can be received * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMaxTokenForExactToken(uint256 _amountIn, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountIn, Exchange.None, ETH_ADDRESS); } uint256 uniTokenOut = 0; uint256 sushiTokenOut = 0; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if(uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); uniTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if(sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); sushiTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } // Fails if both the values are 0 require(!(uniTokenOut == 0 && sushiTokenOut == 0), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenOut >= sushiTokenOut) ? (uniTokenOut, Exchange.Uniswap, uniswapPair) : (sushiTokenOut, Exchange.Sushiswap, sushiswapPair); } /** * Returns the pair address for on a given DEX. * * @param _factory The factory to address * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The pair address (Note: address(0) is returned by default if the pair is not available on that DEX) */ function _getPair(address _factory, address _tokenA, address _tokenB) internal view returns (address) { return IUniswapV2Factory(_factory).getPair(_tokenA, _tokenB); } /** * Returns the router address of a given exchange. * * @param _exchange The Exchange whose router address is needed * * @return IUniswapV2Router02 router of the given exchange */ function _getRouter(Exchange _exchange) internal view returns(IUniswapV2Router02) { return (_exchange == Exchange.Uniswap) ? uniRouter : sushiRouter; } }
Runs all the necessary approval functions required for a list of ERC20 tokens. _tokens Addresses of the tokens which need approval/
function approveTokens(IERC20[] calldata _tokens) external { for (uint256 i = 0; i < _tokens.length; i++) { approveToken(_tokens[i]); } }
2,571,863
//pragma solidity ^0.5.2; pragma solidity >=0.4.22 <0.6.0; /** * @title IERC165 * @dev https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /// @title Shared constants used throughout the Cheeze Wizards contracts contract WizardConstants { // Wizards normally have their affinity set when they are first created, // but for example Exclusive Wizards can be created with no set affinity. // In this case the affinity can be set by the owner. uint8 internal constant ELEMENT_NOTSET = 0; //000 // A neutral Wizard has no particular strength or weakness with specific // elements. uint8 internal constant ELEMENT_NEUTRAL = 1; //001 // The fire, water and wind elements are used both to reflect an affinity // of Elemental Wizards for a specific element, and as the moves a // Wizard can make during a duel. // Note thta if these values change then `moveMask` and `moveDelta` in // ThreeAffinityDuelResolver would need to be updated accordingly. uint8 internal constant ELEMENT_FIRE = 2; //010 uint8 internal constant ELEMENT_WATER = 3; //011 uint8 internal constant ELEMENT_WIND = 4; //100 uint8 internal constant MAX_ELEMENT = ELEMENT_WIND; } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 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 getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } /** * @title ERC165 * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /* * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } /// Utility library of inline functions on address payables. /// Modified from original by OpenZeppelin. contract Address { /// @notice Returns whether the target address is a contract. /// @dev This function will return false if invoked during the constructor of a contract, /// as the code is not actually created until after the constructor finishes. /// @param account address of the account to check /// @return whether the target address is a contract function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } // solium-disable-line security/no-inline-assembly return size > 0; } } /** * @title WizardPresaleNFT * @notice The basic ERC-721 functionality for storing the presale Wizard NFTs. * Derived from: https://github.com/OpenZeppelin/openzeppelin-solidity/tree/v2.2.0 */ contract WizardPresaleNFT is ERC165, IERC721, Address { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// @notice Emitted when a wizard token is created. event WizardSummoned(uint256 indexed tokenId, uint8 element, uint256 power); /// @notice Emitted when a wizard change element. Should only happen once and for wizards /// that previously had the element undefined. event WizardAlignmentAssigned(uint256 indexed tokenId, uint8 element); // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02; /// @dev The presale Wizard structure. /// Fits in one word struct Wizard { // NOTE: Changing the order or meaning of any of these fields requires an update // to the _createWizard() function which assumes a specific order for these fields. uint8 affinity; uint88 power; address owner; } // Mapping from Wizard ID to Wizard struct mapping (uint256 => Wizard) public _wizardsById; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner]; } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _wizardsById[tokenId].owner; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { 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" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _wizardsById[tokenId].owner; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner]--; // delete the entire object to recover the most gas delete _wizardsById[tokenId]; // required for ERC721 compatibility emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from]--; _ownedTokensCount[to]++; _wizardsById[tokenId].owner = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `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) internal returns (bool) { if (!isContract(to)) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } /// @title WizardPresaleInterface /// @notice This interface represents the single method that the final tournament and master Wizard contracts /// will use to import the presale wizards when those contracts have been finalized a released on /// mainnet. Once all presale Wizards have been absorbed, this temporary pre-sale contract can be /// destroyed. contract WizardPresaleInterface { // See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md on how // to calculate this bytes4 public constant _INTERFACE_ID_WIZARDPRESALE = 0x4df71efb; /// @notice This function is used to bring a presale Wizard into the final contracts. It can /// ONLY be called by the official gatekeeper contract (as set by the Owner of the presale /// contract). It does a number of things: /// 1. Check that the presale Wizard exists, and has not already been absorbed /// 2. Transfer the Eth used to create the presale Wizard to the caller /// 3. Mark the Wizard as having been absorbed, reclaiming the storage used by the presale info /// 4. Return the Wizard information (its owner, minting price, and elemental alignment) /// @param id the id of the presale Wizard to be absorbed function absorbWizard(uint256 id) external returns (address owner, uint256 power, uint8 affinity); /// @notice A convenience function that allows multiple Wizards to be moved to the final contracts /// simultaneously, works the same as the previous function, but in a batch. /// @param ids An array of ids indicating which presale Wizards are to be absorbed function absorbWizardMulti(uint256[] calldata ids) external returns (address[] memory owners, uint256[] memory powers, uint8[] memory affinities); function powerToCost(uint256 power) public pure returns (uint256 cost); function costToPower(uint256 cost) public pure returns (uint256 power); } /// @title WizardPresale - Making Cheeze Wizards available for sale! /// @notice Allows for the creation and sale of Cheeze Wizards before the final tournament /// contract has been reviewed and released on mainnet. There are three main types /// of Wizards that are managed by this contract: /// - Neutral Wizards: Available in unlimited quantities and all have the same /// innate power. Don't have a natural affinity for any particular elemental /// spell... or the corresponding weakness! /// - Elemental Wizards: Available in unlimited quantities, but with a steadily increasing /// power; the power of an Elemental Wizard is always _slightly_ higher than the power /// of the previously created Elemental Wizard. Each Elemental Wizard has an Elemental /// Affinity that gives it a power multiplier when using the associated spell, but also /// gives it a weakness for the opposing element. /// - Exclusive Wizards: Only available in VERY limited quantities, with a hard cap set at /// contract creation time. Exclusive Wizards can ONLY be created by the Guild Master /// address (the address that created this contract), and are assigned the first N /// Wizard IDs, starting with 1 (where N is the hard cap on Exclusive Wizards). The first /// non-exclusive Wizard is assigned the ID N+1. Exclusive Wizards have no starting /// affinity, and their owners much choose an affinity before they can be entered into a /// Battle. The affinity CAN NOT CHANGE once it has been selected. The power of Exclusive /// Wizards is not set by the Guild Master and is not required to follow any pattern (although /// it can't be lower than the power of Neutral Wizards). contract WizardPresale is WizardPresaleNFT, WizardPresaleInterface, WizardConstants { /// @dev The ratio between the cost of a Wizard (in wei) and the power of the wizard. /// power = cost / POWER_SCALE /// cost = power * POWER_SCALE uint256 private constant POWER_SCALE = 1000; /// @dev The unit conversion for tenths of basis points uint256 private constant TENTH_BASIS_POINTS = 100000; /// @dev The address used to create this smart contract, has permission to conjure Exclusive Wizards, /// set the gatekeeper address, and destroy this contract once the sale is finished and all Presale /// Wizards have been absorbed into the main contracts. address payable public guildmaster; /// @dev The start block and duration (in blocks) of the sale. /// ACT NOW! For a limited time only! uint256 public saleStartBlock; uint256 public saleDuration; /// @dev The cost of Neutral Wizards (in wei). uint256 public neutralWizardCost; /// @dev The cost of the _next_ Elemental Wizard (in wei); increases with each Elemental Wizard sold uint256 public elementalWizardCost; /// @dev The increment ratio in price between sequential Elemental Wizards, multiplied by 100k for /// greater granularity (0 == 0% increase, 100000 == 100% increase, 100 = 0.1% increase, etc.) /// NOTE: This is NOT percentage points, or basis points. It's tenths of a basis point. uint256 public elementalWizardIncrement; /// @dev The hard cap on how many Exclusive Wizards can be created uint256 public maxExclusives; /// @dev The ID number of the next Wizard to be created (Neutral or Elemental) uint256 public nextWizardId; /// @dev The address of the Gatekeeper for the tournament, initially set to address(0). /// To be set by the Guild Master when the final Tournament Contract is deployed on mainnet address payable public gatekeeper; /// @notice Emitted whenever the start of the sale changes. event StartBlockChanged(uint256 oldStartBlock, uint256 newStartBlock); /// @param startingCost The minimum cost of a Wizard, used as the price for all Neutral Wizards, and the /// cost of the first Elemental Wizard. Also used as a minimum value for Exclusive Wizards. /// @param costIncremement The rate (in tenths of a basis point) at which the price of Elemental Wizards increases /// @param exclusiveCount The hard cap on Exclusive Wizards, also dictates the ID of the first non-Exclusive /// @param startBlock The starting block of the presale. /// @param duration The duration of the presale. Not changeable! constructor(uint128 startingCost, uint16 costIncremement, uint256 exclusiveCount, uint128 startBlock, uint128 duration) public { require(startBlock > block.number, "Start must be greater than current block"); guildmaster = msg.sender; saleStartBlock = startBlock; saleDuration = duration; neutralWizardCost = startingCost; elementalWizardCost = startingCost; elementalWizardIncrement = costIncremement; maxExclusives = exclusiveCount; nextWizardId = exclusiveCount + 1; _registerInterface(_INTERFACE_ID_WIZARDPRESALE); } /// @dev Throws if called by any account other than the gatekeeper. modifier onlyGatekeeper() { require(msg.sender == gatekeeper, "Must be gatekeeper"); _; } /// @dev Throws if called by any account other than the guildmaster. modifier onlyGuildmaster() { require(msg.sender == guildmaster, "Must be guildmaster"); _; } /// @dev Checks to see that the current block number is within the range /// [saleStartBlock, saleStartBlock + saleDuraction) indicating that the sale /// is currently active modifier onlyDuringSale() { // The addtion of start and duration can't overflow since they can only be set from // 128-bit arguments. require(block.number >= saleStartBlock, "Sale not open yet"); require(block.number < saleStartBlock + saleDuration, "Sale closed"); _; } /// @dev Sets the address of the Gatekeeper contract once the final Tournament contract is live. /// Can only be set once. /// @param gc The gatekeeper address to set function setGatekeeper(address payable gc) external onlyGuildmaster { require(gatekeeper == address(0) && gc != address(0), "Can only set once and must not be 0"); gatekeeper = gc; } /// @dev Updates the start block of the sale. The sale can only be postponed; it can't be made earlier. /// @param newStart the new start block. function postponeSale(uint128 newStart) external onlyGuildmaster { require(block.number < saleStartBlock, "Sale start time only adjustable before previous start time"); require(newStart > saleStartBlock, "New start time must be later than previous start time"); emit StartBlockChanged(saleStartBlock, newStart); saleStartBlock = newStart; } /// @dev Returns true iff the sale is currently active function isDuringSale() external view returns (bool) { return (block.number >= saleStartBlock && block.number < saleStartBlock + saleDuration); } /// @dev Convenience method for getting a presale wizard's data /// @param id The wizard id function getWizard(uint256 id) public view returns (address owner, uint88 power, uint8 affinity) { Wizard memory wizard = _wizardsById[id]; (owner, power, affinity) = (wizard.owner, wizard.power, wizard.affinity); require(wizard.owner != address(0), "Wizard does not exist"); } /// @param cost The price of the wizard in wei /// @return The power of the wizard (left as uint256) function costToPower(uint256 cost) public pure returns (uint256 power) { return cost / POWER_SCALE; } /// @param power The power of the wizard /// @return The cost of the wizard in wei function powerToCost(uint256 power) public pure returns (uint256 cost) { return power * POWER_SCALE; } /// @notice This function is used to bring a presale Wizard into the final contracts. It can /// ONLY be called by the official gatekeeper contract (as set by the Owner of the presale /// contract). It does a number of things: /// 1. Check that the presale Wizard exists, and has not already been absorbed /// 2. Transfer the Eth used to create the presale Wizard to the caller /// 3. Mark the Wizard as having been absorbed, reclaiming the storage used by the presale info /// 4. Return the Wizard information (its owner, minting price, and elemental alignment) /// @param id the id of the presale Wizard to be absorbed function absorbWizard(uint256 id) external onlyGatekeeper returns (address owner, uint256 power, uint8 affinity) { (owner, power, affinity) = getWizard(id); // Free up the storage used by this wizard _burn(owner, id); // send the price paid to the gatekeeper to be used in the tournament prize pool msg.sender.transfer(powerToCost(power)); } /// @notice A convenience function that allows multiple Wizards to be moved to the final contracts /// simultaneously, works the same as the previous function, but in a batch. /// @param ids An array of ids indicating which presale Wizards are to be absorbed function absorbWizardMulti(uint256[] calldata ids) external onlyGatekeeper returns (address[] memory owners, uint256[] memory powers, uint8[] memory affinities) { // allocate arrays owners = new address[](ids.length); powers = new uint256[](ids.length); affinities = new uint8[](ids.length); // The total eth to send (sent in a batch to save gas) uint256 totalTransfer; // Put the data for each Wizard into the returned arrays for (uint256 i = 0; i < ids.length; i++) { (owners[i], powers[i], affinities[i]) = getWizard(ids[i]); // Free up the storage used by this wizard _burn(owners[i], ids[i]); // add the amount to transfer totalTransfer += powerToCost(powers[i]); } // Send all the eth together msg.sender.transfer(totalTransfer); } /// @dev Internal function to create a new Wizard; reverts if the Wizard ID is taken. /// NOTE: This function heavily depends on the internal format of the Wizard struct /// and should always be reassessed if anything about that structure changes. /// @param tokenId ID of the new Wizard /// @param owner The address that will own the newly conjured Wizard /// @param power The power level associated with the new Wizard /// @param affinity The elemental affinity of the new Wizard function _createWizard(uint256 tokenId, address owner, uint256 power, uint8 affinity) internal { require(!_exists(tokenId), "Can't reuse Wizard ID"); require(owner != address(0), "Owner address must exist"); require(power > 0, "Wizard power must be non-0"); require(power < (1<<88), "Wizard power must fit in 88 bits of storage"); require(affinity <= MAX_ELEMENT, "Invalid elemental affinity"); // Create the Wizard! _wizardsById[tokenId] = Wizard(affinity, uint88(power), owner); _ownedTokensCount[owner]++; // Tell the world! emit Transfer(address(0), owner, tokenId); emit WizardSummoned(tokenId, affinity, power); } /// @dev A private utility function that refunds any overpayment to the sender; smart /// enough to only send the excess if the amount we are returning is more than the /// cost of sending it! /// @dev Warning! This does not check for underflows (msg.value < actualPrice) - so /// be sure to call this with correct values! /// @param actualPrice the actual price owed function _transferRefund(uint256 actualPrice) private { uint256 refund = msg.value - actualPrice; // Make sure the amount we're trying to refund is less than the actual cost of sending it! // See https://github.com/ethereum/wiki/wiki/Subtleties for magic values costs. We can // safley ignore the 25000 additional gas cost for new accounts, as msg.sender is // guarunteed to exist at this point! if (refund > (tx.gasprice * (9000+700))) { msg.sender.transfer(refund); } } /// @notice Conjures an Exclusive Wizard with a specific element and ID. This can only be done by /// the Guildmaster, who still has to pay for the power imbued in that Wizard! The power level /// is inferred by the amount of Eth sent. MUST ONLY BE USED FOR EXTERNAL OWNER ADDRESSES. /// @param id The ID of the new Wizard; must be in the Exclusive range, and can't already be allocated /// @param owner The address which will own the new Wizard /// @param affinity The elemental affinity of the new Wizard, can be ELEMENT_NOTSET for Exclusives! function conjureExclusiveWizard(uint256 id, address owner, uint8 affinity) public payable onlyGuildmaster { require(id > 0 && id <= maxExclusives, "Invalid exclusive ID"); _createWizard(id, owner, costToPower(msg.value), affinity); } /// @notice Same as conjureExclusiveWizard(), but reverts if the owner address is a smart /// contract that is not ERC-721 aware. /// @param id The ID of the new Wizard; must be in the Exclusive range, and can't already be allocated /// @param owner The address which will own the new Wizard /// @param affinity The elemental affinity of the new Wizard, can be ELEMENT_NOTSET for Exclusives! function safeConjureExclusiveWizard(uint256 id, address owner, uint8 affinity) external payable onlyGuildmaster { conjureExclusiveWizard(id, owner, affinity); require(_checkOnERC721Received(address(0), owner, id, ""), "Must support erc721"); } /// @notice Allows for the batch creation of Exclusive Wizards. Same rules apply as above, but the /// powers are specified instead of being inferred. The message still needs to have enough /// value to pay for all the newly conjured Wizards! MUST ONLY BE USED FOR EXTERNAL OWNER ADDRESSES. /// @param ids An array of IDs of the new Wizards /// @param owners An array of owners /// @param powers An array of power levels /// @param affinities An array of elemental affinities function conjureExclusiveWizardMulti( uint256[] calldata ids, address[] calldata owners, uint256[] calldata powers, uint8[] calldata affinities) external payable onlyGuildmaster { // Ensure the arrays are all of the same length require( ids.length == owners.length && owners.length == powers.length && owners.length == affinities.length, "Must have equal array lengths" ); uint256 totalPower = 0; for (uint256 i = 0; i < ids.length; i++) { require(ids[i] > 0 && ids[i] <= maxExclusives, "Invalid exclusive ID"); require(affinities[i] <= MAX_ELEMENT, "Must choose a valid elemental affinity"); _createWizard(ids[i], owners[i], powers[i], affinities[i]); totalPower += powers[i]; } // Ensure that the message includes enough eth to cover the total power of all Wizards // If this check fails, all the Wizards that we just created will be deleted, and we'll just // have wasted a bunch of gas. Don't be dumb, Guildmaster! // If the guildMaster has managed to overflow totalPower, well done! require(powerToCost(totalPower) <= msg.value, "Must pay for power in all Wizards"); // We don't return "change" if the caller overpays, because the caller is the Guildmaster and // shouldn't be dumb like that. How many times do I have to say it? Don't be dumb, Guildmaster! } /// @notice Sets the affinity for a Wizard that doesn't already have its elemental affinity chosen. /// Only usable for Exclusive Wizards (all non-Exclusives must have their affinity chosen when /// conjured.) Even Exclusives can't change their affinity once it's been chosen. /// @param wizardId The id of the wizard /// @param newAffinity The new affinity of the wizard function setAffinity(uint256 wizardId, uint8 newAffinity) external { require(newAffinity > ELEMENT_NOTSET && newAffinity <= MAX_ELEMENT, "Must choose a valid affinity"); (address owner, , uint8 affinity) = getWizard(wizardId); require(msg.sender == owner, "Affinity can only be set by owner"); require(affinity == ELEMENT_NOTSET, "Affinity can only be chosen once"); _wizardsById[wizardId].affinity = newAffinity; // Tell the world this wizards now has an affinity! emit WizardAlignmentAssigned(wizardId, newAffinity); } /// @dev An internal convenience function used by conjureWizard and conjureWizardMulti that takes care /// of the work that is shared between them. /// The use of tempElementalWizardCost and updatedElementalWizardCost deserves some explanation here. /// Using elementalWizardCost directly would be very expensive in the case where this function is /// called repeatedly by conjureWizardMulti. Buying an elemental wizard would update the elementalWizardCost /// each time through this function _which would cost 5000 gas each time_. Of course, we don't actually /// need to store the new value each time, only once at the very end. So we go through this very annoying /// process of passing the elementalWizardCost in as an argument (tempElementalWizardCost) and returning /// the updated value as a return value (updatedElementalWizardCost). It's enough to make one want /// tear one's hair out. But! What's done is done, and hopefully SOMEONE will realize how much trouble /// we went to to save them _just that little bit_ of gas cost when they decided to buy a schwack of /// Wizards. function _conjureWizard( uint256 wizardId, address owner, uint8 affinity, uint256 tempElementalWizardCost) private returns (uint256 wizardCost, uint256 updatedElementalWizardCost) { // Check for a valid elemental affinity require(affinity > ELEMENT_NOTSET && affinity <= MAX_ELEMENT, "Non-exclusive Wizards need a real affinity"); updatedElementalWizardCost = tempElementalWizardCost; // Determine the price if (affinity == ELEMENT_NEUTRAL) { wizardCost = neutralWizardCost; } else { wizardCost = updatedElementalWizardCost; // Update the elemental Wizard cost // NOTE: This math can't overflow because the total Ether supply in wei is well less than // 2^128. Multiplying a price in wei by some number <100k can't possibly overflow 256 bits. updatedElementalWizardCost += (updatedElementalWizardCost * elementalWizardIncrement) / TENTH_BASIS_POINTS; } // Bring the new Wizard into existence! _createWizard(wizardId, owner, costToPower(wizardCost), affinity); } /// @notice This is it folks, the main event! The way for the world to get new Wizards! Does /// pretty much what it says on the box: Let's you conjure a new Wizard with a specified /// elemental affinity. The call must include enough eth to cover the cost of the new /// Wizard, and any excess is refunded. The power of the Wizard is derived from /// the sale price. YOU CAN NOT PAY EXTRA TO GET MORE POWER. (But you always have the option /// to conjure some more Wizards!) Returns the ID of the newly conjured Wizard. /// @param affinity The elemental affinity you want for your wizard. function conjureWizard(uint8 affinity) external payable onlyDuringSale returns (uint256 wizardId) { wizardId = nextWizardId; nextWizardId++; uint256 wizardCost; (wizardCost, elementalWizardCost) = _conjureWizard(wizardId, msg.sender, affinity, elementalWizardCost); require(msg.value >= wizardCost, "Not enough eth to pay"); // Refund any overpayment _transferRefund(wizardCost); // Ensure the Wizard is being assigned to an ERC-721 aware address (either an external address, // or a smart contract that implements onERC721Reived()) require(_checkOnERC721Received(address(0), msg.sender, wizardId, ""), "Must support erc721"); } /// @notice A convenience function that allows you to get a whole bunch of Wizards at once! You know how /// there's "a pride of lions", "a murder of crows", and "a parliament of owls"? Well, with this /// here function you can conjure yourself "a stench of Cheeze Wizards"! /// @dev This function is careful to bundle all of the external calls (the refund and onERC721Received) /// at the end of the function to limit the risk of reentrancy attacks. /// @param affinities the elements of the wizards function conjureWizardMulti(uint8[] calldata affinities) external payable onlyDuringSale returns (uint256[] memory wizardIds) { // allocate result array wizardIds = new uint256[](affinities.length); uint256 totalCost = 0; // We take these two storage variables, and turn them into local variables for the course // of this loop to save about 10k gas per wizard. It's kind of ugly, but that's a lot of // gas! Won't somebody please think of the children!! uint256 tempWizardId = nextWizardId; uint256 tempElementalWizardCost = elementalWizardCost; for (uint256 i = 0; i < affinities.length; i++) { wizardIds[i] = tempWizardId; tempWizardId++; uint256 wizardCost; (wizardCost, tempElementalWizardCost) = _conjureWizard( wizardIds[i], msg.sender, affinities[i], tempElementalWizardCost); totalCost += wizardCost; } elementalWizardCost = tempElementalWizardCost; nextWizardId = tempWizardId; // check to see if there's enough eth require(msg.value >= totalCost, "Not enough eth to pay"); // Ensure the Wizard is being assigned to an ERC-721 aware address (either an external address, // or a smart contract that implements onERC721Received()). We unwind the logic of _checkOnERC721Received // because called address.isContract() every time through this loop can get reasonably expensive. We do // need to call this function for each token created, however, because it's allowed for an ERC-721 receiving // contract to reject the transfer based on the properties of the token. if (isContract(msg.sender)) { for (uint256 i = 0; i < wizardIds.length; i++) { bytes4 retval = IERC721Receiver(msg.sender).onERC721Received(msg.sender, address(0), wizardIds[i], ""); require(retval == _ERC721_RECEIVED, "Contract owner didn't accept ERC721 transfer"); } } // Refund any excess funds _transferRefund(totalCost); } /// @dev Transfers the current balance to the owner and terminates the contract. function destroy() external onlyGuildmaster { selfdestruct(guildmaster); } }
This is it folks, the main event! The way for the world to get new Wizards! Does pretty much what it says on the box: Let's you conjure a new Wizard with a specified elemental affinity. The call must include enough eth to cover the cost of the new Wizard, and any excess is refunded. The power of the Wizard is derived from the sale price. YOU CAN NOT PAY EXTRA TO GET MORE POWER. (But you always have the option to conjure some more Wizards!) Returns the ID of the newly conjured Wizard. affinity The elemental affinity you want for your wizard. Refund any overpayment Ensure the Wizard is being assigned to an ERC-721 aware address (either an external address, or a smart contract that implements onERC721Reived())
function conjureWizard(uint8 affinity) external payable onlyDuringSale returns (uint256 wizardId) { wizardId = nextWizardId; nextWizardId++; uint256 wizardCost; (wizardCost, elementalWizardCost) = _conjureWizard(wizardId, msg.sender, affinity, elementalWizardCost); require(msg.value >= wizardCost, "Not enough eth to pay"); _transferRefund(wizardCost); require(_checkOnERC721Received(address(0), msg.sender, wizardId, ""), "Must support erc721"); }
2,529,610