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.9; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/FeedRegistryInterface.sol"; import "@chainlink/contracts/src/v0.8/Denominations.sol"; import "./interfaces/IPaymentStreamFactory.sol"; import "./PaymentStream.sol"; contract PaymentStreamFactory is IPaymentStreamFactory, Ownable { string public constant VERSION = "1.0.2"; string public constant NAME = "PaymentStreamFactory"; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address[] private allStreams; mapping(address => bool) private isOurs; // Chainlink Feed Registry: https://docs.chain.link/docs/feed-registry/ // Aggregates all supported price feeds in one handy factory contract // Automatically supported TOKEN/USD and TOKEN/ETH pairs: https://docs.chain.link/docs/ethereum-addresses/ FeedRegistryInterface public feedRegistry; // Some tokens like ETH or BTC have special addresses in the feed registry // token address => token denomination in Feed Registry mapping(address => address) public customFeedMapping; constructor(address _feedRegistry) { feedRegistry = FeedRegistryInterface(_feedRegistry); customFeedMapping[WETH] = Denominations.ETH; } /** * @notice Creates a new payment stream * @dev Payer (_msgSender()) is set as admin of "pausableRole", so he can grant and revoke the "pausable" role later on * @param _payee address that receives the payment stream * @param _usdAmount uint256 total amount in USD (scaled to 18 decimals) to be distributed until endTime * @param _token address of the ERC20 token that payee receives as payment * @param _fundingAddress address used to withdraw the drip * @param _endTime timestamp that sets drip distribution end */ function createStream( address _payee, uint256 _usdAmount, address _token, address _fundingAddress, uint256 _endTime ) external returns (address streamAddress) { // Prevents the caller to create a Stream with an unsupported token // In case a USD/TOKEN or ETH/TOKEN Pair doesn't exist // This will revert with "Feed not found" usdToTokenAmount(_token, _usdAmount); streamAddress = address( new PaymentStream( _msgSender(), _payee, _usdAmount, _token, _fundingAddress, _endTime ) ); allStreams.push(streamAddress); isOurs[streamAddress] = true; emit StreamCreated( allStreams.length - 1, streamAddress, _msgSender(), _payee, _usdAmount ); } /** * @notice Updates Chainlink FeedRegistry contract address * @dev Only contract owner can change feedRegistry * @param _newAddress address of new Chainlink FeedRegistry instance */ function updateFeedRegistry(address _newAddress) external override onlyOwner { require(_newAddress != address(0), "invalid-feed-registry-address"); require(_newAddress != address(feedRegistry), "same-feed-registry-address"); emit FeedRegistryUpdated(address(feedRegistry), _newAddress); feedRegistry = FeedRegistryInterface(_newAddress); } /** * @notice Defines a custom mapping for token denominations in the Feed Registry * @param _token address of the ERC20 token * @param _denomination the denomination address that the feed registry uses for _token */ function updateCustomFeedMapping(address _token, address _denomination) external onlyOwner { require(_denomination != address(0), "invalid-custom-feed-map"); require(_denomination != customFeedMapping[_token], "same-custom-feed-map"); customFeedMapping[_token] = _denomination; emit CustomFeedMappingUpdated(_token, _denomination); } /** * @notice Converts given amount in usd to target token amount using oracle * @param _token address of target token * @param _amount amount in USD (scaled to 18 decimals) * @return lastPrice target token amount */ function usdToTokenAmount(address _token, uint256 _amount) public view override returns (uint256 lastPrice) { // tries a direct _token -> USD pair first try feedRegistry.getFeed(_tokenDenomination(_token), Denominations.USD) returns (AggregatorV2V3Interface) { uint256 _quote = _getQuote(_token, Denominations.USD); lastPrice = ((_amount * 1e18) / _quote) / 10**(18 - IERC20Metadata(_token).decimals()); } catch { // If getFeed reverts, uses token/ETH/usd route // If a feed doesn't exist for _token/ETH, it will revert with "Feed not found" uint256 _ethQuote = _getQuote(_token, Denominations.ETH); uint256 _ethUsdQuote = _getQuote(Denominations.ETH, Denominations.USD); uint256 _amountInETH = (_amount * 1e18) / _ethUsdQuote; lastPrice = ((_amountInETH * 1e18) / _ethQuote) / 10**(18 - IERC20Metadata(_token).decimals()); } } /** * @notice Checks if a address belongs to this contract' streams */ function ours(address _a) external view override returns (bool) { return isOurs[_a]; } /** * @notice Returns no. of streams stored in contract */ function getStreamsCount() external view override returns (uint256) { return allStreams.length; } /** * @notice Returns address of the stream located at given id */ function getStream(uint256 _idx) external view override returns (address) { return allStreams[_idx]; } function _getQuote(address _base, address _quote) internal view returns (uint256) { (, int256 _price, , , ) = feedRegistry.latestRoundData(_tokenDenomination(_base), _quote); // USD decimals is 8 in ChainLink, scales it up to 18 decimals _price = (_quote == Denominations.USD) ? _price * 1e10 : _price; return uint256(_price); } function _tokenDenomination(address _token) internal view returns (address) { return (customFeedMapping[_token] == address(0)) ? _token : customFeedMapping[_token]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./AggregatorV2V3Interface.sol"; interface FeedRegistryInterface { struct Phase { uint16 phaseId; uint80 startingAggregatorRoundId; uint80 endingAggregatorRoundId; } event FeedProposed( address indexed asset, address indexed denomination, address indexed proposedAggregator, address currentAggregator, address sender ); event FeedConfirmed( address indexed asset, address indexed denomination, address indexed latestAggregator, address previousAggregator, uint16 nextPhaseId, address sender ); // V3 AggregatorV3Interface function decimals( address base, address quote ) external view returns ( uint8 ); function description( address base, address quote ) external view returns ( string memory ); function version( address base, address quote ) external view returns ( uint256 ); function latestRoundData( address base, address quote ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getRoundData( address base, address quote, uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // V2 AggregatorInterface function latestAnswer( address base, address quote ) external view returns ( int256 answer ); function latestTimestamp( address base, address quote ) external view returns ( uint256 timestamp ); function latestRound( address base, address quote ) external view returns ( uint256 roundId ); function getAnswer( address base, address quote, uint256 roundId ) external view returns ( int256 answer ); function getTimestamp( address base, address quote, uint256 roundId ) external view returns ( uint256 timestamp ); // Registry getters function getFeed( address base, address quote ) external view returns ( AggregatorV2V3Interface aggregator ); function getPhaseFeed( address base, address quote, uint16 phaseId ) external view returns ( AggregatorV2V3Interface aggregator ); function isFeedEnabled( address aggregator ) external view returns ( bool ); function getPhase( address base, address quote, uint16 phaseId ) external view returns ( Phase memory phase ); // Round helpers function getRoundFeed( address base, address quote, uint80 roundId ) external view returns ( AggregatorV2V3Interface aggregator ); function getPhaseRange( address base, address quote, uint16 phaseId ) external view returns ( uint80 startingRoundId, uint80 endingRoundId ); function getPreviousRoundId( address base, address quote, uint80 roundId ) external view returns ( uint80 previousRoundId ); function getNextRoundId( address base, address quote, uint80 roundId ) external view returns ( uint80 nextRoundId ); // Feed management function proposeFeed( address base, address quote, address aggregator ) external; function confirmFeed( address base, address quote, address aggregator ) external; // Proposed aggregator function getProposedFeed( address base, address quote ) external view returns ( AggregatorV2V3Interface proposedAggregator ); function proposedGetRoundData( address base, address quote, uint80 roundId ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData( address base, address quote ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // Phases function getCurrentPhaseId( address base, address quote ) external view returns ( uint16 currentPhaseId ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Denominations { address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB; // Fiat currencies follow https://en.wikipedia.org/wiki/ISO_4217 address public constant USD = address(840); address public constant GBP = address(826); address public constant EUR = address(978); address public constant JPY = address(392); address public constant KRW = address(410); address public constant CNY = address(156); address public constant AUD = address(36); address public constant CAD = address(124); address public constant CHF = address(756); address public constant ARS = address(32); address public constant PHP = address(608); address public constant NZD = address(554); address public constant SGD = address(702); address public constant NGN = address(566); address public constant ZAR = address(710); address public constant RUB = address(643); address public constant INR = address(356); address public constant BRL = address(986); } //SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IPaymentStreamFactory { event StreamCreated( uint256 id, address indexed stream, address indexed payer, address indexed payee, uint256 usdAmount ); event CustomFeedMappingUpdated( address indexed token, address indexed tokenDenomination ); event FeedRegistryUpdated( address indexed previousFeedRegistry, address indexed newFeedRegistry ); function updateFeedRegistry(address newAddress) external; function usdToTokenAmount(address _token, uint256 _amount) external view returns (uint256); function ours(address _a) external view returns (bool); function getStreamsCount() external view returns (uint256); function getStream(uint256 _idx) external view returns (address); } //SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./interfaces/IPaymentStream.sol"; import "./interfaces/IPaymentStreamFactoryMetadata.sol"; contract PaymentStream is AccessControl, IPaymentStream { using SafeERC20 for IERC20; // solhint-disable var-name-mixedcase string public VERSION; // solhint-enable var-name-mixedcase string public constant NAME = "PaymentStream"; address public immutable payer; address public immutable token; address public payee; address public fundingAddress; uint256 public usdAmount; uint256 public startTime; uint256 public secs; uint256 public usdPerSec; uint256 public claimed; bool public paused; IPaymentStreamFactoryMetadata public immutable factory; bytes32 private constant ADMIN_ROLE = keccak256(abi.encodePacked("admin")); bytes32 private constant PAUSABLE_ROLE = keccak256(abi.encodePacked("pausable")); modifier onlyPayer() { require(_msgSender() == payer, "not-stream-owner"); _; } modifier onlyPayerOrDelegated() { require( _msgSender() == payer || hasRole(PAUSABLE_ROLE, _msgSender()), "not-stream-owner-or-delegated" ); _; } modifier onlyPayee() { require(_msgSender() == payee, "not-payee"); _; } /** * @notice Creates a new payment stream * @dev Payer is set as admin of "PAUSABLE_ROLE", so he can grant and revoke the "pausable" role later on * @param _payer Owner of the stream * @param _payee address that receives the payment stream * @param _usdAmount uint256 total amount in USD (scaled to 18 decimals) to be distributed until endTime * @param _token address of the ERC20 token that payee receives as payment * @param _fundingAddress address used to withdraw the drip * @param _endTime timestamp that sets drip distribution end */ constructor( address _payer, address _payee, uint256 _usdAmount, address _token, address _fundingAddress, uint256 _endTime ) { factory = IPaymentStreamFactoryMetadata(_msgSender()); VERSION = factory.VERSION(); require(_endTime > block.timestamp, "invalid-end-time"); require(_payee != _fundingAddress, "payee-is-funding-address"); require( _payee != address(0) && _fundingAddress != address(0), "payee-or-funding-address-is-0" ); require(_usdAmount > 0, "usd-amount-is-0"); payee = _payee; usdAmount = _usdAmount; token = _token; fundingAddress = _fundingAddress; payer = _payer; startTime = block.timestamp; secs = _endTime - block.timestamp; usdPerSec = _usdAmount / secs; require(usdPerSec != 0, "usd-per-sec-is-0"); _setupRole(ADMIN_ROLE, _payer); _setRoleAdmin(PAUSABLE_ROLE, ADMIN_ROLE); } /** * @notice Delegates pausable capability to new delegate * @dev Only RoleAdmin (Payer) can delegate this capability, tx will revert otherwise * @param _delegate address that receives the "PAUSABLE_ROLE" */ function delegatePausable(address _delegate) external override { require(_delegate != address(0), "invalid-delegate"); grantRole(PAUSABLE_ROLE, _delegate); } /** * @notice Revokes pausable capability of a delegate * @dev Only RoleAdmin (Payer) can revoke this capability, tx will revert otherwise * @param _delegate address that has its "PAUSABLE_ROLE" revoked */ function revokePausable(address _delegate) external override { revokeRole(PAUSABLE_ROLE, _delegate); } /** * @notice Pauses a stream if caller is either the payer or a delegate of PAUSABLE_ROLE */ function pauseStream() external override onlyPayerOrDelegated { paused = true; emit StreamPaused(); } /** * @notice Unpauses a stream if caller is either the payer or a delegate of PAUSABLE_ROLE */ function unpauseStream() external override onlyPayerOrDelegated { paused = false; emit StreamUnpaused(); } /** * @notice If caller is the payer of the stream it sets a new address as receiver of the stream * @param _newPayee address of new payee */ function updatePayee(address _newPayee) external override onlyPayer { require(_newPayee != address(0), "invalid-new-payee"); require(_newPayee != payee, "same-new-payee"); require(_newPayee != fundingAddress, "new-payee-is-funding-address"); _claim(); emit PayeeUpdated(payee, _newPayee); payee = _newPayee; } /** * @notice If caller is the payer of the stream it sets a new address used to withdraw the drip * @param _newFundingAddress new address used to withdraw the drip */ function updateFundingAddress(address _newFundingAddress) external override onlyPayer { require(_newFundingAddress != address(0), "invalid-new-funding-address"); require(_newFundingAddress != fundingAddress, "same-new-funding-address"); require(_newFundingAddress != payee, "new-funding-address-is-payee"); emit FundingAddressUpdated(fundingAddress, _newFundingAddress); fundingAddress = _newFundingAddress; } /** * @notice If caller is the payer it increases or decreases a stream funding rate * @dev Any unclaimed drip amount remaining will be claimed on behalf of payee * @param _usdAmount uint256 total amount in USD (scaled to 18 decimals) to be distributed until endTime * @param _endTime timestamp that sets drip distribution end */ function updateFundingRate(uint256 _usdAmount, uint256 _endTime) external override onlyPayer { require(_endTime > block.timestamp, "invalid-end-time"); _claim(); usdAmount = _usdAmount; startTime = block.timestamp; secs = _endTime - block.timestamp; usdPerSec = _usdAmount / secs; claimed = 0; emit StreamUpdated(_usdAmount, _endTime); } /** * @notice If caller is the payee of the stream it receives the accrued drip amount */ function claim() external override onlyPayee { require(!paused, "stream-is-paused"); _claim(); } function claimable() external view override returns (uint256) { return _claimable(); } /** * @notice Helper function, gets the accrued drip of given stream converted into target token amount * @return uint256 amount in target token */ function claimableToken() external view override returns (uint256) { return factory.usdToTokenAmount(token, _claimable()); } function _claim() internal { uint256 _accumulated = _claimable(); if (_accumulated == 0) return; uint256 _amount = factory.usdToTokenAmount(token, _accumulated); claimed += _accumulated; IERC20(token).safeTransferFrom(fundingAddress, payee, _amount); emit Claimed(_accumulated, _amount); } /** * @notice gets the accrued drip of given stream in USD * @return uint256 USD amount (scaled to 18 decimals) */ function _claimable() internal view returns (uint256) { uint256 _elapsed = block.timestamp - startTime; if (_elapsed > secs) { return usdAmount - claimed; // no more drips to avoid floating point dust } return (usdPerSec * _elapsed) - claimed; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns ( int256 ); function latestTimestamp() external view returns ( uint256 ); function latestRound() external view returns ( uint256 ); function getAnswer( uint256 roundId ) external view returns ( int256 ); function getTimestamp( uint256 roundId ) external view returns ( uint256 ); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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) + 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 // 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.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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 Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } //SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IPaymentStream { event Claimed(uint256 usdAmount, uint256 tokenAmount); event StreamPaused(); event StreamUnpaused(); event StreamUpdated(uint256 usdAmount, uint256 endTime); event FundingAddressUpdated( address indexed previousFundingAddress, address indexed newFundingAddress ); event PayeeUpdated(address indexed previousPayee, address indexed newPayee); function claim() external; function pauseStream() external; function unpauseStream() external; function delegatePausable(address delegate) external; function revokePausable(address delegate) external; function updateFundingRate(uint256 usdAmount, uint256 endTime) external; function updateFundingAddress(address newFundingAddress) external; function updatePayee(address newPayee) external; function claimableToken() external view returns (uint256); function claimable() external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IPaymentStreamFactory.sol"; interface IPaymentStreamFactoryMetadata is IPaymentStreamFactory { // solhint-disable func-name-mixedcase function NAME() external view returns (string memory); function VERSION() external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Unpauses a stream if caller is either the payer or a delegate of PAUSABLE_ROLE/
function unpauseStream() external override onlyPayerOrDelegated { paused = false; emit StreamUnpaused(); }
1,315,607
pragma solidity ^0.5.0; import "./Adminable.sol"; import "./SafeMath.sol"; /** @title Online Marketplace. */ contract MarketPlace is Adminable { using SafeMath for uint256; struct Product { string name; uint price; uint quantity; uint sales; bool isOpen; mapping(address => uint) shoppers; } struct Front { string name; bool isOpen; string[] productKeys; mapping(string => bool) isProduct; mapping(string => Product) products; } struct Store { string name; uint balance; string[] frontKeys; mapping(string => bool) isFront; mapping(string => Front) fronts; } mapping(address => bool) public isStore; mapping(address => Store) public stores; address[] public storeKeys; // modifier onlyAdmin() { // require(msg.sender == admin, "caller is not admin"); // _; // } modifier onlyStoreOwner() { require(isStore[msg.sender], "caller is not store owner"); _; } modifier storeExist(address _owner) { require(isStore[_owner], "the store does not exist."); _; } event LogNewStore(address indexed owner, string name); event LogNewFront(address indexed owner, string front); event LogNewProduct(address indexed owner, string front, string product); event LogBuyProduct(address indexed shopper, address owner, string front, string product, uint amount); event LogWithdraw(address indexed owner, uint newBalance); constructor() public { // admin = msg.sender; } /** @dev Create a store by admin. * @param _owner address of store owner. * @param _name a unique name of store. */ function createStore(address _owner, string memory _name) public onlyAdmin stopInEmergency { require(!isStore[_owner], "duplicate store."); isStore[_owner] = true; stores[_owner] = Store(_name, 0, new string[](0)); storeKeys.push(_owner); emit LogNewStore(_owner, _name); } /** @dev Create a storefront by store owner . * @param _name a unique name of storefront. * @param _isOpen is the storefront available or not. */ function createFront(string memory _name, bool _isOpen) public onlyStoreOwner stopInEmergency { require(!stores[msg.sender].isFront[_name], "front name is already created."); Store storage store = stores[msg.sender]; store.isFront[_name] = true; store.fronts[_name] = Front(_name, _isOpen, new string[](0)); store.frontKeys.push(_name); emit LogNewFront(msg.sender, _name); } /** @dev Toggle storefront isOpen for shoppers. * @param _name a unique name of storefront. */ function toggleFrontActive(string memory _name) public onlyStoreOwner stopInEmergency { require(stores[msg.sender].isFront[_name], "front name doesn't exist."); Store storage s = stores[msg.sender]; Front storage f = s.fronts[_name]; f.isOpen = !f.isOpen; } /** @dev Create a product of storefront by store owner . * @param _front the name of storefront. * @param _product a unique name of product. * @param _price price of product. * @param _quantity quantity of product. * @param _isOpen is the product available or not. */ function createProduct(string memory _front, string memory _product, uint _price, uint _quantity, bool _isOpen) public onlyStoreOwner stopInEmergency { Store storage s = stores[msg.sender]; require(s.isFront[_front], "front doesn't exist."); Front storage f = s.fronts[_front]; require(!f.isProduct[_product], "product name is already created."); f.isProduct[_product] = true; f.products[_product] = Product(_product, _price, _quantity, 0, _isOpen); f.productKeys.push(_product); emit LogNewProduct(msg.sender, _front, _product); } /** @dev Toggle the product of storefront isOpen for shoppers. * @param _front a unique name of storefront. * @param _product a unique name of product. */ function toggleFrontActive(string memory _front, string memory _product) public onlyStoreOwner stopInEmergency { require(stores[msg.sender].isFront[_front], "front name doesn't exist."); Store storage s = stores[msg.sender]; Front storage f = s.fronts[_front]; require(f.isProduct[_product], "product name doesn't exist."); Product storage p = f.products[_product]; p.isOpen = !p.isOpen; } /** @dev Store owner can withdraw his balance. * @param _amount amount of balance to be withdraw. */ function withdraw(uint _amount) public onlyStoreOwner stopInEmergency { require(_amount <= stores[msg.sender].balance, "insufficient balance."); stores[msg.sender].balance = stores[msg.sender].balance.sub(_amount); msg.sender.transfer(_amount); emit LogWithdraw(msg.sender, stores[msg.sender].balance); } /** @dev Force store owners to withdraw their balance. * @param _owner address of store owner. */ function forcedWithdraw(address payable _owner) public onlyAdmin onlyInEmergency { require(stores[_owner].balance > 0, "the balance is zero."); uint amount = stores[_owner].balance; stores[_owner].balance = 0; _owner.transfer(amount); } /** @dev Shopper can purches a product. * @param _owner the address of store owner. * @param _front the unique name of storefront. * @param _product the unique name of product. * @param _amount purches amount of product. */ function buyProduct(address _owner, string memory _front, string memory _product, uint _amount) public payable stopInEmergency { require(isStore[_owner], "the store doesn't exist."); Store storage s = stores[_owner]; require(s.isFront[_front], "the front doesn't exist."); Front storage f = s.fronts[_front]; require(f.isOpen, "the front is not open."); require(f.isProduct[_product], "the product doesn't exist."); Product storage p = f.products[_product]; require(p.isOpen, "the product is not open."); require(_amount <= p.quantity, "out of amount."); require(msg.value >= _amount * p.price, "not enough value."); uint refund = msg.value.sub(_amount.mul(p.price)); if (refund > 0) { msg.sender.transfer(refund); } p.quantity = p.quantity.sub(_amount); p.sales = p.sales.add(_amount); p.shoppers[msg.sender] = p.shoppers[msg.sender].add(_amount); s.balance = s.balance.add(msg.value.sub(refund)); emit LogBuyProduct(msg.sender, _owner, _front, _product, _amount); } /** @dev Get store count. * @return The store count. */ function getStoreCount() public view returns(uint) { return storeKeys.length; } /** @dev Get a store information by index. * @param _index a index of store. * @return owner The address of store owner. * @return name The name of store. * @return balance The balance of store. */ function getStoreAtIndex(uint _index) public view returns(address owner, string memory name, uint balance) { require(_index < storeKeys.length, "out of index."); owner = storeKeys[_index]; name = stores[storeKeys[_index]].name; balance = stores[storeKeys[_index]].balance; } /** @dev Get a store information by address. * @param _owner an address of store owner. * @return name The name of store. * @return balance The balance of store. */ function getStoreDetail(address _owner) public view returns(string memory name, uint balance) { require(isStore[_owner], "the owner's store doesn't exist"); name = stores[_owner].name; balance = stores[_owner].balance; } /** @dev Get storefront count. * @param _owner the address of store owner. * @return The storefront count. */ function getFrontsCount(address _owner) public view returns(uint) { require(isStore[_owner], "the owner's store doesn't exist"); return stores[_owner].frontKeys.length; } /** @dev Get a storefront information by index. * @param _owner the address of store owner. * @param _index a index of storefront. * @return name The name of storefront. * @return isOpen The status of storefront. */ function getFrontAtIndex(address _owner, uint _index) public view returns(string memory name, bool isOpen) { require(isStore[_owner], "the owner's store doesn't exist"); Store storage s = stores[_owner]; require(_index < s.frontKeys.length, "out of index."); Front memory f = s.fronts[s.frontKeys[_index]]; name = f.name; isOpen = f.isOpen; } /** @dev Get product count of a storefront. * @param _owner the address of store owner. * @param _front the unique name of storefront. * @return The product count of the storefront. */ function getProductsCount(address _owner, string memory _front) public view returns(uint) { require(isStore[_owner], "the owner's store doesn't exist"); Store storage s = stores[_owner]; require(s.isFront[_front], "the owner's front doesn't exist"); Front memory f = s.fronts[_front]; return f.productKeys.length; } /** @dev Get a product information by index. * @param _owner the address of store owner. * @param _front the unique name of storefront. * @param _index a index of product of storefront. * @return name The name of product. * @return price The price of product. * @return quantity The quantity of product. * @return sales The sales of product. * @return isOpen The status of product. */ function getProductAtIndex(address _owner, string memory _front, uint _index) public view returns(string memory name, uint price, uint quantity, uint sales, bool isOpen) { require(isStore[_owner], "the owner's store doesn't exist"); Store storage s = stores[_owner]; require(s.isFront[_front], "the owner's front doesn't exist"); Front storage f = s.fronts[_front]; Product memory p = f.products[f.productKeys[_index]]; name = p.name; price = p.price; quantity = p.quantity; sales = p.sales; isOpen = p.isOpen; } function getShopperProducts(address _owner, string memory _front, string memory _product, address _shopper) public view returns(uint amount) { require(isStore[_owner], "the owner's store doesn't exist"); Store storage s = stores[_owner]; require(s.isFront[_front], "the owner's front doesn't exist"); Front storage f = s.fronts[_front]; Product storage p = f.products[_product]; amount = p.shoppers[_shopper]; } /** @dev Fallback function which reverts all tx. */ function () external payable { revert(); } }
Shopper can purches a product. _owner the address of store owner. _front the unique name of storefront. _product the unique name of product. _amount purches amount of product./
function buyProduct(address _owner, string memory _front, string memory _product, uint _amount) public payable stopInEmergency { require(isStore[_owner], "the store doesn't exist."); Store storage s = stores[_owner]; require(s.isFront[_front], "the front doesn't exist."); Front storage f = s.fronts[_front]; require(f.isOpen, "the front is not open."); require(f.isProduct[_product], "the product doesn't exist."); Product storage p = f.products[_product]; require(p.isOpen, "the product is not open."); require(_amount <= p.quantity, "out of amount."); require(msg.value >= _amount * p.price, "not enough value."); uint refund = msg.value.sub(_amount.mul(p.price)); if (refund > 0) { msg.sender.transfer(refund); } p.quantity = p.quantity.sub(_amount); p.sales = p.sales.add(_amount); p.shoppers[msg.sender] = p.shoppers[msg.sender].add(_amount); s.balance = s.balance.add(msg.value.sub(refund)); emit LogBuyProduct(msg.sender, _owner, _front, _product, _amount); }
5,412,303
pragma solidity ^0.5.0; /** * @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; } } library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function isOwner(address account) public view returns (bool) { if( account == owner ){ return true; } else { return false; } } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract AdminRole is Ownable{ using Roles for Roles.Role; event AdminAdded(address indexed account); event AdminRemoved(address indexed account); Roles.Role private _admin_list; constructor () internal { _addAdmin(msg.sender); } modifier onlyAdmin() { require(isAdmin(msg.sender)|| isOwner(msg.sender)); _; } function isAdmin(address account) public view returns (bool) { return _admin_list.has(account); } function addAdmin(address account) public onlyAdmin { _addAdmin(account); } function removeAdmin(address account) public onlyOwner { _removeAdmin(account); } function renounceAdmin() public { _removeAdmin(msg.sender); } function _addAdmin(address account) internal { _admin_list.add(account); emit AdminAdded(account); } function _removeAdmin(address account) internal { _admin_list.remove(account); emit AdminRemoved(account); } } contract Pausable is AdminRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, 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); _; } /** * @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() public onlyAdmin whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyAdmin whenPaused { _paused = false; emit Unpaused(msg.sender); } } 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); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Burnable is ERC20 { /** * @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); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } contract RPM is ERC20Detailed, ERC20Pausable, ERC20Burnable { struct LockInfo { uint256 _releaseTime; uint256 _amount; } address public implementation; mapping (address => LockInfo[]) public timelockList; mapping (address => bool) public frozenAccount; event Freeze(address indexed holder); event Unfreeze(address indexed holder); event Lock(address indexed holder, uint256 value, uint256 releaseTime); event Unlock(address indexed holder, uint256 value); modifier notFrozen(address _holder) { require(!frozenAccount[_holder]); _; } constructor() ERC20Detailed("RPM Protocol", "RPM", 18) public { _mint(msg.sender, 5000000000 * (10 ** 18)); } function balanceOf(address owner) public view returns (uint256) { uint256 totalBalance = super.balanceOf(owner); if( timelockList[owner].length >0 ){ for(uint i=0; i<timelockList[owner].length;i++){ totalBalance = totalBalance.add(timelockList[owner][i]._amount); } } return totalBalance; } function transfer(address to, uint256 value) public notFrozen(msg.sender) returns (bool) { if (timelockList[msg.sender].length > 0 ) { _autoUnlock(msg.sender); } return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public notFrozen(from) returns (bool) { if (timelockList[from].length > 0) { _autoUnlock(from); } return super.transferFrom(from, to, value); } function freezeAccount(address holder) public onlyAdmin returns (bool) { require(!frozenAccount[holder]); frozenAccount[holder] = true; emit Freeze(holder); return true; } function unfreezeAccount(address holder) public onlyAdmin returns (bool) { require(frozenAccount[holder]); frozenAccount[holder] = false; emit Unfreeze(holder); return true; } function lock(address holder, uint256 value, uint256 releaseTime) public onlyAdmin returns (bool) { require(_balances[holder] >= value,"There is not enough balance of holder."); _lock(holder,value,releaseTime); return true; } function transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlyAdmin returns (bool) { _transfer(msg.sender, holder, value); _lock(holder,value,releaseTime); return true; } function unlock(address holder, uint256 idx) public onlyAdmin returns (bool) { require( timelockList[holder].length > idx, "There is not lock info."); _unlock(holder,idx); return true; } /** * @dev Upgrades the implementation address * @param _newImplementation address of the new implementation */ function upgradeTo(address _newImplementation) public onlyOwner { require(implementation != _newImplementation); _setImplementation(_newImplementation); } function _lock(address holder, uint256 value, uint256 releaseTime) internal returns(bool) { _balances[holder] = _balances[holder].sub(value); timelockList[holder].push( LockInfo(releaseTime, value) ); emit Lock(holder, value, releaseTime); return true; } function _unlock(address holder, uint256 idx) internal returns(bool) { LockInfo storage lockinfo = timelockList[holder][idx]; uint256 releaseAmount = lockinfo._amount; delete timelockList[holder][idx]; timelockList[holder][idx] = timelockList[holder][timelockList[holder].length.sub(1)]; timelockList[holder].length -=1; emit Unlock(holder, releaseAmount); _balances[holder] = _balances[holder].add(releaseAmount); return true; } function _autoUnlock(address holder) internal returns(bool) { for(uint256 idx =0; idx < timelockList[holder].length ; idx++ ) { if (timelockList[holder][idx]._releaseTime <= now) { // If lockupinfo was deleted, loop restart at same position. if( _unlock(holder, idx) ) { idx -=1; } } } return true; } /** * @dev Sets the address of the current implementation * @param _newImp address of the new implementation */ function _setImplementation(address _newImp) internal { implementation = _newImp; } /** * @dev Fallback function allowing to perform a delegatecall * to the given implementation. This function will return * whatever the implementation call returns */ function () payable external { address impl = implementation; require(impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0) let size := returndatasize /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, size) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
Integer division of two numbers truncating the quotient, reverts on division by zero./ assert(a == b c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; }
1,377,532
pragma solidity ^0.5.2; import "./CereneumData.sol"; contract CereneumImplementation is CereneumData { using SafeMath for uint256; //Events event ClaimEvent( uint256 nOriginalClaimAmount, uint256 nAmountGranted, uint256 nBonuses, uint256 nPenalties, bool bWasReferred ); event StartStakeEvent( uint256 nAmount, uint256 nDays ); event CompoundInterestEvent( uint256 nInterestCompounded ); event EndStakeEvent( uint256 nPrincipal, uint256 nPayout, uint256 nDaysServed, uint256 nPenalty, uint256 nStakeShares, uint256 nDaysCommitted ); event EndStakeForAFriendEvent( uint256 nShares, uint256 tStakeEndTimeCommit ); event StartEthStakeEvent( uint256 nEthAmount ); event EndEthStakeEvent( uint256 nPayout ); /// @dev Returns the number of current stakes for given address. /// @param a_address Address of stake to lookup /// @return The number of stakes. function GetNumberOfStakes( address a_address ) external view returns (uint256) { return m_staked[a_address].length; } /// @dev Returns the number of current Eth pool stakes for given address. /// @param a_address Address of stake to lookup /// @return The number of stakes. function GetNumberOfEthPoolStakes( address a_address ) external view returns (uint256) { return m_EthereumStakers[a_address].length; } /// @dev Returns the timestamp until the next daily update /// @return The time until the next daily update. function GetTimeUntilNextDailyUpdate() external view returns (uint256) { uint256 nDay = 1 days; return nDay.sub((block.timestamp.sub(m_tContractLaunchTime)).mod(1 days)); } /// @dev Calculates difference between 2 timestamps in days /// @param a_nStartTime beginning timestamp /// @param a_nEndTime ending timestamp /// @return Difference between timestamps in days function DifferenceInDays( uint256 a_nStartTime, uint256 a_nEndTime ) public pure returns (uint256) { return (a_nEndTime.sub(a_nStartTime).div(1 days)); } /// @dev Calculates the number of days since contract launch for a given timestamp. /// @param a_tTimestamp Timestamp to calculate from /// @return Number of days into contract function TimestampToDaysSinceLaunch( uint256 a_tTimestamp ) public view returns (uint256) { return (a_tTimestamp.sub(m_tContractLaunchTime).div(1 days)); } /// @dev Gets the number of days since the launch of the contract /// @return Number of days since contract launch function DaysSinceLaunch() public view returns (uint256) { return (TimestampToDaysSinceLaunch(block.timestamp)); } /// @dev Checks if we're still in the claimable phase (first 52 weeks) /// @return Boolean on if we are still in the claimable phase function IsClaimablePhase() public view returns (bool) { return (DaysSinceLaunch() < 364); } /// @dev Starts a 1 day stake in the ETH pool. Requires minimum of 0.01 ETH function StartEthStake() external payable { //Require the minimum value for staking require(msg.value >= 0.01 ether, "ETH Sent not above minimum value"); require(DaysSinceLaunch() >= m_nClaimPhaseBufferDays, "Eth Pool staking doesn't begin until after the buffer window"); UpdateDailyData(); m_EthereumStakers[msg.sender].push( EthStakeStruct( msg.value, // Ethereum staked DaysSinceLaunch() //Day staked ) ); emit StartEthStakeEvent( msg.value ); m_nTotalEthStaked = m_nTotalEthStaked.add(msg.value); } /// @dev The default function function() external payable { } /// @dev Withdraw CER from the Eth pool after stake has completed /// @param a_nIndex The index of the stake to be withdrawn function WithdrawFromEthPool(uint256 a_nIndex) external { //Require that the stake index doesn't go out of bounds require(m_EthereumStakers[msg.sender].length > a_nIndex, "Eth stake does not exist"); UpdateDailyData(); uint256 nDay = m_EthereumStakers[msg.sender][a_nIndex].nDay; require(nDay < DaysSinceLaunch(), "Must wait until next day to withdraw"); uint256 nAmount = m_EthereumStakers[msg.sender][a_nIndex].nAmount; uint256 nPayoutAmount = m_dailyDataMap[nDay].nPayoutAmount.div(10); //10% uint256 nEthPoolPayout = nPayoutAmount.mul(nAmount) .div(m_dailyDataMap[nDay].nTotalEthStaked); _mint(msg.sender, nEthPoolPayout); emit EndEthStakeEvent( nEthPoolPayout ); uint256 nEndingIndex = m_EthereumStakers[msg.sender].length.sub(1); //Only copy if we aren't removing the last index if(nEndingIndex != a_nIndex) { //Copy last stake in array over stake we are removing m_EthereumStakers[msg.sender][a_nIndex] = m_EthereumStakers[msg.sender][nEndingIndex]; } //Lower array length by 1 m_EthereumStakers[msg.sender].length = nEndingIndex; } /// @dev Transfers ETH in the contract to the genesis address /// Only callable once every 12 weeks. function TransferContractETH() external { require(address(this).balance != 0, "No Eth to transfer"); require(m_nLastEthWithdrawalTime.add(12 weeks) <= block.timestamp, "Can only withdraw once every 3 months"); m_EthGenesis.transfer(address(this).balance); m_nLastEthWithdrawalTime = block.timestamp; } /// @dev Updates and stores the global interest for each day. /// Additionally adds the frenzy/prosperous bonuses and the Early/Late unstake penalties. /// This function gets called at the start of popular public functions to continuously update. function UpdateDailyData() public { for(m_nLastUpdatedDay; DaysSinceLaunch() > m_nLastUpdatedDay; m_nLastUpdatedDay++) { //Gives 5% inflation per 365 days uint256 nPayoutRound = totalSupply().div(7300); uint256 nUnclaimedCoins = 0; //Frenzy/Prosperous bonuses and Unclaimed redistribution only available during claims phase. if(m_nLastUpdatedDay < 364) { nUnclaimedCoins = m_nMaxRedeemable.sub(m_nTotalRedeemed); nUnclaimedCoins = GetRobinHoodMonthlyAmount(nUnclaimedCoins, m_nLastUpdatedDay); nPayoutRound = nPayoutRound.add(nUnclaimedCoins); //Pay frenzy and Prosperous bonuses to genesis address _mint(m_genesis, nPayoutRound.mul(m_nRedeemedCount).div(m_nUTXOCountAtSnapshot)); // Frenzy _mint(m_genesis, nPayoutRound.mul(m_nTotalRedeemed).div(m_nAdjustedMaxRedeemable)); // Prosperous nPayoutRound = nPayoutRound.add( //Frenzy bonus 0-100% based on total users claiming nPayoutRound.mul(m_nRedeemedCount).div(m_nUTXOCountAtSnapshot) ).add( //Prosperous bonus 0-100% based on size of claims nPayoutRound.mul(m_nTotalRedeemed).div(m_nAdjustedMaxRedeemable) ); } else { //If we are not in the claimable phase anymore apply the voted on interest multiplier //First we need to check if there is a new "most voted on" multiplier uint8 nVoteMultiplier = 1; uint256 nVoteCount = m_votingMultiplierMap[1]; for(uint8 i=2; i <= 10; i++) { if(m_votingMultiplierMap[i] > nVoteCount) { nVoteCount = m_votingMultiplierMap[i]; nVoteMultiplier = i; } } nPayoutRound = nPayoutRound.mul(nVoteMultiplier); //Store last interest multiplier for public viewing m_nInterestMultiplier = nVoteMultiplier; } //Add nPayoutRound to contract's balance _mint(address(this), nPayoutRound.sub(nUnclaimedCoins)); //Add early and late unstake pool to payout round if(m_nEarlyAndLateUnstakePool != 0) { nPayoutRound = nPayoutRound.add(m_nEarlyAndLateUnstakePool); //Reset back to 0 for next day m_nEarlyAndLateUnstakePool = 0; } //Store daily data m_dailyDataMap[m_nLastUpdatedDay] = DailyDataStuct( nPayoutRound, m_nTotalStakeShares, m_nTotalEthStaked ); m_nTotalEthStaked = 0; } } /// @dev Gets the circulating supply (total supply minus staked coins). /// @return Circulating Supply function GetCirculatingSupply() external view returns (uint256) { return totalSupply().sub(balanceOf(address(this))); } /// @dev Verify a Merkle proof using the UTXO Merkle tree /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_hMerkleLeaf Merkle leaf hash that must be present in the UTXO Merkle tree /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on validity of proof function VerifyProof( bytes32[] memory a_hMerkleTreeBranches, bytes32 a_hMerkleLeaf, BlockchainType a_nWhichChain ) public view returns (bool) { require(uint8(a_nWhichChain) >= 0 && uint8(a_nWhichChain) <= 4, "Invalid blockchain option"); return MerkleProof.verify(a_hMerkleTreeBranches, m_hMerkleTreeRootsArray[uint8(a_nWhichChain)], a_hMerkleLeaf); } /// @dev Validate the ECDSA parameters of signed message /// ECDSA public key associated with the specified Ethereum address /// @param a_addressClaiming Address within signed message /// @param a_publicKeyX X parameter of uncompressed ECDSA public key /// @param a_publicKeyY Y parameter of uncompressed ECDSA public key /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on if the signature is valid function ECDSAVerify( address a_addressClaiming, bytes32 a_publicKeyX, bytes32 a_publicKeyY, uint8 a_v, bytes32 a_r, bytes32 a_s, BlockchainType a_nWhichChain ) public pure returns (bool) { bytes memory addressAsHex = GenerateSignatureMessage(a_addressClaiming, a_nWhichChain); bytes32 hHash; if(a_nWhichChain != BlockchainType.Ethereum) //All Bitcoin chains and Litecoin do double sha256 hash { hHash = sha256(abi.encodePacked(sha256(abi.encodePacked(addressAsHex)))); } else //Otherwise ETH { hHash = keccak256(abi.encodePacked(addressAsHex)); } return ValidateSignature( hHash, a_v, a_r, a_s, PublicKeyToEthereumAddress(a_publicKeyX, a_publicKeyY) ); } /// @dev Convert an uncompressed ECDSA public key into an Ethereum address /// @param a_publicKeyX X parameter of uncompressed ECDSA public key /// @param a_publicKeyY Y parameter of uncompressed ECDSA public key /// @return Ethereum address generated from the ECDSA public key function PublicKeyToEthereumAddress( bytes32 a_publicKeyX, bytes32 a_publicKeyY ) public pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(a_publicKeyX, a_publicKeyY)); return address(uint160(uint256((hash)))); } /// @dev Calculate the Bitcoin-style address associated with an ECDSA public key /// @param a_publicKeyX First half of ECDSA public key /// @param a_publicKeyY Second half of ECDSA public key /// @param a_nAddressType Whether BTC/LTC is Legacy or Segwit address and if it was compressed /// @return Raw Bitcoin address function PublicKeyToBitcoinAddress( bytes32 a_publicKeyX, bytes32 a_publicKeyY, AddressType a_nAddressType ) public pure returns (bytes20) { bytes20 publicKey; uint8 initialByte; if(a_nAddressType == AddressType.LegacyCompressed || a_nAddressType == AddressType.SegwitCompressed) { //Hash the compressed format initialByte = (uint256(a_publicKeyY) & 1) == 0 ? 0x02 : 0x03; publicKey = ripemd160(abi.encodePacked(sha256(abi.encodePacked(initialByte, a_publicKeyX)))); } else { //Hash the uncompressed format initialByte = 0x04; publicKey = ripemd160(abi.encodePacked(sha256(abi.encodePacked(initialByte, a_publicKeyX, a_publicKeyY)))); } if(a_nAddressType == AddressType.LegacyUncompressed || a_nAddressType == AddressType.LegacyCompressed) { return publicKey; } else if(a_nAddressType == AddressType.SegwitUncompressed || a_nAddressType == AddressType.SegwitCompressed) { return ripemd160(abi.encodePacked(sha256(abi.encodePacked(hex"0014", publicKey)))); } } /// @dev Appends an Ethereum address onto the expected string for a Bitcoin signed message /// @param a_address Ethereum address /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Correctly formatted message for bitcoin signing function GenerateSignatureMessage( address a_address, BlockchainType a_nWhichChain ) public pure returns(bytes memory) { bytes16 hexDigits = "0123456789abcdef"; bytes memory prefix; uint8 nPrefixLength = 0; //One of the bitcoin chains if(a_nWhichChain >= BlockchainType.Bitcoin && a_nWhichChain <= BlockchainType.BitcoinSV) { nPrefixLength = 46; prefix = new bytes(nPrefixLength); prefix = "\x18Bitcoin Signed Message:\n\x3CClaim_Cereneum_to_0x"; } else if(a_nWhichChain == BlockchainType.Ethereum) //Ethereum chain { nPrefixLength = 48; prefix = new bytes(nPrefixLength); prefix = "\x19Ethereum Signed Message:\n60Claim_Cereneum_to_0x"; } else //Otherwise LTC { nPrefixLength = 47; prefix = new bytes(nPrefixLength); prefix = "\x19Litecoin Signed Message:\n\x3CClaim_Cereneum_to_0x"; } bytes20 addressBytes = bytes20(a_address); bytes memory message = new bytes(nPrefixLength + 40); uint256 nOffset = 0; for(uint i = 0; i < nPrefixLength; i++) { message[nOffset++] = prefix[i]; } for(uint i = 0; i < 20; i++) { message[nOffset++] = hexDigits[uint256(uint8(addressBytes[i] >> 4))]; message[nOffset++] = hexDigits[uint256(uint8(addressBytes[i] & 0x0f))]; } return message; } /// @dev Validate ECSDA signature was signed by the specified address /// @param a_hash Hash of signed data /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_address Ethereum address matching the signature /// @return Boolean on if the signature is valid function ValidateSignature( bytes32 a_hash, uint8 a_v, bytes32 a_r, bytes32 a_s, address a_address ) public pure returns (bool) { return ecrecover( a_hash, a_v, a_r, a_s ) == a_address; } /// @dev Verify that a UTXO with the Merkle leaf hash can be claimed /// @param a_hMerkleLeafHash Merkle tree hash of the UTXO to be checked /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on if the UTXO from the given hash can be redeemed function CanClaimUTXOHash( bytes32 a_hMerkleLeafHash, bytes32[] memory a_hMerkleTreeBranches, BlockchainType a_nWhichChain ) public view returns (bool) { //Check that the UTXO has not yet been redeemed and that it exists in the Merkle tree return( (m_claimedUTXOsMap[uint8(a_nWhichChain)][a_hMerkleLeafHash] == false) && VerifyProof(a_hMerkleTreeBranches, a_hMerkleLeafHash, a_nWhichChain) ); } /// @dev Check if address can make a claim /// @param a_addressRedeeming Raw Bitcoin address (no base58-check encoding) /// @param a_nAmount Amount of UTXO to redeem /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Boolean on if the UTXO can be redeemed function CanClaim( bytes20 a_addressRedeeming, uint256 a_nAmount, bytes32[] memory a_hMerkleTreeBranches, BlockchainType a_nWhichChain ) public view returns (bool) { //Calculate the hash of the Merkle leaf associated with this UTXO bytes32 hMerkleLeafHash = keccak256( abi.encodePacked( a_addressRedeeming, a_nAmount ) ); //Check if it can be redeemed return CanClaimUTXOHash(hMerkleLeafHash, a_hMerkleTreeBranches, a_nWhichChain); } /// @dev Calculates the monthly Robin Hood reward /// @param a_nAmount The amount to calculate from /// @param a_nDaysSinceLaunch The number of days since contract launch /// @return The amount after applying monthly Robin Hood calculation function GetRobinHoodMonthlyAmount(uint256 a_nAmount, uint256 a_nDaysSinceLaunch) public pure returns (uint256) { uint256 nScaledAmount = a_nAmount.mul(1000000000000); uint256 nScalar = 400000000000000; // 0.25% //Month 1 - 0.25% late penalty if(a_nDaysSinceLaunch < 43) { return nScaledAmount.div(nScalar.mul(29)); } //Month 2 - Additional 0.5% penalty // 0.25% + 0.5% = .75% else if(a_nDaysSinceLaunch < 72) { nScalar = 200000000000000; // 0.5% return nScaledAmount.div(nScalar.mul(29)); } //Month 3 - Additional 0.75% penalty // 0.25% + 0.5% + .75% = 1.5% else if(a_nDaysSinceLaunch < 101) { nScalar = 133333333333333; // 0.75% return nScaledAmount.div(nScalar.mul(29)); } //Month 4 - Additional 1.5% // 0.25% + 0.5% + .75% + 1.5% = 3% else if(a_nDaysSinceLaunch < 130) { nScalar = 66666666666666; // 1.5% return nScaledAmount.div(nScalar.mul(29)); } //Month 5 - Additional 3% // 0.25% + 0.5% + .75% + 1.5% + 3% = 6% else if(a_nDaysSinceLaunch < 159) { nScalar = 33333333333333; // 3% return nScaledAmount.div(nScalar.mul(29)); } //Month 6 - Additional 6% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% = 12% else if(a_nDaysSinceLaunch < 188) { nScalar = 16666666666666; // 6% return nScaledAmount.div(nScalar.mul(29)); } //Month 7 - Additional 8% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% = 20% else if(a_nDaysSinceLaunch < 217) { nScalar = 12499999999999; // 8% return nScaledAmount.div(nScalar.mul(29)); } //Month 8 - Additional 10% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% = 30% else if(a_nDaysSinceLaunch < 246) { nScalar = 10000000000000; // 10% return nScaledAmount.div(nScalar.mul(29)); } //Month 9 - Additional 12.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% = 42.5% else if(a_nDaysSinceLaunch < 275) { nScalar = 7999999999999; // 12.5% return nScaledAmount.div(nScalar.mul(29)); } //Month 10 - Additional 15% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% = 57.5% else if(a_nDaysSinceLaunch < 304) { nScalar = 6666666666666; // 15% return nScaledAmount.div(nScalar.mul(29)); } //Month 11 - Additional 17.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% = 75% else if(a_nDaysSinceLaunch < 334) { nScalar = 5714285714290; // 17.5% return nScaledAmount.div(nScalar.mul(30)); } //Month 12 - Additional 25% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% + 25% = 100% else if(a_nDaysSinceLaunch < 364) { nScalar = 4000000000000; // 25% return nScaledAmount.div(nScalar.mul(30)); } } /// @dev Calculates the monthly late penalty /// @param a_nAmount The amount to calculate from /// @param a_nDaysSinceLaunch The number of days since contract launch /// @return The amount after applying monthly late penalty function GetMonthlyLatePenalty(uint256 a_nAmount, uint256 a_nDaysSinceLaunch) public pure returns (uint256) { if(a_nDaysSinceLaunch <= m_nClaimPhaseBufferDays) { return 0; } uint256 nScaledAmount = a_nAmount.mul(1000000000000); uint256 nPreviousMonthPenalty = 0; uint256 nScalar = 400000000000000; // 0.25% //Month 1 - 0.25% late penalty if(a_nDaysSinceLaunch <= 43) { a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(14); return nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); } //Month 2 - Additional 0.5% penalty // 0.25% + 0.5% = .75% else if(a_nDaysSinceLaunch <= 72) { nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(43); nScalar = 200000000000000; // 0.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 3 - Additional 0.75% penalty // 0.25% + 0.5% + .75% = 1.5% else if(a_nDaysSinceLaunch <= 101) { nScalar = 133333333333333; // 0.75% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(72); nScalar = 133333333333333; // 0.75% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 4 - Additional 1.5% // 0.25% + 0.5% + .75% + 1.5% = 3% else if(a_nDaysSinceLaunch <= 130) { nScalar = 66666666666666; // 1.5% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(101); nScalar = 66666666666666; // 1.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 5 - Additional 3% // 0.25% + 0.5% + .75% + 1.5% + 3% = 6% else if(a_nDaysSinceLaunch <= 159) { nScalar = 33333333333333; // 3% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(130); nScalar = 33333333333333; // 3% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 6 - Additional 6% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% = 12% else if(a_nDaysSinceLaunch <= 188) { nScalar = 16666666666666; // 6% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(159); nScalar = 16666666666666; // 6% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 7 - Additional 8% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% = 20% else if(a_nDaysSinceLaunch <= 217) { nScalar = 8333333333333; // 12% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(188); nScalar = 12499999999999; // 8% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 8 - Additional 10% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% = 30% else if(a_nDaysSinceLaunch <= 246) { nScalar = 5000000000000; // 20% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(217); nScalar = 10000000000000; // 10% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 9 - Additional 12.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% = 42.5% else if(a_nDaysSinceLaunch <= 275) { nScalar = 3333333333333; // 30% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(246); nScalar = 7999999999999; // 12.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 10 - Additional 15% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% = 57.5% else if(a_nDaysSinceLaunch <= 304) { nScalar = 2352941176472; // 42.5% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(275); nScalar = 6666666666666; // 15% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(29)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 11 - Additional 17.5% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% = 75% else if(a_nDaysSinceLaunch <= 334) { nScalar = 1739130434782; // 57.5% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(304); nScalar = 5714285714290; // 17.5% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(30)); return nScaledAmount.add(nPreviousMonthPenalty); } //Month 12 - Additional 25% // 0.25% + 0.5% + .75% + 1.5% + 3% + 6% + 8% + 10% + 12.5% + 15% + 17.5% + 25% = 100% else if(a_nDaysSinceLaunch < 364) { nScalar = 1333333333333; // 75% nPreviousMonthPenalty = nScaledAmount.div(nScalar); a_nDaysSinceLaunch = a_nDaysSinceLaunch.sub(334); nScalar = 4000000000000; // 25% nScaledAmount = nScaledAmount.mul(a_nDaysSinceLaunch).div(nScalar.mul(30)); return nScaledAmount.add(nPreviousMonthPenalty); } else { return a_nAmount; } } /// @dev Returns claim amount with deduction based on weeks since contract launch. /// @param a_nAmount Amount of claim from UTXO /// @return Amount after any late penalties function GetLateClaimAmount(uint256 a_nAmount) internal view returns (uint256) { uint256 nDaysSinceLaunch = DaysSinceLaunch(); return a_nAmount.sub(GetMonthlyLatePenalty(a_nAmount, nDaysSinceLaunch)); } /// @dev Calculates speed bonus for claiming early /// @param a_nAmount Amount of claim from UTXO /// @return Speed bonus amount function GetSpeedBonus(uint256 a_nAmount) internal view returns (uint256) { uint256 nDaysSinceLaunch = DaysSinceLaunch(); //We give a two week buffer after contract launch before penalties if(nDaysSinceLaunch < m_nClaimPhaseBufferDays) { nDaysSinceLaunch = 0; } else { nDaysSinceLaunch = nDaysSinceLaunch.sub(m_nClaimPhaseBufferDays); } uint256 nMaxDays = 350; a_nAmount = a_nAmount.div(5); return a_nAmount.mul(nMaxDays.sub(nDaysSinceLaunch)).div(nMaxDays); } /// @dev Gets the redeem amount with the blockchain ratio applied. /// @param a_nAmount Amount of UTXO in satoshis /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Amount with blockchain ratio applied function GetRedeemRatio(uint256 a_nAmount, BlockchainType a_nWhichChain) internal view returns (uint256) { if(a_nWhichChain != BlockchainType.Bitcoin) { uint8 nWhichChain = uint8(a_nWhichChain); --nWhichChain; //Many zeros to avoid rounding errors uint256 nScalar = 100000000000000000; uint256 nRatio = nScalar.div(m_blockchainRatios[nWhichChain]); a_nAmount = a_nAmount.mul(1000000000000).div(nRatio); } return a_nAmount; } /// @dev Gets the redeem amount and bonuses based on time since contract launch /// @param a_nAmount Amount of UTXO in satoshis /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @return Claim amount, bonuses and penalty function GetRedeemAmount(uint256 a_nAmount, BlockchainType a_nWhichChain) public view returns (uint256, uint256, uint256) { a_nAmount = GetRedeemRatio(a_nAmount, a_nWhichChain); uint256 nAmount = GetLateClaimAmount(a_nAmount); uint256 nBonus = GetSpeedBonus(a_nAmount); return (nAmount, nBonus, a_nAmount.sub(nAmount)); } /// @dev Verify claim ownership from signed message /// @param a_nAmount Amount of UTXO claim /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_addressClaiming Ethereum address within signed message /// @param a_pubKeyX First half of uncompressed ECDSA public key from signed message /// @param a_pubKeyY Second half of uncompressed ECDSA public key from signed message /// @param a_nAddressType Whether BTC/LTC is Legacy or Segwit address /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC function ValidateOwnership( uint256 a_nAmount, bytes32[] memory a_hMerkleTreeBranches, address a_addressClaiming, bytes32 a_pubKeyX, bytes32 a_pubKeyY, AddressType a_nAddressType, uint8 a_v, bytes32 a_r, bytes32 a_s, BlockchainType a_nWhichChain ) internal { //Calculate the UTXO Merkle leaf hash for the correct chain bytes32 hMerkleLeafHash; if(a_nWhichChain != BlockchainType.Ethereum) //All Bitcoin chains and Litecoin have the same raw address format { hMerkleLeafHash = keccak256(abi.encodePacked(PublicKeyToBitcoinAddress(a_pubKeyX, a_pubKeyY, a_nAddressType), a_nAmount)); } else //Otherwise ETH { hMerkleLeafHash = keccak256(abi.encodePacked(PublicKeyToEthereumAddress(a_pubKeyX, a_pubKeyY), a_nAmount)); } //Require that the UTXO can be redeemed require(CanClaimUTXOHash(hMerkleLeafHash, a_hMerkleTreeBranches, a_nWhichChain), "UTXO Cannot be redeemed."); //Verify the ECDSA parameters match the signed message require( ECDSAVerify( a_addressClaiming, a_pubKeyX, a_pubKeyY, a_v, a_r, a_s, a_nWhichChain ), "ECDSA verification failed." ); //Save the UTXO as redeemed in the global map m_claimedUTXOsMap[uint8(a_nWhichChain)][hMerkleLeafHash] = true; } /// @dev Claim tokens from a UTXO at snapshot block /// granting CER tokens proportional to amount of UTXO. /// BCH, BSV, ETH & LTC chains get proportional BTC ratio awards. /// @param a_nAmount Amount of UTXO /// @param a_hMerkleTreeBranches Merkle tree branches from leaf to root /// @param a_addressClaiming The Ethereum address for the claimed CER tokens to be sent to /// @param a_publicKeyX X parameter of uncompressed ECDSA public key from UTXO /// @param a_publicKeyY Y parameter of uncompressed ECDSA public key from UTXO /// @param a_nAddressType Whether BTC/LTC is Legacy or Segwit address and if it was compressed /// @param a_v v parameter of ECDSA signature /// @param a_r r parameter of ECDSA signature /// @param a_s s parameter of ECDSA signature /// @param a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC /// @param a_referrer Optional address of referrer. Address(0) for no referral /// @return The number of tokens redeemed, if successful function Claim( uint256 a_nAmount, bytes32[] memory a_hMerkleTreeBranches, address a_addressClaiming, bytes32 a_publicKeyX, bytes32 a_publicKeyY, AddressType a_nAddressType, uint8 a_v, bytes32 a_r, bytes32 a_s, BlockchainType a_nWhichChain, address a_referrer ) public returns (uint256) { //No claims after the first 50 weeks of contract launch require(IsClaimablePhase(), "Claim is outside of claims period."); require(uint8(a_nWhichChain) >= 0 && uint8(a_nWhichChain) <= 4, "Incorrect blockchain value."); require(a_v <= 30 && a_v >= 27, "V parameter is invalid."); ValidateOwnership( a_nAmount, a_hMerkleTreeBranches, a_addressClaiming, a_publicKeyX, a_publicKeyY, a_nAddressType, a_v, a_r, a_s, a_nWhichChain ); UpdateDailyData(); m_nTotalRedeemed = m_nTotalRedeemed.add(GetRedeemRatio(a_nAmount, a_nWhichChain)); (uint256 nTokensRedeemed, uint256 nBonuses, uint256 nPenalties) = GetRedeemAmount(a_nAmount, a_nWhichChain); //Transfer coins from contracts wallet to claim wallet _transfer(address(this), a_addressClaiming, nTokensRedeemed); //Mint speed bonus to claiming address _mint(a_addressClaiming, nBonuses); //Speed bonus matched for genesis address _mint(m_genesis, nBonuses); m_nRedeemedCount = m_nRedeemedCount.add(1); if(a_referrer != address(0)) { //Grant 10% bonus token to the person being referred _mint(a_addressClaiming, nTokensRedeemed.div(10)); nBonuses = nBonuses.add(nTokensRedeemed.div(10)); //Grant 20% bonus of tokens to referrer _mint(a_referrer, nTokensRedeemed.div(5)); //Match referral bonus for genesis address (20% for referral and 10% for claimer referral = 30%) _mint(m_genesis, nTokensRedeemed.mul(1000000000000).div(3333333333333)); } emit ClaimEvent( a_nAmount, nTokensRedeemed, nBonuses, nPenalties, a_referrer != address(0) ); //Return the number of tokens redeemed return nTokensRedeemed.add(nBonuses); } /// @dev Calculates stake payouts for a given stake /// @param a_nStakeShares Number of shares to calculate payout for /// @param a_tLockTime Starting timestamp of stake /// @param a_tEndTime Ending timestamp of stake /// @return payout amount function CalculatePayout( uint256 a_nStakeShares, uint256 a_tLockTime, uint256 a_tEndTime ) public view returns (uint256) { if(m_nLastUpdatedDay == 0) return 0; uint256 nPayout = 0; uint256 tStartDay = TimestampToDaysSinceLaunch(a_tLockTime); //Calculate what day stake was closed uint256 tEndDay = TimestampToDaysSinceLaunch(a_tEndTime); //Iterate through each day and sum up the payout for(uint256 i = tStartDay; i < tEndDay; i++) { uint256 nDailyPayout = m_dailyDataMap[i].nPayoutAmount.mul(a_nStakeShares) .div(m_dailyDataMap[i].nTotalStakeShares); //Keep sum of payouts nPayout = nPayout.add(nDailyPayout); } return nPayout; } /// @dev Updates current amount of stake to apply compounding interest /// @notice This applies all of your earned interest to future payout calculations /// @param a_nStakeIndex index of stake to compound interest for function CompoundInterest( uint256 a_nStakeIndex ) external { require(m_nLastUpdatedDay != 0, "First update day has not finished."); //Get a reference to the stake to save gas from constant map lookups StakeStruct storage rStake = m_staked[msg.sender][a_nStakeIndex]; require(block.timestamp < rStake.tEndStakeCommitTime, "Stake has already matured."); UpdateDailyData(); uint256 nInterestEarned = CalculatePayout( rStake.nSharesStaked, rStake.tLastCompoundedUpdateTime, block.timestamp ); if(nInterestEarned != 0) { rStake.nCompoundedPayoutAccumulated = rStake.nCompoundedPayoutAccumulated.add(nInterestEarned); rStake.nSharesStaked = rStake.nSharesStaked.add(nInterestEarned); //InterestRateMultiplier votes m_votingMultiplierMap[rStake.nVotedOnMultiplier] = m_votingMultiplierMap[rStake.nVotedOnMultiplier].add(nInterestEarned); m_nTotalStakeShares = m_nTotalStakeShares.add(nInterestEarned); rStake.tLastCompoundedUpdateTime = block.timestamp; emit CompoundInterestEvent( nInterestEarned ); } } /// @dev Starts a stake /// @param a_nAmount Amount of token to stake /// @param a_nDays Number of days to stake /// @param a_nInterestMultiplierVote Pooled interest rate to vote for (1-10 => 5%-50% interest) function StartStake( uint256 a_nAmount, uint256 a_nDays, uint8 a_nInterestMultiplierVote ) external { require(DaysSinceLaunch() >= m_nClaimPhaseBufferDays, "Staking doesn't begin until after the buffer window"); //Verify account has enough tokens require(balanceOf(msg.sender) >= a_nAmount, "Not enough funds for stake."); //Don't allow 0 amount stakes require(a_nAmount > 0, "Stake amount must be greater than 0"); require(a_nDays >= 7, "Stake is under the minimum time required."); require(a_nInterestMultiplierVote >= 1 && a_nInterestMultiplierVote <= 10, "Interest multiplier range is 1-10."); //Calculate Unlock time uint256 tEndStakeCommitTime = block.timestamp.add(a_nDays.mul(1 days)); //Don't allow stakes over the maximum stake time require(tEndStakeCommitTime <= block.timestamp.add(m_nMaxStakingTime), "Stake time exceeds maximum."); UpdateDailyData(); //Calculate bonus interest for longer stake periods (20% bonus per year) uint256 nSharesModifier = 0; //Minimum stake time of 3 months to get amplifier bonus if(a_nDays >= 90) { //We can't have a fractional modifier such as .5 so we need to use whole numbers and divide later nSharesModifier = a_nDays.mul(2000000).div(365); } //20% bonus shares per year of committed stake time uint256 nStakeShares = a_nAmount.add(a_nAmount.mul(nSharesModifier).div(10000000)); //Create and store the stake m_staked[msg.sender].push( StakeStruct( a_nAmount, // nAmountStaked nStakeShares, // nSharesStaked 0, //Accumulated Payout from CompoundInterest block.timestamp, // tLockTime tEndStakeCommitTime, // tEndStakeCommitTime block.timestamp, //tLastCompoundedUpdateTime 0, // tTimeRemovedFromGlobalPool a_nInterestMultiplierVote, true, // bIsInGlobalPool false // bIsLatePenaltyAlreadyPooled ) ); emit StartStakeEvent( a_nAmount, a_nDays ); //InterestRateMultiplier m_votingMultiplierMap[a_nInterestMultiplierVote] = m_votingMultiplierMap[a_nInterestMultiplierVote].add(nStakeShares); //Globally track staked tokens m_nTotalStakedTokens = m_nTotalStakedTokens.add(a_nAmount); //Globally track staked shares m_nTotalStakeShares = m_nTotalStakeShares.add(nStakeShares); //Transfer staked tokens to contract wallet _transfer(msg.sender, address(this), a_nAmount); } /// @dev Calculates penalty for unstaking late /// @param a_tEndStakeCommitTime Timestamp stake matured /// @param a_tTimeRemovedFromGlobalPool Timestamp stake was removed from global pool /// @param a_nInterestEarned Interest earned from stake /// @return penalty value function CalculateLatePenalty( uint256 a_tEndStakeCommitTime, uint256 a_tTimeRemovedFromGlobalPool, uint256 a_nInterestEarned ) public pure returns (uint256) { uint256 nPenalty = 0; //One week grace period if(a_tTimeRemovedFromGlobalPool > a_tEndStakeCommitTime.add(1 weeks)) { //Penalty is 1% per day after the 1 week grace period uint256 nPenaltyPercent = DifferenceInDays(a_tEndStakeCommitTime.add(1 weeks), a_tTimeRemovedFromGlobalPool); //Cap max percent at 100 if(nPenaltyPercent > 100) { nPenaltyPercent = 100; } //Calculate penalty nPenalty = a_nInterestEarned.mul(nPenaltyPercent).div(100); } return nPenalty; } /// @dev Calculates penalty for unstaking early /// @param a_tLockTime Starting timestamp of stake /// @param a_nEndStakeCommitTime Timestamp the stake matures /// @param a_nAmount Amount that was staked /// @param a_nInterestEarned Interest earned from stake /// @return penalty value function CalculateEarlyPenalty( uint256 a_tLockTime, uint256 a_nEndStakeCommitTime, uint256 a_nAmount, uint256 a_nInterestEarned ) public view returns (uint256) { uint256 nPenalty = 0; if(block.timestamp < a_nEndStakeCommitTime) { //If they didn't stake for at least 1 full day we give them no interest //To prevent any abuse if(DifferenceInDays(a_tLockTime, block.timestamp) == 0) { nPenalty = a_nInterestEarned; } else { //Base penalty is half of earned interest nPenalty = a_nInterestEarned.div(2); } uint256 nCommittedStakeDays = DifferenceInDays(a_tLockTime, a_nEndStakeCommitTime); if(nCommittedStakeDays >= 90) { //Take another 10% per year of committed stake nPenalty = nPenalty.add(nPenalty.mul(nCommittedStakeDays).div(3650)); } //5% yearly interest converted to daily interest multiplied by stake time uint256 nMinimumPenalty = a_nAmount.mul(nCommittedStakeDays).div(7300); if(nMinimumPenalty > nPenalty) { nPenalty = nMinimumPenalty; } } return nPenalty; } /// @dev Removes completed stake from global pool /// @notice Removing finished stakes will increase the payout to other stakers. /// @param a_nStakeIndex Index of stake to process /// @param a_address Address of the staker function EndStakeForAFriend( uint256 a_nStakeIndex, address a_address ) external { //Require that the stake index doesn't go out of bounds require(m_staked[a_address].length > a_nStakeIndex, "Stake does not exist"); //Require that the stake has been matured require(block.timestamp > m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime, "Stake must be matured."); ProcessStakeEnding(a_nStakeIndex, a_address, true); } /// @dev Ends a stake, even if it is before it has matured. /// @notice If stake has matured behavior is the same as EndStakeSafely /// @param a_nStakeIndex Index of stake to close function EndStakeEarly( uint256 a_nStakeIndex ) external { //Require that the stake index doesn't go out of bounds require(m_staked[msg.sender].length > a_nStakeIndex, "Stake does not exist"); ProcessStakeEnding(a_nStakeIndex, msg.sender, false); } /// @dev Ends a stake safely. Will only execute if a stake is matured. /// @param a_nStakeIndex Index of stake to close function EndStakeSafely( uint256 a_nStakeIndex ) external { //Require that the stake index doesn't go out of bounds require(m_staked[msg.sender].length > a_nStakeIndex, "Stake does not exist"); //Require that stake is matured require(block.timestamp > m_staked[msg.sender][a_nStakeIndex].tEndStakeCommitTime, "Stake must be matured."); ProcessStakeEnding(a_nStakeIndex, msg.sender, false); } function ProcessStakeEnding( uint256 a_nStakeIndex, address a_address, bool a_bWasForAFriend ) internal { UpdateDailyData(); //Get a reference to the stake to save gas from constant map lookups StakeStruct storage rStake = m_staked[a_address][a_nStakeIndex]; uint256 tEndTime = block.timestamp > rStake.tEndStakeCommitTime ? rStake.tEndStakeCommitTime : block.timestamp; //Calculate Payout uint256 nTotalPayout = CalculatePayout( rStake.nSharesStaked, rStake.tLastCompoundedUpdateTime, tEndTime ); //Add any accumulated interest payout from user calling CompoundInterest nTotalPayout = nTotalPayout.add(rStake.nCompoundedPayoutAccumulated); //Add back the original amount staked nTotalPayout = nTotalPayout.add(rStake.nAmountStaked); //Is stake still in the global pool? if(rStake.bIsInGlobalPool) { //Update global staked token tracking m_nTotalStakedTokens = m_nTotalStakedTokens.sub(rStake.nAmountStaked); //Update global stake shares tracking m_nTotalStakeShares = m_nTotalStakeShares.sub(rStake.nSharesStaked); //InterestRateMultiplier m_votingMultiplierMap[rStake.nVotedOnMultiplier] = m_votingMultiplierMap[rStake.nVotedOnMultiplier].sub(rStake.nSharesStaked); //Set time removed rStake.tTimeRemovedFromGlobalPool = block.timestamp; //Set flag that it is no longer in the global pool rStake.bIsInGlobalPool = false; if(a_bWasForAFriend) { emit EndStakeForAFriendEvent( rStake.nSharesStaked, rStake.tEndStakeCommitTime ); } } //Calculate penalties if any uint256 nPenalty = 0; if(!a_bWasForAFriend) //Can't have an early penalty if it was called by EndStakeForAFriend { nPenalty = CalculateEarlyPenalty( rStake.tLockTime, rStake.tEndStakeCommitTime, rStake.nAmountStaked, nTotalPayout.sub(rStake.nAmountStaked) ); } //Only calculate late penalty if there wasn't an early penalty if(nPenalty == 0) { nPenalty = CalculateLatePenalty( rStake.tEndStakeCommitTime, rStake.tTimeRemovedFromGlobalPool, nTotalPayout.sub(rStake.nAmountStaked) ); } //Don't payout penalty amount that has already been paid out if(nPenalty != 0 && !rStake.bIsLatePenaltyAlreadyPooled) { //Split penalty between genesis and pool m_nEarlyAndLateUnstakePool = m_nEarlyAndLateUnstakePool.add(nPenalty.div(2)); _transfer(address(this), m_genesis, nPenalty.div(2)); } if(a_bWasForAFriend) { //Set flag rStake.bIsLatePenaltyAlreadyPooled = true; } else { //Apply penalty nTotalPayout = nTotalPayout.sub(nPenalty); emit EndStakeEvent( rStake.nAmountStaked, nTotalPayout, block.timestamp < rStake.tEndStakeCommitTime ? DifferenceInDays(rStake.tLockTime, block.timestamp) : DifferenceInDays(rStake.tLockTime, rStake.tTimeRemovedFromGlobalPool), nPenalty, rStake.nSharesStaked, DifferenceInDays(rStake.tLockTime, rStake.tEndStakeCommitTime) ); //Payout staked coins from contract _transfer(address(this), a_address, nTotalPayout); //Remove stake RemoveStake(a_address, a_nStakeIndex); } } /// @dev Remove stake from array /// @param a_address address of staker /// @param a_nStakeIndex index of the stake to delete function RemoveStake( address a_address, uint256 a_nStakeIndex ) internal { uint256 nEndingIndex = m_staked[a_address].length.sub(1); //Only copy if we aren't removing the last index if(nEndingIndex != a_nStakeIndex) { //Copy last stake in array over stake we are removing m_staked[a_address][a_nStakeIndex] = m_staked[a_address][nEndingIndex]; } //Lower array length by 1 m_staked[a_address].length = nEndingIndex; } }
Appends an Ethereum address onto the expected string for a Bitcoin signed message a_address Ethereum address a_nWhichChain Which blockchain is claiming, 0=BTC, 1=BCH, 2=BSV, 3=ETH, 4=LTC return Correctly formatted message for bitcoin signingOne of the bitcoin chains
function GenerateSignatureMessage( address a_address, BlockchainType a_nWhichChain ) public pure returns(bytes memory) { bytes16 hexDigits = "0123456789abcdef"; bytes memory prefix; uint8 nPrefixLength = 0; if(a_nWhichChain >= BlockchainType.Bitcoin && a_nWhichChain <= BlockchainType.BitcoinSV) { nPrefixLength = 46; prefix = new bytes(nPrefixLength); prefix = "\x18Bitcoin Signed Message:\n\x3CClaim_Cereneum_to_0x"; } { nPrefixLength = 48; prefix = new bytes(nPrefixLength); prefix = "\x19Ethereum Signed Message:\n60Claim_Cereneum_to_0x"; } { nPrefixLength = 47; prefix = new bytes(nPrefixLength); prefix = "\x19Litecoin Signed Message:\n\x3CClaim_Cereneum_to_0x"; } bytes20 addressBytes = bytes20(a_address); bytes memory message = new bytes(nPrefixLength + 40); uint256 nOffset = 0; for(uint i = 0; i < nPrefixLength; i++) { message[nOffset++] = prefix[i]; } for(uint i = 0; i < 20; i++) { message[nOffset++] = hexDigits[uint256(uint8(addressBytes[i] >> 4))]; message[nOffset++] = hexDigits[uint256(uint8(addressBytes[i] & 0x0f))]; } return message; }
5,400,059
pragma solidity 0.4.18; // From https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); assert(b >= 0); return b; } } /** * @title SafeMathInt * @dev Math operations with safety checks that throw on error * @dev SafeMath adapted for int256 */ library SafeMathInt { function mul(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when multiplying INT256_MIN with -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 assert(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1)); int256 c = a * b; assert((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing INT256_MIN by -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 assert(!(a == - 2**255 && b == -1)); // assert(b > 0); // Solidity automatically throws when dividing by 0 int256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(int256 a, int256 b) internal pure returns (int256) { assert((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function toUint256Safe(int256 a) internal pure returns (uint256) { assert(a>=0); return uint256(a); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev SafeMath adapted for uint8 */ library SafeMathUint8 { function mul(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint8 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint8 a, uint8 b) internal pure returns (uint8) { assert(b <= a); return a - b; } function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; assert(c >= a); return c; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev SafeMath adapted for uint96 */ library SafeMathUint96 { function mul(uint96 a, uint96 b) internal pure returns (uint96) { uint96 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint96 a, uint96 b) internal pure returns (uint96) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint96 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint96 a, uint96 b) internal pure returns (uint96) { assert(b <= a); return a - b; } function add(uint96 a, uint96 b) internal pure returns (uint96) { uint96 c = a + b; assert(c >= a); return c; } } /** * @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 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Administrable * @dev Base contract for the administration of Core. Handles whitelisting of currency contracts */ contract Administrable is Pausable { // mapping of address of trusted contract mapping(address => uint8) public trustedCurrencyContracts; // Events of the system event NewTrustedContract(address newContract); event RemoveTrustedContract(address oldContract); /** * @dev add a trusted currencyContract * * @param _newContractAddress The address of the currencyContract */ function adminAddTrustedCurrencyContract(address _newContractAddress) external onlyOwner { trustedCurrencyContracts[_newContractAddress] = 1; //Using int instead of boolean in case we need several states in the future. NewTrustedContract(_newContractAddress); } /** * @dev remove a trusted currencyContract * * @param _oldTrustedContractAddress The address of the currencyContract */ function adminRemoveTrustedCurrencyContract(address _oldTrustedContractAddress) external onlyOwner { require(trustedCurrencyContracts[_oldTrustedContractAddress] != 0); trustedCurrencyContracts[_oldTrustedContractAddress] = 0; RemoveTrustedContract(_oldTrustedContractAddress); } /** * @dev get the status of a trusted currencyContract * @dev Not used today, useful if we have several states in the future. * * @param _contractAddress The address of the currencyContract * @return The status of the currencyContract. If trusted 1, otherwise 0 */ function getStatusContract(address _contractAddress) view external returns(uint8) { return trustedCurrencyContracts[_contractAddress]; } /** * @dev check if a currencyContract is trusted * * @param _contractAddress The address of the currencyContract * @return bool true if contract is trusted */ function isTrustedContract(address _contractAddress) public view returns(bool) { return trustedCurrencyContracts[_contractAddress] == 1; } } /** * @title RequestCore * * @dev The Core is the main contract which stores all the requests. * * @dev The Core philosophy is to be as much flexible as possible to adapt in the future to any new system * @dev All the important conditions and an important part of the business logic takes place in the currency contracts. * @dev Requests can only be created in the currency contracts * @dev Currency contracts have to be allowed by the Core and respect the business logic. * @dev Request Network will develop one currency contracts per currency and anyone can creates its own currency contracts. */ contract RequestCore is Administrable { using SafeMath for uint256; using SafeMathUint96 for uint96; using SafeMathInt for int256; using SafeMathUint8 for uint8; enum State { Created, Accepted, Canceled } struct Request { // ID address of the payer address payer; // Address of the contract managing the request address currencyContract; // State of the request State state; // Main payee Payee payee; } // Structure for the payees. A sub payee is an additional entity which will be paid during the processing of the invoice. // ex: can be used for routing taxes or fees at the moment of the payment. struct Payee { // ID address of the payee address addr; // amount expected for the payee. // Not uint for evolution (may need negative amounts one day), and simpler operations int256 expectedAmount; // balance of the payee int256 balance; } // Count of request in the mapping. A maximum of 2^96 requests can be created per Core contract. // Integer, incremented for each request of a Core contract, starting from 0 // RequestId (256bits) = contract address (160bits) + numRequest uint96 public numRequests; // Mapping of all the Requests. The key is the request ID. // not anymore public to avoid "UnimplementedFeatureError: Only in-memory reference type can be stored." // https://github.com/ethereum/solidity/issues/3577 mapping(bytes32 => Request) requests; // Mapping of subPayees of the requests. The key is the request ID. // This array is outside the Request structure to optimize the gas cost when there is only 1 payee. mapping(bytes32 => Payee[256]) public subPayees; /* * Events */ event Created(bytes32 indexed requestId, address indexed payee, address indexed payer, address creator, string data); event Accepted(bytes32 indexed requestId); event Canceled(bytes32 indexed requestId); // Event for Payee & subPayees event NewSubPayee(bytes32 indexed requestId, address indexed payee); // Separated from the Created Event to allow a 4th indexed parameter (subpayees) event UpdateExpectedAmount(bytes32 indexed requestId, uint8 payeeIndex, int256 deltaAmount); event UpdateBalance(bytes32 indexed requestId, uint8 payeeIndex, int256 deltaAmount); /* * @dev Function used by currency contracts to create a request in the Core * * @dev _payees and _expectedAmounts must have the same size * * @param _creator Request creator. The creator is the one who initiated the request (create or sign) and not necessarily the one who broadcasted it * @param _payees array of payees address (the index 0 will be the payee the others are subPayees). Size must be smaller than 256. * @param _expectedAmounts array of Expected amount to be received by each payees. Must be in same order than the payees. Size must be smaller than 256. * @param _payer Entity expected to pay * @param _data data of the request * @return Returns the id of the request */ function createRequest( address _creator, address[] _payees, int256[] _expectedAmounts, address _payer, string _data) external whenNotPaused returns (bytes32 requestId) { // creator must not be null require(_creator!=0); // not as modifier to lighten the stack // call must come from a trusted contract require(isTrustedContract(msg.sender)); // not as modifier to lighten the stack // Generate the requestId requestId = generateRequestId(); address mainPayee; int256 mainExpectedAmount; // extract the main payee if filled if(_payees.length!=0) { mainPayee = _payees[0]; mainExpectedAmount = _expectedAmounts[0]; } // Store the new request requests[requestId] = Request(_payer, msg.sender, State.Created, Payee(mainPayee, mainExpectedAmount, 0)); // Declare the new request Created(requestId, mainPayee, _payer, _creator, _data); // Store and declare the sub payees (needed in internal function to avoid "stack too deep") initSubPayees(requestId, _payees, _expectedAmounts); return requestId; } /* * @dev Function used by currency contracts to create a request in the Core from bytes * @dev Used to avoid receiving a stack too deep error when called from a currency contract with too many parameters. * @audit Note that to optimize the stack size and the gas cost we do not extract the params and store them in the stack. As a result there is some code redundancy * @param _data bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @return Returns the id of the request */ function createRequestFromBytes(bytes _data) external whenNotPaused returns (bytes32 requestId) { // call must come from a trusted contract require(isTrustedContract(msg.sender)); // not as modifier to lighten the stack // extract address creator & payer address creator = extractAddress(_data, 0); address payer = extractAddress(_data, 20); // creator must not be null require(creator!=0); // extract the number of payees uint8 payeesCount = uint8(_data[40]); // get the position of the dataSize in the byte (= number_of_payees * (address_payee_size + int256_payee_size) + address_creator_size + address_payer_size + payees_count_size // (= number_of_payees * (20+32) + 20 + 20 + 1 ) uint256 offsetDataSize = uint256(payeesCount).mul(52).add(41); // extract the data size and then the data itself uint8 dataSize = uint8(_data[offsetDataSize]); string memory dataStr = extractString(_data, dataSize, offsetDataSize.add(1)); address mainPayee; int256 mainExpectedAmount; // extract the main payee if possible if(payeesCount!=0) { mainPayee = extractAddress(_data, 41); mainExpectedAmount = int256(extractBytes32(_data, 61)); } // Generate the requestId requestId = generateRequestId(); // Store the new request requests[requestId] = Request(payer, msg.sender, State.Created, Payee(mainPayee, mainExpectedAmount, 0)); // Declare the new request Created(requestId, mainPayee, payer, creator, dataStr); // Store and declare the sub payees for(uint8 i = 1; i < payeesCount; i = i.add(1)) { address subPayeeAddress = extractAddress(_data, uint256(i).mul(52).add(41)); // payees address cannot be 0x0 require(subPayeeAddress != 0); subPayees[requestId][i-1] = Payee(subPayeeAddress, int256(extractBytes32(_data, uint256(i).mul(52).add(61))), 0); NewSubPayee(requestId, subPayeeAddress); } return requestId; } /* * @dev Function used by currency contracts to accept a request in the Core. * @dev callable only by the currency contract of the request * @param _requestId Request id */ function accept(bytes32 _requestId) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); r.state = State.Accepted; Accepted(_requestId); } /* * @dev Function used by currency contracts to cancel a request in the Core. Several reasons can lead to cancel a request, see request life cycle for more info. * @dev callable only by the currency contract of the request * @param _requestId Request id */ function cancel(bytes32 _requestId) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); r.state = State.Canceled; Canceled(_requestId); } /* * @dev Function used to update the balance * @dev callable only by the currency contract of the request * @param _requestId Request id * @param _payeeIndex index of the payee (0 = main payee) * @param _deltaAmount modifier amount */ function updateBalance(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); if( _payeeIndex == 0 ) { // modify the main payee r.payee.balance = r.payee.balance.add(_deltaAmount); } else { // modify the sub payee Payee storage sp = subPayees[_requestId][_payeeIndex-1]; sp.balance = sp.balance.add(_deltaAmount); } UpdateBalance(_requestId, _payeeIndex, _deltaAmount); } /* * @dev Function update the expectedAmount adding additional or subtract * @dev callable only by the currency contract of the request * @param _requestId Request id * @param _payeeIndex index of the payee (0 = main payee) * @param _deltaAmount modifier amount */ function updateExpectedAmount(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); if( _payeeIndex == 0 ) { // modify the main payee r.payee.expectedAmount = r.payee.expectedAmount.add(_deltaAmount); } else { // modify the sub payee Payee storage sp = subPayees[_requestId][_payeeIndex-1]; sp.expectedAmount = sp.expectedAmount.add(_deltaAmount); } UpdateExpectedAmount(_requestId, _payeeIndex, _deltaAmount); } /* * @dev Internal: Init payees for a request (needed to avoid 'stack too deep' in createRequest()) * @param _requestId Request id * @param _payees array of payees address * @param _expectedAmounts array of payees initial expected amounts */ function initSubPayees(bytes32 _requestId, address[] _payees, int256[] _expectedAmounts) internal { require(_payees.length == _expectedAmounts.length); for (uint8 i = 1; i < _payees.length; i = i.add(1)) { // payees address cannot be 0x0 require(_payees[i] != 0); subPayees[_requestId][i-1] = Payee(_payees[i], _expectedAmounts[i], 0); NewSubPayee(_requestId, _payees[i]); } } /* GETTER */ /* * @dev Get address of a payee * @param _requestId Request id * @param _payeeIndex payee index (0 = main payee) * @return payee address */ function getPayeeAddress(bytes32 _requestId, uint8 _payeeIndex) public constant returns(address) { if(_payeeIndex == 0) { return requests[_requestId].payee.addr; } else { return subPayees[_requestId][_payeeIndex-1].addr; } } /* * @dev Get payer of a request * @param _requestId Request id * @return payer address */ function getPayer(bytes32 _requestId) public constant returns(address) { return requests[_requestId].payer; } /* * @dev Get amount expected of a payee * @param _requestId Request id * @param _payeeIndex payee index (0 = main payee) * @return amount expected */ function getPayeeExpectedAmount(bytes32 _requestId, uint8 _payeeIndex) public constant returns(int256) { if(_payeeIndex == 0) { return requests[_requestId].payee.expectedAmount; } else { return subPayees[_requestId][_payeeIndex-1].expectedAmount; } } /* * @dev Get number of subPayees for a request * @param _requestId Request id * @return number of subPayees */ function getSubPayeesCount(bytes32 _requestId) public constant returns(uint8) { for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { // nothing to do } return i; } /* * @dev Get currencyContract of a request * @param _requestId Request id * @return currencyContract address */ function getCurrencyContract(bytes32 _requestId) public constant returns(address) { return requests[_requestId].currencyContract; } /* * @dev Get balance of a payee * @param _requestId Request id * @param _payeeIndex payee index (0 = main payee) * @return balance */ function getPayeeBalance(bytes32 _requestId, uint8 _payeeIndex) public constant returns(int256) { if(_payeeIndex == 0) { return requests[_requestId].payee.balance; } else { return subPayees[_requestId][_payeeIndex-1].balance; } } /* * @dev Get balance total of a request * @param _requestId Request id * @return balance */ function getBalance(bytes32 _requestId) public constant returns(int256) { int256 balance = requests[_requestId].payee.balance; for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { balance = balance.add(subPayees[_requestId][i].balance); } return balance; } /* * @dev check if all the payees balances are null * @param _requestId Request id * @return true if all the payees balances are equals to 0 */ function areAllBalanceNull(bytes32 _requestId) public constant returns(bool isNull) { isNull = requests[_requestId].payee.balance == 0; for (uint8 i = 0; isNull && subPayees[_requestId][i].addr != address(0); i = i.add(1)) { isNull = subPayees[_requestId][i].balance == 0; } return isNull; } /* * @dev Get total expectedAmount of a request * @param _requestId Request id * @return balance */ function getExpectedAmount(bytes32 _requestId) public constant returns(int256) { int256 expectedAmount = requests[_requestId].payee.expectedAmount; for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { expectedAmount = expectedAmount.add(subPayees[_requestId][i].expectedAmount); } return expectedAmount; } /* * @dev Get state of a request * @param _requestId Request id * @return state */ function getState(bytes32 _requestId) public constant returns(State) { return requests[_requestId].state; } /* * @dev Get address of a payee * @param _requestId Request id * @return payee index (0 = main payee) or -1 if not address not found */ function getPayeeIndex(bytes32 _requestId, address _address) public constant returns(int16) { // return 0 if main payee if(requests[_requestId].payee.addr == _address) return 0; for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { if(subPayees[_requestId][i].addr == _address) { // if found return subPayee index + 1 (0 is main payee) return i+1; } } return -1; } /* * @dev getter of a request * @param _requestId Request id * @return request as a tuple : (address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance) */ function getRequest(bytes32 _requestId) external constant returns(address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance) { Request storage r = requests[_requestId]; return ( r.payer, r.currencyContract, r.state, r.payee.addr, r.payee.expectedAmount, r.payee.balance ); } /* * @dev extract a string from a bytes. Extracts a sub-part from tha bytes and convert it to string * @param data bytes from where the string will be extracted * @param size string size to extract * @param _offset position of the first byte of the string in bytes * @return string */ function extractString(bytes data, uint8 size, uint _offset) internal pure returns (string) { bytes memory bytesString = new bytes(size); for (uint j = 0; j < size; j++) { bytesString[j] = data[_offset+j]; } return string(bytesString); } /* * @dev generate a new unique requestId * @return a bytes32 requestId */ function generateRequestId() internal returns (bytes32) { // Update numRequest numRequests = numRequests.add(1); // requestId = ADDRESS_CONTRACT_CORE + numRequests (0xADRRESSCONTRACT00000NUMREQUEST) return bytes32((uint256(this) << 96).add(numRequests)); } /* * @dev extract an address from a bytes at a given position * @param _data bytes from where the address will be extract * @param _offset position of the first byte of the address * @return address */ function extractAddress(bytes _data, uint offset) internal pure returns (address m) { require(offset >=0 && offset + 20 <= _data.length); assembly { m := and( mload(add(_data, add(20, offset))), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /* * @dev extract a bytes32 from a bytes * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes _data, uint offset) public pure returns (bytes32 bs) { require(offset >=0 && offset + 32 <= _data.length); assembly { bs := mload(add(_data, add(32, offset))) } } /** * @dev transfer to owner any tokens send by mistake on this contracts * @param token The address of the token to transfer. * @param amount The amount to be transfered. */ function emergencyERC20Drain(ERC20 token, uint amount ) public onlyOwner { token.transfer(owner, amount); } } /** * @title RequestCollectInterface * * @dev RequestCollectInterface is a contract managing the fees for currency contracts */ contract RequestCollectInterface is Pausable { using SafeMath for uint256; uint256 public rateFeesNumerator; uint256 public rateFeesDenominator; uint256 public maxFees; // address of the contract that will burn req token (through Kyber) address public requestBurnerContract; /* * Events */ event UpdateRateFees(uint256 rateFeesNumerator, uint256 rateFeesDenominator); event UpdateMaxFees(uint256 maxFees); /* * @dev Constructor * @param _requestBurnerContract Address of the contract where to send the ethers. * This burner contract will have a function that can be called by anyone and will exchange ethers to req via Kyber and burn the REQ */ function RequestCollectInterface(address _requestBurnerContract) public { requestBurnerContract = _requestBurnerContract; } /* * @dev send fees to the request burning address * @param _amount amount to send to the burning address */ function collectForREQBurning(uint256 _amount) internal returns(bool) { return requestBurnerContract.send(_amount); } /* * @dev compute the fees * @param _expectedAmount amount expected for the request * @return the expected amount of fees in wei */ function collectEstimation(int256 _expectedAmount) public view returns(uint256) { if(_expectedAmount<0) return 0; uint256 computedCollect = uint256(_expectedAmount).mul(rateFeesNumerator); if(rateFeesDenominator != 0) { computedCollect = computedCollect.div(rateFeesDenominator); } return computedCollect < maxFees ? computedCollect : maxFees; } /* * @dev set the fees rate * NB: if the _rateFeesDenominator is 0, it will be treated as 1. (in other words, the computation of the fees will not use it) * @param _rateFeesNumerator numerator rate * @param _rateFeesDenominator denominator rate */ function setRateFees(uint256 _rateFeesNumerator, uint256 _rateFeesDenominator) external onlyOwner { rateFeesNumerator = _rateFeesNumerator; rateFeesDenominator = _rateFeesDenominator; UpdateRateFees(rateFeesNumerator, rateFeesDenominator); } /* * @dev set the maximum fees in wei * @param _newMax new max */ function setMaxCollectable(uint256 _newMaxFees) external onlyOwner { maxFees = _newMaxFees; UpdateMaxFees(maxFees); } /* * @dev set the request burner address * @param _requestBurnerContract address of the contract that will burn req token (probably through Kyber) */ function setRequestBurnerContract(address _requestBurnerContract) external onlyOwner { requestBurnerContract=_requestBurnerContract; } } /** * @title RequestCurrencyContractInterface * * @dev RequestCurrencyContractInterface is the currency contract managing the request in Ethereum * @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them or withdraw funds. * * @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer */ contract RequestCurrencyContractInterface is RequestCollectInterface { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; // RequestCore object RequestCore public requestCore; /* * @dev Constructor * @param _requestCoreAddress Request Core address */ function RequestCurrencyContractInterface(address _requestCoreAddress, address _addressBurner) RequestCollectInterface(_addressBurner) public { requestCore=RequestCore(_requestCoreAddress); } /* * @dev Base function for request creation * * @dev msg.sender will be the creator * * @param _payer Entity expected to pay * @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request and the sum of the expected amounts */ function createCoreRequestInternal( address _payer, address[] _payeesIdAddress, int256[] _expectedAmounts, string _data) internal whenNotPaused returns(bytes32 requestId, int256 totalExpectedAmounts) { totalExpectedAmounts = 0; for (uint8 i = 0; i < _expectedAmounts.length; i = i.add(1)) { // all expected amounts must be positive require(_expectedAmounts[i]>=0); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(_expectedAmounts[i]); } // store request in the core requestId= requestCore.createRequest(msg.sender, _payeesIdAddress, _expectedAmounts, _payer, _data); } /* * @dev Function to accept a request * * @dev msg.sender must be _payer * * @param _requestId id of the request */ function acceptAction(bytes32 _requestId) public whenNotPaused onlyRequestPayer(_requestId) { // only a created request can be accepted require(requestCore.getState(_requestId)==RequestCore.State.Created); // declare the acceptation in the core requestCore.accept(_requestId); } /* * @dev Function to cancel a request * * @dev msg.sender must be the _payer or the _payee. * @dev only request with balance equals to zero can be cancel * * @param _requestId id of the request */ function cancelAction(bytes32 _requestId) public whenNotPaused { // payer can cancel if request is just created // payee can cancel when request is not canceled yet require((requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created) || (requestCore.getPayeeAddress(_requestId,0)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled)); // impossible to cancel a Request with any payees balance != 0 require(requestCore.areAllBalanceNull(_requestId)); // declare the cancellation in the core requestCore.cancel(_requestId); } /* * @dev Function to declare additionals * * @dev msg.sender must be _payer * @dev the request must be accepted or created * * @param _requestId id of the request * @param _additionalAmounts amounts of additional to declare (index 0 is for main payee) */ function additionalAction(bytes32 _requestId, uint256[] _additionalAmounts) public whenNotPaused onlyRequestPayer(_requestId) { // impossible to make additional if request is canceled require(requestCore.getState(_requestId)!=RequestCore.State.Canceled); // impossible to declare more additionals than the number of payees require(_additionalAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); for(uint8 i = 0; i < _additionalAmounts.length; i = i.add(1)) { // no need to declare a zero as additional if(_additionalAmounts[i] != 0) { // Store and declare the additional in the core requestCore.updateExpectedAmount(_requestId, i, _additionalAmounts[i].toInt256Safe()); } } } /* * @dev Function to declare subtracts * * @dev msg.sender must be _payee * @dev the request must be accepted or created * * @param _requestId id of the request * @param _subtractAmounts amounts of subtract to declare (index 0 is for main payee) */ function subtractAction(bytes32 _requestId, uint256[] _subtractAmounts) public whenNotPaused onlyRequestPayee(_requestId) { // impossible to make subtracts if request is canceled require(requestCore.getState(_requestId)!=RequestCore.State.Canceled); // impossible to declare more subtracts than the number of payees require(_subtractAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); for(uint8 i = 0; i < _subtractAmounts.length; i = i.add(1)) { // no need to declare a zero as subtracts if(_subtractAmounts[i] != 0) { // subtract must be equal or lower than amount expected require(requestCore.getPayeeExpectedAmount(_requestId,i) >= _subtractAmounts[i].toInt256Safe()); // Store and declare the subtract in the core requestCore.updateExpectedAmount(_requestId, i, -_subtractAmounts[i].toInt256Safe()); } } } // ---------------------------------------------------------------------------------------- /* * @dev Modifier to check if msg.sender is the main payee * @dev Revert if msg.sender is not the main payee * @param _requestId id of the request */ modifier onlyRequestPayee(bytes32 _requestId) { require(requestCore.getPayeeAddress(_requestId, 0)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is payer * @dev Revert if msg.sender is not payer * @param _requestId id of the request */ modifier onlyRequestPayer(bytes32 _requestId) { require(requestCore.getPayer(_requestId)==msg.sender); _; } } /** * @title RequestERC20 * * @dev RequestERC20 is the currency contract managing the request in ERC20 token * @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them or withdraw funds. * * @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer */ contract RequestERC20 is RequestCurrencyContractInterface { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; // payment addresses by requestId (optional). We separate the Identity of the payee/payer (in the core) and the wallet address in the currency contract mapping(bytes32 => address[256]) public payeesPaymentAddress; mapping(bytes32 => address) public payerRefundAddress; // token address ERC20 public erc20Token; /* * @dev Constructor * @param _requestCoreAddress Request Core address * @param _requestBurnerAddress Request Burner contract address * @param _erc20Token ERC20 token contract handled by this currency contract */ function RequestERC20(address _requestCoreAddress, address _requestBurnerAddress, ERC20 _erc20Token) RequestCurrencyContractInterface(_requestCoreAddress, _requestBurnerAddress) public { erc20Token = _erc20Token; } /* * @dev Function to create a request as payee * * @dev msg.sender must be the main payee * @dev if _payeesPaymentAddress.length > _payeesIdAddress.length, the extra addresses will be stored but never used * * @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees) * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payer Entity expected to pay * @param _payerRefundAddress Address of refund for the payer (optional) * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayeeAction( address[] _payeesIdAddress, address[] _payeesPaymentAddress, int256[] _expectedAmounts, address _payer, address _payerRefundAddress, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0); int256 totalExpectedAmounts; (requestId, totalExpectedAmounts) = createCoreRequestInternal(_payer, _payeesIdAddress, _expectedAmounts, _data); // compute and send fees uint256 fees = collectEstimation(totalExpectedAmounts); require(fees == msg.value && collectForREQBurning(fees)); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // set payment address for payer if(_payerRefundAddress != 0) { payerRefundAddress[requestId] = _payerRefundAddress; } return requestId; } /* * @dev Function to create a request as payer. The request is payed if _payeeAmounts > 0. * * @dev msg.sender will be the payer * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _payeesIdAddress array of payees address (the index 0 will be the payee the others are subPayees) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payerRefundAddress Address of refund for the payer (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayerAction( address[] _payeesIdAddress, int256[] _expectedAmounts, address _payerRefundAddress, uint256[] _payeeAmounts, uint256[] _additionals, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(msg.sender != _payeesIdAddress[0] && _payeesIdAddress[0] != 0); int256 totalExpectedAmounts; (requestId, totalExpectedAmounts) = createCoreRequestInternal(msg.sender, _payeesIdAddress, _expectedAmounts, _data); // set payment address for payer if(_payerRefundAddress != 0) { payerRefundAddress[requestId] = _payerRefundAddress; } // accept and pay the request with the value remaining after the fee collect acceptAndPay(requestId, _payeeAmounts, _additionals, totalExpectedAmounts); return requestId; } /* * @dev Function to broadcast and accept an offchain signed request (the broadcaster can also pays and makes additionals ) * * @dev msg.sender will be the _payer * @dev only the _payer can make additionals * @dev if _payeesPaymentAddress.length > _requestData.payeesIdAddress.length, the extra addresses will be stored but never used * * @param _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature in bytes * * @return Returns the id of the request */ function broadcastSignedRequestAsPayerAction( bytes _requestData, // gather data to avoid "stack too deep" address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals, uint256 _expirationDate, bytes _signature) external payable whenNotPaused returns(bytes32 requestId) { // check expiration date require(_expirationDate >= block.timestamp); // check the signature require(checkRequestSignature(_requestData, _payeesPaymentAddress, _expirationDate, _signature)); return createAcceptAndPayFromBytes(_requestData, _payeesPaymentAddress, _payeeAmounts, _additionals); } /* * @dev Internal function to create, accept, add additionals and pay a request as Payer * * @dev msg.sender must be _payer * * @param _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * * @return Returns the id of the request */ function createAcceptAndPayFromBytes( bytes _requestData, address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals) internal returns(bytes32 requestId) { // extract main payee address mainPayee = extractAddress(_requestData, 41); require(msg.sender != mainPayee && mainPayee != 0); // creator must be the main payee require(extractAddress(_requestData, 0) == mainPayee); // extract the number of payees uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for(uint8 i = 0; i < payeesCount; i++) { // extract the expectedAmount for the payee[i] int256 expectedAmountTemp = int256(extractBytes32(_requestData, uint256(i).mul(52).add(61))); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp); // all expected amount must be positive require(expectedAmountTemp>0); } // compute and send fees uint256 fees = collectEstimation(totalExpectedAmounts); // check fees has been well received require(fees == msg.value && collectForREQBurning(fees)); // insert the msg.sender as the payer in the bytes updateBytes20inBytes(_requestData, 20, bytes20(msg.sender)); // store request in the core requestId = requestCore.createRequestFromBytes(_requestData); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // accept and pay the request with the value remaining after the fee collect acceptAndPay(requestId, _payeeAmounts, _additionals, totalExpectedAmounts); return requestId; } /* * @dev Internal function to accept, add additionals and pay a request as Payer * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equals to _amountPaid) * @param _additionals Will increase the ExpectedAmounts of payees * @param _payeeAmountsSum total of amount token send for this transaction * */ function acceptAndPay( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionals, int256 _payeeAmountsSum) internal { acceptAction(_requestId); additionalAction(_requestId, _additionals); if(_payeeAmountsSum > 0) { paymentInternal(_requestId, _payeeAmounts); } } /* * @dev Function to pay a request in ERC20 token * * @dev msg.sender must have a balance of the token higher or equal to the sum of _payeeAmounts * @dev msg.sender must have approved an amount of the token higher or equal to the sum of _payeeAmounts to the current contract * @dev the request will be automatically accepted if msg.sender==payer. * * @param _requestId id of the request * @param _payeeAmounts Amount to pay to payees (sum must be equal to msg.value) in wei * @param _additionalAmounts amount of additionals per payee in wei to declare */ function paymentAction( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionalAmounts) external whenNotPaused { // automatically accept request if request is created and msg.sender is payer if (requestCore.getState(_requestId)==RequestCore.State.Created && msg.sender == requestCore.getPayer(_requestId)) { acceptAction(_requestId); } if (_additionalAmounts.length != 0) { additionalAction(_requestId, _additionalAmounts); } paymentInternal(_requestId, _payeeAmounts); } /* * @dev Function to pay back in ERC20 token a request to the payees * * @dev msg.sender must have a balance of the token higher or equal to _amountToRefund * @dev msg.sender must have approved an amount of the token higher or equal to _amountToRefund to the current contract * @dev msg.sender must be one of the payees or one of the payees payment address * @dev the request must be created or accepted * * @param _requestId id of the request */ function refundAction(bytes32 _requestId, uint256 _amountToRefund) external whenNotPaused { refundInternal(_requestId, msg.sender, _amountToRefund); } // ---- INTERNAL FUNCTIONS ---------------------------------------------------------------- /* * @dev Function internal to manage payment declaration * * @param _requestId id of the request * @param _payeesAmounts Amount to pay to payees (sum must be equals to msg.value) */ function paymentInternal( bytes32 _requestId, uint256[] _payeeAmounts) internal { require(requestCore.getState(_requestId)!=RequestCore.State.Canceled); // we cannot have more amounts declared than actual payees require(_payeeAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); for(uint8 i = 0; i < _payeeAmounts.length; i = i.add(1)) { if(_payeeAmounts[i] != 0) { // Store and declare the payment to the core requestCore.updateBalance(_requestId, i, _payeeAmounts[i].toInt256Safe()); // pay the payment address if given, the id address otherwise address addressToPay; if(payeesPaymentAddress[_requestId][i] == 0) { addressToPay = requestCore.getPayeeAddress(_requestId, i); } else { addressToPay = payeesPaymentAddress[_requestId][i]; } // payment done, the token need to be sent fundOrderInternal(msg.sender, addressToPay, _payeeAmounts[i]); } } } /* * @dev Function internal to manage refund declaration * * @param _requestId id of the request * @param _address address from where the refund has been done * @param _amount amount of the refund in ERC20 token to declare */ function refundInternal( bytes32 _requestId, address _address, uint256 _amount) internal { require(requestCore.getState(_requestId)!=RequestCore.State.Canceled); // Check if the _address is a payeesId int16 payeeIndex = requestCore.getPayeeIndex(_requestId, _address); // get the number of payees uint8 payeesCount = requestCore.getSubPayeesCount(_requestId).add(1); if(payeeIndex < 0) { // if not ID addresses maybe in the payee payments addresses for (uint8 i = 0; i < payeesCount && payeeIndex == -1; i = i.add(1)) { if(payeesPaymentAddress[_requestId][i] == _address) { // get the payeeIndex payeeIndex = int16(i); } } } // the address must be found somewhere require(payeeIndex >= 0); // useless (subPayee size <256): require(payeeIndex < 265); requestCore.updateBalance(_requestId, uint8(payeeIndex), -_amount.toInt256Safe()); // refund to the payment address if given, the id address otherwise address addressToPay = payerRefundAddress[_requestId]; if(addressToPay == 0) { addressToPay = requestCore.getPayer(_requestId); } // refund declared, the money is ready to be sent to the payer fundOrderInternal(_address, addressToPay, _amount); } /* * @dev Function internal to manage fund mouvement * * @param _from address where the token will get from * @param _recipient address where the token has to be sent to * @param _amount amount in ERC20 token to send */ function fundOrderInternal( address _from, address _recipient, uint256 _amount) internal { require(erc20Token.transferFrom(_from, _recipient, _amount)); } // ----------------------------------------------------------------------------- /* * @dev Check the validity of a signed request & the expiration date * @param _data bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @param _payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature containing v, r and s as bytes * * @return Validity of order signature. */ function checkRequestSignature( bytes _requestData, address[] _payeesPaymentAddress, uint256 _expirationDate, bytes _signature) public view returns (bool) { bytes32 hash = getRequestHash(_requestData, _payeesPaymentAddress, _expirationDate); // extract "v, r, s" from the signature uint8 v = uint8(_signature[64]); v = v < 27 ? v.add(27) : v; bytes32 r = extractBytes32(_signature, 0); bytes32 s = extractBytes32(_signature, 32); // check signature of the hash with the creator address return isValidSignature(extractAddress(_requestData, 0), hash, v, r, s); } /* * @dev Function internal to calculate Keccak-256 hash of a request with specified parameters * * @param _data bytes containing all the data packed * @param _payeesPaymentAddress array of payees payment addresses * @param _expirationDate timestamp after what the signed request cannot be broadcasted * * @return Keccak-256 hash of (this,_requestData, _payeesPaymentAddress, _expirationDate) */ function getRequestHash( bytes _requestData, address[] _payeesPaymentAddress, uint256 _expirationDate) internal view returns(bytes32) { return keccak256(this,_requestData, _payeesPaymentAddress, _expirationDate); } /* * @dev Verifies that a hash signature is valid. 0x style * @param signer address of signer. * @param hash Signed Keccak-256 hash. * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * @return Validity of order signature. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /* * @dev extract an address in a bytes * @param data bytes from where the address will be extract * @param offset position of the first byte of the address * @return address */ function extractAddress(bytes _data, uint offset) internal pure returns (address m) { require(offset >=0 && offset + 20 <= _data.length); assembly { m := and( mload(add(_data, add(20, offset))), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /* * @dev extract a bytes32 from a bytes * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes _data, uint offset) public pure returns (bytes32 bs) { require(offset >=0 && offset + 32 <= _data.length); assembly { bs := mload(add(_data, add(32, offset))) } } /* * @dev modify 20 bytes in a bytes * @param data bytes to modify * @param offset position of the first byte to modify * @param b bytes20 to insert * @return address */ function updateBytes20inBytes(bytes data, uint offset, bytes20 b) internal pure { require(offset >=0 && offset + 20 <= data.length); assembly { let m := mload(add(data, add(20, offset))) m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) m := or(m, div(b, 0x1000000000000000000000000)) mstore(add(data, add(20, offset)), m) } } }
set the maximum fees in wei _newMax new max/
function setMaxCollectable(uint256 _newMaxFees) external onlyOwner { maxFees = _newMaxFees; UpdateMaxFees(maxFees); }
6,189,717
./partial_match/1/0xA60E18145BED6BA4a269fA5b445695B37101947f/sources/contracts/OnChainPoll.sol
Retrieves the poll detail. id Poll id to fetch the poll details. return PollDetail The poll detail./
function getPollDetail( uint256 id ) external view override returns (PollDetails memory) { return PollDetails({ createPollDetails: createPollsDetail[id], endPollDetails: endPollsDetail[id] }); }
9,154,003
./full_match/43113/0x28F5c190AE9F6E2C08b5C3ebd26b9d8da0E16c92/sources/Certifications.sol
returns the certification subscribed by the `memberAddress`./
function getMemberSubscriptions(address memberAddress) public view returns (uint256[] memory) { return m_memberSubscriptions[memberAddress]; }
13,209,223
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; contract Factory{ mapping ( address => address ) private children; //from user to contract address private cloud; modifier OnlyCloud {require (msg.sender == cloud, "OnlyCloud"); _;} modifier Exists (address user) { require (children[user] != address(0), "Exists"); _;} event ChildCreated(address childAddress, address _user); constructor(){ cloud = msg.sender; } function createChild(address _user, uint _price, uint _validityDuration, uint lostFileCredits, uint undeletedFileCredits) external OnlyCloud{ CloudSLA child = new CloudSLA(msg.sender, _user, _price, _validityDuration, lostFileCredits, undeletedFileCredits); children[_user] = address(child); emit ChildCreated(address(child), _user); } function getSmartContractAddress(address user) external view Exists(user) returns(address){ return children[user]; } } contract CloudSLA { address private oracle = 0xFa5B6432308d45B54A1CE1373513Fab77166436f; address private user; address private cloud; struct Period{ uint startTime; uint endTime; } enum Violation {lostFile, undeletedFile} struct Sla{ bool paid; Period validityPeriod; uint credits; } enum State {defaultValue, uploadRequested, uploadRequestAck, uploadTransferAck, uploaded, deleteRequested, deleted, readRequested, readRequestAck, readDeny, checkRequested} struct File { bytes32 ID; //hash of filepath bool onCloud; State[] states; bytes32[] digests; //hashes of content string url; //last url } mapping ( bytes32 => File ) private files; uint price; mapping (Violation => uint) violationCredits; uint validityDuration; Sla private currentSLA; function Hash(string memory str) private pure returns(bytes32){ return (sha256(abi.encodePacked(str))); } modifier OnlyUser {require (msg.sender == user, "OnlyUser"); _;} modifier OnlyCloud {require (msg.sender == cloud, "OnlyCloud"); _;} modifier OnlyUserOrCloud{ require ((msg.sender == user || msg.sender == cloud), "OnlyUserOrCloud"); _;} function FileInBC(bytes32 i) public view returns(bool res) { return (i != 0x0 && files[i].ID != 0x0); } function UrlPublished(bytes32 i) public view returns(bool res) { return (i != 0x0 && files[i].ID != 0x0 && bytes(files[i].url).length != 0); } function FileOnCloud(bytes32 i, bool onCloud) public view returns(bool res) { bool inBC = files[i].ID != 0x0; if (onCloud) return (i != 0x0 && inBC && files[i].onCloud); else return (! inBC || ! files[i].onCloud); } function NotBeingChecked(bytes32 i) public view returns(bool res) { bool inBC = files[i].ID != 0x0; return (!inBC || (files[i].states[files[i].states.length - 1] != State.checkRequested)); } function FileState(bytes32 i, State prevState) public view returns(bool res) { bool inBC = files[i].ID != 0x0; State lastState = files[i].states[files[i].states.length - 1]; return (i != 0x0 && inBC && lastState == prevState); } modifier IsSLAValid(){ require(block.timestamp >= currentSLA.validityPeriod.startTime && block.timestamp <= currentSLA.validityPeriod.endTime, "SLAValidity"); _; } modifier Activatable(uint sentValue){ require(!currentSLA.paid && sentValue == price, "Activatable"); _; } modifier ValidityPeriodEnded(){ require(block.timestamp >= currentSLA.validityPeriod.endTime, "ValidityPeriodEnded"); _; } event Paid(address indexed _from, uint endTime); event CompensatedUser(address indexed _user, uint value); event PaidCloudProvider(address indexed _cloud, uint value); event UploadRequested(address indexed _from, string filepath); event UploadRequestAcked(address indexed _from, string filepath); event UploadTransferAcked(address indexed _from, string filepath, bytes32 digest); event DeleteRequested(address indexed _from, string filepath); event Deleted(address indexed _from, string filepath); event ReadRequested(address indexed _from, string filepath); event ReadRequestAcked(address indexed _from, string filepath, string url); event ReadRequestDenied(address indexed _from, string filepath, bool lostFile, uint credits); event FileChecked(address indexed _from, string filepath, string msg, uint credits); constructor (address _cloud, address _user, uint _price, uint _validityDuration, uint lostFileCredits, uint undeletedFileCredits) { cloud = _cloud; user = _user; price = _price; validityDuration = _validityDuration; violationCredits[Violation.lostFile] = lostFileCredits; violationCredits[Violation.undeletedFile] = undeletedFileCredits; } function Deposit() external payable OnlyUser Activatable(msg.value){ currentSLA.paid = true; currentSLA.validityPeriod.startTime = block.timestamp; currentSLA.validityPeriod.endTime = block.timestamp + validityDuration; emit Paid(msg.sender, currentSLA.validityPeriod.endTime); } function EndSla() external OnlyUserOrCloud ValidityPeriodEnded { CompensateUser(); PayCloudProvider(); delete currentSLA; } function CompensateUser() internal { uint value = currentSLA.credits < price ? currentSLA.credits : price; payable(user).transfer(value); emit CompensatedUser(user, value); } function PayCloudProvider() internal{ uint value = address(this).balance; payable(cloud).transfer(value); emit PaidCloudProvider(cloud, value); } function UploadRequest(string calldata filepath) external OnlyUser IsSLAValid{ bytes32 i = Hash(filepath); require(FileOnCloud(i, false) && NotBeingChecked(i)); files[i].ID = i; files[i].states.push(State.uploadRequested); emit UploadRequested(msg.sender, filepath); } function UploadRequestAck(string calldata filepath) external OnlyCloud IsSLAValid{ bytes32 i = Hash(filepath); require(FileState(i, State.uploadRequested)); files[i].states.push(State.uploadRequestAck); emit UploadRequestAcked(msg.sender, filepath); } function UploadTransferAck(string calldata filepath, bytes32 digest) external OnlyCloud IsSLAValid{ bytes32 i = Hash(filepath); require(FileState(i, State.uploadRequestAck)); files[i].states.push(State.uploadTransferAck); files[i].digests.push(digest); emit UploadTransferAcked(msg.sender, filepath, digest); } function UploadConfirm(string calldata filepath, bool ack) external OnlyUser IsSLAValid{ bytes32 i = Hash(filepath); require(FileState(i, State.uploadTransferAck)); if(ack){ files[i].states.push(State.uploaded); files[i].onCloud = true; } else{ files[i].states.push(State.deleteRequested); emit DeleteRequested(msg.sender, filepath); } } function DeleteRequest(string calldata filepath) external OnlyUser IsSLAValid { bytes32 i = Hash(filepath); require(FileOnCloud(i, true) && NotBeingChecked(i)); files[i].states.push(State.deleteRequested); emit DeleteRequested(msg.sender, filepath); } function Delete(string calldata filepath) external OnlyCloud IsSLAValid{ bytes32 i = Hash(filepath); require(FileState(i, State.deleteRequested)); files[i].states.push(State.deleted); files[i].onCloud = false; emit Deleted(msg.sender, filepath); } function ReadRequest(string calldata filepath) external OnlyUser IsSLAValid{ bytes32 i = Hash(filepath); require(FileOnCloud(i, true) && NotBeingChecked(i)); files[i].states.push(State.readRequested); emit ReadRequested(msg.sender, filepath); } function ReadRequestAck(string calldata filepath, string calldata url) external OnlyCloud IsSLAValid{ bytes32 i = Hash(filepath); require(FileState(i, State.readRequested)); files[i].states.push(State.readRequestAck); files[i].url = url; emit ReadRequestAcked(msg.sender, filepath, url); } function ReadRequestDeny(string calldata filepath) external OnlyCloud IsSLAValid{ bytes32 i = Hash(filepath); require(FileState(i, State.readRequested)); files[i].states.push(State.readDeny); emit ReadRequestDenied(msg.sender, filepath, LostFileCheck(i), currentSLA.credits); } function LostFileCheck(bytes32 ID) internal returns(bool){ bool lostFile = !OperationAfterUpload(ID, State.deleteRequested); if(lostFile){ currentSLA.credits = currentSLA.credits + violationCredits[Violation.lostFile]; } return(lostFile); } function FileHashRequest(string calldata filepath) external OnlyUser IsSLAValid{ bytes32 i = Hash(filepath); require(UrlPublished(i)); FileDigestOracle(oracle).DigestRequest(files[i].url); if(files[i].states[files[i].states.length - 1] != State.checkRequested) files[i].states.push(State.checkRequested); } function FileCheck(string calldata filepath) external OnlyUser IsSLAValid{ bytes32 i = Hash(filepath); require(FileInBC(i) && FileState(i, State.checkRequested)); bool intactOnCloud = (files[i].digests[files[i].digests.length - 1] == FileDigestOracle(oracle).DigestRetrieve(files[i].url)); string memory res = "No SLA violations."; if(!files[i].onCloud && intactOnCloud) { res = "Cloud should have deleted the file but it did not."; currentSLA.credits = currentSLA.credits + violationCredits[Violation.undeletedFile]; }else if (files[i].onCloud && !intactOnCloud){ res = "File has been corrupted."; currentSLA.credits = currentSLA.credits + violationCredits[Violation.lostFile]; } //restore previous state files[i].states.push(files[i].states[files[i].states.length - 2]); emit FileChecked(msg.sender, filepath, res, currentSLA.credits); } //check if there is an operation after last upload function OperationAfterUpload(bytes32 ID, State operation) internal view returns(bool){ //get index of last uploaded state and last deleted state if present uint uploadedTime; uint operationTime; bool uploadedFound = false; bool operationFound = false; for (uint j = files[ID].states.length; j > 0; j--) { if(!operationFound && files[ID].states[j-1] == operation){ operationTime = j-1; operationFound = true; } else if(!uploadedFound && files[ID].states[j-1] == State.uploaded){ uploadedTime= j-1; uploadedFound = true; } //early exit if(operationFound && uploadedFound) break; } return(operationFound && operationTime > uploadedTime); } function GetFile(string memory filepath) public view returns(bytes32, State [] memory, bool, bytes32 [] memory, string memory){ bytes32 i = Hash(filepath); require(FileInBC(i)); return (files[i].ID, files[i].states, files[i].onCloud, files[i].digests, files[i].url); } function GetSLAInfo() public view returns(bool, uint, uint, uint){ return (currentSLA.paid, currentSLA.validityPeriod.startTime, currentSLA.validityPeriod.endTime, currentSLA.credits); } } interface FileDigestOracle { function DigestRequest(string calldata url) external; function DigestStore(string calldata url, bytes32 digest) external; function DigestRetrieve(string calldata url) external view returns(bytes32); }
check if there is an operation after last uploadget index of last uploaded state and last deleted state if present
function OperationAfterUpload(bytes32 ID, State operation) internal view returns(bool){ uint uploadedTime; uint operationTime; bool uploadedFound = false; bool operationFound = false; for (uint j = files[ID].states.length; j > 0; j--) { if(!operationFound && files[ID].states[j-1] == operation){ operationTime = j-1; operationFound = true; } else if(!uploadedFound && files[ID].states[j-1] == State.uploaded){ uploadedTime= j-1; uploadedFound = true; } break; } return(operationFound && operationTime > uploadedTime); }
1,036,035
./full_match/1/0xe5094556EDDCBdABFFEdFc2f7122e2b1702A6D4e/sources/ERC20.sol
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./ Overflow not possible: amount <= accountBalance <= totalSupply.
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); } event LockedLP(uint256 amount, uint256 duration); address private _owner; address public uniPair;
4,868,281
./full_match/1/0x5082C1EA537CD035c76F3BFb3f8e459794b3331D/sources/Sinja.sol
generate the uniswap pair path of token -> weth make the swap
function swapTokensForEth(uint256 swapAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), swapAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( swapAmount, path, address(this), block.timestamp ); }
16,513,073
./partial_match/42/0xF80Ac056c5D499d0D7efFBFe5E3f0BF6b152c486/sources/Affinity.sol
This function hands over ownership of the token, as well as the bpt tokens to the specified address. It also sets the balanced variable to whichever the old contract was. This prevents it from being recalled when the contract was upgraded. This function is particularly useful when it comes to upgrading the contract. This can be called once the new contract is deployed and everything will be migrated automatically. USE WITH CAUTION./
function handOverContract(address newOwner) public onlyOwner { sendBPT(newOwner, bpt.balanceOf(address(this))); erc20.handOverContract(newOwner); }
8,975,532
./full_match/1/0xe05447ae2426c4bEb7733c90058C00cC32ABfe49/sources/src/Kong/Treasury.sol
Redeem TOKEN for backing _amount Amount of TOKEN to redeem
function redeem(uint256 _amount) external { ITOKEN(TOKEN).burnFrom(msg.sender, _amount); IERC20(uniswapV2Router.WETH()).transfer(msg.sender, (_amount * BACKING) / 1e9); }
8,304,416
pragma solidity ^0.4.19; /** * Authored by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /** * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /** * Envisioned in FirstBlood ICO contract. * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /** * Originally from https://github.com/OpenZeppelin/zeppelin-solidity * Modified by https://www.coinfabrik.com/ */ /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() internal { 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)); owner = newOwner; } } /** * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * */ contract Haltable is Ownable { bool public halted; event Halted(bool halted); modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; Halted(true); } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; Halted(false); } } pragma solidity ^0.4.19; /** * Originally from https://github.com/OpenZeppelin/zeppelin-solidity * Modified by https://www.coinfabrik.com/ */ /** * 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(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } function min256(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } pragma solidity ^0.4.19; /** * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /** * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /** * Originally from https://github.com/OpenZeppelin/zeppelin-solidity * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /** * Interface for the standard token. * Based on https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract EIP20Token { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); function allowance(address owner, address spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /** ** Optional functions * function name() public view returns (string name); function symbol() public view returns (string symbol); function decimals() public view returns (uint8 decimals); * **/ } pragma solidity ^0.4.19; // Interface for burning tokens contract Burnable { // @dev Destroys tokens for an account // @param account Account whose tokens are destroyed // @param value Amount of tokens to destroy function burnTokens(address account, uint value) internal; event Burned(address account, uint value); } pragma solidity ^0.4.19; /** * Authored by https://www.coinfabrik.com/ */ /** * Internal interface for the minting of tokens. */ contract Mintable { /** * @dev Mints tokens for an account * This function should the Minted event. */ function mintInternal(address receiver, uint amount) internal; /** Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); } /** * @title Standard token * @dev Basic implementation of the EIP20 standard token (also known as ERC20 token). */ contract StandardToken is EIP20Token, Burnable, Mintable { using SafeMath for uint; uint private total_supply; mapping(address => uint) private balances; mapping(address => mapping (address => uint)) private allowed; function totalSupply() public view returns (uint) { return total_supply; } /** * @dev transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); return true; } /** * @dev Gets the balance of the specified address. * @param account The address whose balance is to be queried. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address account) public view returns (uint balance) { return balances[account]; } /** * @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 uint the amout of tokens to be transfered */ function transferFrom(address from, address to, uint value) public returns (bool success) { uint allowance = allowed[from][msg.sender]; // Check is not needed because sub(allowance, value) will already throw if this condition is not met // require(value <= allowance); // SafeMath uses assert instead of require though, beware when using an analysis tool balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowance.sub(value); Transfer(from, to, value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses&#39; // allowance to zero by calling `approve(spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require (value == 0 || allowed[msg.sender][spender] == 0); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param account address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address account, address spender) public view returns (uint remaining) { return allowed[account][spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address spender, uint addedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][spender]; allowed[msg.sender][spender] = oldValue.add(addedValue); Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address spender, uint subtractedValue) public returns (bool success) { uint oldVal = allowed[msg.sender][spender]; if (subtractedValue > oldVal) { allowed[msg.sender][spender] = 0; } else { allowed[msg.sender][spender] = oldVal.sub(subtractedValue); } Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } /** * @dev Provides an internal function for destroying tokens. Useful for upgrades. */ function burnTokens(address account, uint value) internal { balances[account] = balances[account].sub(value); total_supply = total_supply.sub(value); Transfer(account, 0, value); Burned(account, value); } /** * @dev Provides an internal minting function. */ function mintInternal(address receiver, uint amount) internal { total_supply = total_supply.add(amount); balances[receiver] = balances[receiver].add(amount); Minted(receiver, amount); // Beware: Address zero may be used for special transactions in a future fork. // This will make the mint transaction appear in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } } /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is StandardToken, Ownable { /* The finalizer contract that allows lifting the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Set the contract that can call release and make the token transferable. * * Since the owner of this contract is (or should be) the crowdsale, * it can only be called by a corresponding exposed API in the crowdsale contract in case of input error. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don&#39;t do interface check here as we might want to have a normal wallet address to act as a release agent. releaseAgent = addr; } /** * Owner can allow a particular address (e.g. a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens into the wild. * * Can be called only from the release agent that should typically be the finalize agent ICO contract. * In the scope of the crowdsale, it is only called if the crowdsale has been a success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** * Limit token transfer until the crowdsale is over. */ modifier canTransfer(address sender) { require(released || transferAgents[sender]); _; } /** The function can be called only before or after the tokens have been released */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } /** We restrict transfer by overriding it */ function transfer(address to, uint value) public canTransfer(msg.sender) returns (bool success) { // Call StandardToken.transfer() return super.transfer(to, value); } /** We restrict transferFrom by overriding it */ function transferFrom(address from, address to, uint value) public canTransfer(from) returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(from, to, value); } } pragma solidity ^0.4.19; /** * First envisioned by Golem and Lunyr projects. * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /** * Inspired by Lunyr. * Originally from https://github.com/TokenMarketNet/ico */ /** * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. * * The Upgrade agent is the interface used to implement a token * migration in the case of an emergency. * The function upgradeFrom has to implement the part of the creation * of new tokens on behalf of the user doing the upgrade. * * The new token can implement this interface directly, or use. */ contract UpgradeAgent { /** This value should be the same as the original token&#39;s total supply */ uint public originalSupply; /** Interface to ensure the contract is correctly configured */ function isUpgradeAgent() public pure returns (bool) { return true; } /** Upgrade an account When the token contract is in the upgrade status the each user will have to call `upgrade(value)` function from UpgradeableToken. The upgrade function adjust the balance of the user and the supply of the previous token and then call `upgradeFrom(value)`. The UpgradeAgent is the responsible to create the tokens for the user in the new contract. * @param from Account to upgrade. * @param value Tokens to upgrade. */ function upgradeFrom(address from, uint value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * */ contract UpgradeableToken is EIP20Token, Burnable { using SafeMath for uint; /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint public totalUpgraded = 0; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don&#39;t have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet. This allows changing the upgrade agent while there is time. * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed from, address to, uint value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address master) internal { setUpgradeMaster(master); } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint value) public { UpgradeState state = getUpgradeState(); // Ensure it&#39;s not called in a bad state require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); // Validate input value. require(value != 0); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); // Take tokens out from circulation burnTokens(msg.sender, value); totalUpgraded = totalUpgraded.add(value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles the upgrade process */ function setUpgradeAgent(address agent) onlyMaster external { // Check whether the token is in a state that we could think of upgrading require(canUpgrade()); require(agent != 0x0); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply()); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public view returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function changeUpgradeMaster(address new_master) onlyMaster public { setUpgradeMaster(new_master); } /** * Internal upgrade master setter. */ function setUpgradeMaster(address new_master) private { require(new_master != 0x0); upgradeMaster = new_master; } /** * Child contract can override to provide the condition in which the upgrade can begin. */ function canUpgrade() public view returns(bool) { return true; } modifier onlyMaster() { require(msg.sender == upgradeMaster); _; } } pragma solidity ^0.4.19; /** * Authored by https://www.coinfabrik.com/ */ // This contract aims to provide an inheritable way to recover tokens from a contract not meant to hold tokens // To use this contract, have your token-ignoring contract inherit this one and implement getLostAndFoundMaster to decide who can move lost tokens. // Of course, this contract imposes support costs upon whoever is the lost and found master. contract LostAndFoundToken { /** * @return Address of the account that handles movements. */ function getLostAndFoundMaster() internal view returns (address); /** * @param agent Address that will be able to move tokens with transferFrom * @param tokens Amount of tokens approved for transfer * @param token_contract Contract of the token */ function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public { require(msg.sender == getLostAndFoundMaster()); // We use approve instead of transfer to minimize the possibility of the lost and found master // getting them stuck in another address by accident. token_contract.approve(agent, tokens); } } pragma solidity ^0.4.19; /** * Originally from https://github.com/TokenMarketNet/ico * Modified by https://www.coinfabrik.com/ */ /** * A public interface to increase the supply of a token. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, usually contracts whitelisted by the owner, can mint new tokens. * */ contract MintableToken is Mintable, Ownable { using SafeMath for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); function MintableToken(uint initialSupply, address multisig, bool mintable) internal { require(multisig != address(0)); // Cannot create a token without supply and no minting require(mintable || initialSupply != 0); // Create initially all balance on the team multisig if (initialSupply > 0) mintInternal(multisig, initialSupply); // No more new supply allowed after the token creation mintingFinished = !mintable; } /** * Create new tokens and allocate them to an address. * * Only callable by a mint agent (e.g. crowdsale contract). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { mintInternal(receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only mint agents are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** Make sure we are not done yet. */ modifier canMint() { require(!mintingFinished); _; } } /** * A crowdsale token. * * An ERC-20 token designed specifically for crowdsales with investor protection and further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through the approve() mechanism * - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens) * - ERC20 tokens transferred to this contract can be recovered by a lost and found master * */ contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, LostAndFoundToken { string public name = "TokenHome"; string public symbol = "TH"; uint8 public decimals; address public lost_and_found_master; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param initial_supply How many tokens we start with. * @param token_decimals Number of decimal places. * @param team_multisig Address of the multisig that receives the initial supply and is set as the upgrade master. * @param token_retriever Address of the account that handles ERC20 tokens that were accidentally sent to this contract. */ function CrowdsaleToken(uint initial_supply, uint8 token_decimals, address team_multisig, address token_retriever) public UpgradeableToken(team_multisig) MintableToken(initial_supply, team_multisig, true) { require(token_retriever != address(0)); decimals = token_decimals; lost_and_found_master = token_retriever; } /** * When token is released to be transferable, prohibit new token creation. */ function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality to kick in only if the crowdsale was a success. */ function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); } function burn(uint value) public { burnTokens(msg.sender, value); } function getLostAndFoundMaster() internal view returns(address) { return lost_and_found_master; } } /** * Abstract base contract for token sales. * * Handles * - start and end dates * - accepting investments * - various statistics during the crowdfund * - different investment policies (require server side customer id, allow only whitelisted addresses) * */ contract GenericCrowdsale is Haltable { using SafeMath for uint; /* The token we are selling */ CrowdsaleToken public token; /* ether will be transferred to this address */ address public multisigWallet; /* the starting timestamp of the crowdsale */ uint public startsAt; /* the ending timestamp of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* Has this crowdsale been finalized */ bool public finalized = false; /* Do we need to have a unique contributor id for each customer */ bool public requireCustomerId = false; /* Has this crowdsale been configured */ bool public configured = false; /** * Do we verify that contributor has been cleared on the server side (accredited investors only). * This method was first used in the FirstBlood crowdsale to ensure all contributors had accepted terms of sale (on the web). */ bool public requiredSignedAddress = false; /** Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */ address public signerAddress; /** How many ETH each address has invested in this crowdsale */ mapping (address => uint) public investedAmountOf; /** How many tokens this crowdsale has credited for each investor address */ mapping (address => uint) public tokenAmountOf; /** Addresses that are allowed to invest even before ICO officially opens. For testing, for ICO partners, etc. */ mapping (address => bool) public earlyParticipantWhitelist; /** State machine * * - PendingConfiguration: Crowdsale not yet configured * - Prefunding: We have not reached the starting timestamp yet * - Funding: Active crowdsale * - Success: Crowdsale ended * - Finalized: The finalize function has been called and successfully executed */ enum State{Unknown, PendingConfiguration, PreFunding, Funding, Success, Finalized} // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); // The rules about what kind of investments we accept were changed event InvestmentPolicyChanged(bool requireCId, bool requireSignedAddress, address signer); // Address early participation whitelist status changed event Whitelisted(address addr, bool status); // Crowdsale&#39;s finalize function has been called event Finalized(); /* * The configuration from the constructor was moved to the configurationGenericCrowdsale function. * * @param team_multisig Address of the multisignature wallet of the team that will receive all the funds contributed in the crowdsale. * @param start Timestamp where the crowdsale will be officially started. It should be greater than the timestamp in which the contract is deployed. * @param end Timestamp where the crowdsale finishes. No tokens can be sold through this contract after this timestamp. * * configurationGenericCrowdsale can only be called when in State.PendingConfiguration because of the inState modifier. */ function configurationGenericCrowdsale(address team_multisig, uint start, uint end) internal inState(State.PendingConfiguration) { setMultisig(team_multisig); // Don&#39;t mess the dates require(start != 0 && end != 0); require(now < start && start < end); startsAt = start; endsAt = end; configured = true; } /** * Default fallback behaviour is to call buy. * Ideally, no contract calls this crowdsale without supporting ERC20. * However, some sort of refunding function may be desired to cover such situations. */ function() payable public { buy(); } /** * Make an investment. * * The crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * @param customerId (optional) UUID v4 to track the successful payments on the server side * */ function investInternal(address receiver, uint128 customerId) stopInEmergency notFinished private { // Determine if it&#39;s a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit require(earlyParticipantWhitelist[msg.sender]); } uint weiAmount; uint tokenAmount; (weiAmount, tokenAmount) = calculateTokenAmount(msg.value, receiver); // Sanity check against bad implementation. assert(weiAmount <= msg.value); // Dust transaction if no tokens can be given require(tokenAmount != 0); if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } updateInvestorFunds(tokenAmount, weiAmount, receiver, customerId); // Pocket the money multisigWallet.transfer(weiAmount); // Return excess of money returnExcedent(msg.value.sub(weiAmount), msg.sender); } /** * Preallocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * No money is exchanged, as the crowdsale team already have received the payment. * * @param receiver Account that receives the tokens. * @param fullTokens tokens as full tokens - decimal places are added internally. * @param weiPrice Price of a single indivisible token in wei. * */ function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner notFinished { require(receiver != address(0)); uint tokenAmount = fullTokens.mul(10**uint(token.decimals())); require(tokenAmount != 0); uint weiAmount = weiPrice.mul(tokenAmount); // This can also be 0, in which case we give out tokens for free updateInvestorFunds(tokenAmount, weiAmount, receiver , 0); } /** * Private function to update accounting in the crowdsale. */ function updateInvestorFunds(uint tokenAmount, uint weiAmount, address receiver, uint128 customerId) private { // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount); // Update totals weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); assignTokens(receiver, tokenAmount); // Tell us that the investment was completed successfully Invested(receiver, weiAmount, tokenAmount, customerId); } /** * Investing function that recognizes the receiver and verifies he is allowed to invest. * * @param customerId UUIDv4 that identifies this contributor */ function buyOnBehalfWithSignedAddress(address receiver, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable validCustomerId(customerId) { bytes32 hash = sha256(receiver); require(ecrecover(hash, v, r, s) == signerAddress); investInternal(receiver, customerId); } /** * Investing function that recognizes the receiver. * * @param customerId UUIDv4 that identifies this contributor */ function buyOnBehalfWithCustomerId(address receiver, uint128 customerId) public payable validCustomerId(customerId) unsignedBuyAllowed { investInternal(receiver, customerId); } /** * Buys tokens on behalf of an address. * * Pay for funding, get invested tokens back in the receiver address. */ function buyOnBehalf(address receiver) public payable unsignedBuyAllowed { require(!requireCustomerId); // Crowdsale needs to track participants for thank you email investInternal(receiver, 0); } /** * Investing function that recognizes the payer and verifies he is allowed to invest. * * @param customerId UUIDv4 that identifies this contributor */ function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { buyOnBehalfWithSignedAddress(msg.sender, customerId, v, r, s); } /** * Investing function that recognizes the payer. * * @param customerId UUIDv4 that identifies this contributor */ function buyWithCustomerId(uint128 customerId) public payable { buyOnBehalfWithCustomerId(msg.sender, customerId); } /** * The basic entry point to participate in the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { buyOnBehalf(msg.sender); } /** * Finalize a successful crowdsale. * * The owner can trigger post-crowdsale actions, like releasing the tokens. * Note that by default tokens are not in a released state. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { finalized = true; Finalized(); } /** * Set policy do we need to have server-side customer ids for the investments. * */ function setRequireCustomerId(bool value) public onlyOwner { requireCustomerId = value; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } /** * Set policy if all investors must be cleared on the server side first. * * This is e.g. for the accredited investor clearing. * */ function setRequireSignedAddress(bool value, address signer) public onlyOwner { requiredSignedAddress = value; signerAddress = signer; InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress); } /** * Allow addresses to do early participation. */ function setEarlyParticipantWhitelist(address addr, bool status) public onlyOwner notFinished stopInEmergency { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } /** * Internal setter for the multisig wallet */ function setMultisig(address addr) internal { require(addr != 0); multisigWallet = addr; } /** * Crowdfund state machine management. * * This function has the timed transition builtin. * So there is no chance of the variable being stale. */ function getState() public view returns (State) { if (finalized) return State.Finalized; else if (!configured) return State.PendingConfiguration; else if (now < startsAt) return State.PreFunding; else if (now <= endsAt && !isCrowdsaleFull()) return State.Funding; else return State.Success; } /** Internal functions that exist to provide inversion of control should they be overriden */ /** Interface for the concrete instance to interact with the token contract in a customizable way */ function assignTokens(address receiver, uint tokenAmount) internal; /** * Determine if the goal was already reached in the current crowdsale */ function isCrowdsaleFull() internal view returns (bool full); /** * Returns any excess wei received * * This function can be overriden to provide a different refunding method. */ function returnExcedent(uint excedent, address receiver) internal { if (excedent > 0) { receiver.transfer(excedent); } } /** * Calculate the amount of tokens that corresponds to the received amount. * The wei amount is returned too in case not all of it can be invested. * * Note: When there&#39;s an excedent due to rounding error, it should be returned to allow refunding. * This is worked around in the current design using an appropriate amount of decimals in the FractionalERC20 standard. * The workaround is good enough for most use cases, hence the simplified function signature. * @return weiAllowed The amount of wei accepted in this transaction. * @return tokenAmount The tokens that are assigned to the receiver in this transaction. */ function calculateTokenAmount(uint weiAmount, address receiver) internal view returns (uint weiAllowed, uint tokenAmount); // // Modifiers // modifier inState(State state) { require(getState() == state); _; } modifier unsignedBuyAllowed() { require(!requiredSignedAddress); _; } /** Modifier allowing execution only if the crowdsale is currently running. */ modifier notFinished() { State current_state = getState(); require(current_state == State.PreFunding || current_state == State.Funding); _; } modifier validCustomerId(uint128 customerId) { require(customerId != 0); // UUIDv4 sanity check _; } } pragma solidity ^0.4.19; // Simple deployment information store inside contract storage. contract DeploymentInfo { uint private deployed_on; function DeploymentInfo() public { deployed_on = block.number; } function getDeploymentBlock() public view returns (uint) { return deployed_on; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * * Heavily modified by https://www.coinfabrik.com/ */ pragma solidity ^0.4.19; /// @dev Tranche based pricing. /// Implementing "first price" tranches, meaning, that if a buyer&#39;s order is /// covering more than one tranche, the price of the lowest tranche will apply /// to the whole order. contract TokenTranchePricing { using SafeMath for uint; /** * Define pricing schedule using tranches. */ struct Tranche { // Amount in tokens when this tranche becomes inactive uint amount; // Timestamp interval [start, end) // Starting timestamp (included in the interval) uint start; // Ending timestamp (excluded from the interval) uint end; // How many tokens per wei you will get while this tranche is active uint price; } // We define offsets and size for the deserialization of ordered tuples in raw arrays uint private constant amount_offset = 0; uint private constant start_offset = 1; uint private constant end_offset = 2; uint private constant price_offset = 3; uint private constant tranche_size = 4; Tranche[] public tranches; function getTranchesLength() public view returns (uint) { return tranches.length; } // The configuration from the constructor was moved to the configurationTokenTranchePricing function. // /// @dev Construction, creating a list of tranches /* @param init_tranches Raw array of ordered tuples: (start amount, start timestamp, end timestamp, price) */ // function configurationTokenTranchePricing(uint[] init_tranches) internal { // Need to have tuples, length check require(init_tranches.length % tranche_size == 0); // A tranche with amount zero can never be selected and is therefore useless. // This check and the one inside the loop ensure no tranche can have an amount equal to zero. require(init_tranches[amount_offset] > 0); uint input_tranches_length = init_tranches.length.div(tranche_size); Tranche memory last_tranche; for (uint i = 0; i < input_tranches_length; i++) { uint tranche_offset = i.mul(tranche_size); uint amount = init_tranches[tranche_offset.add(amount_offset)]; uint start = init_tranches[tranche_offset.add(start_offset)]; uint end = init_tranches[tranche_offset.add(end_offset)]; uint price = init_tranches[tranche_offset.add(price_offset)]; // No invalid steps require(start < end && now < end); // Bail out when entering unnecessary tranches // This is preferably checked before deploying contract into any blockchain. require(i == 0 || (end >= last_tranche.end && amount > last_tranche.amount) || (end > last_tranche.end && amount >= last_tranche.amount)); last_tranche = Tranche(amount, start, end, price); tranches.push(last_tranche); } } /// @dev Get the current tranche or bail out if there is no tranche defined for the current timestamp. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return Returns the struct representing the current tranche function getCurrentTranche(uint tokensSold) private view returns (Tranche storage) { for (uint i = 0; i < tranches.length; i++) { if (tranches[i].start <= now && now < tranches[i].end && tokensSold < tranches[i].amount) { return tranches[i]; } } // No tranche is currently active revert(); } /// @dev Get the current price. May revert if there is no tranche currently active. /// @param tokensSold total amount of tokens sold, for calculating the current tranche /// @return The current price function getCurrentPrice(uint tokensSold) internal view returns (uint result) { return getCurrentTranche(tokensSold).price; } } // This contract has the sole objective of providing a sane concrete instance of the Crowdsale contract. contract Crowdsale is GenericCrowdsale, LostAndFoundToken, DeploymentInfo, TokenTranchePricing { uint public sellable_tokens; uint public initial_tokens; uint public milieurs_per_eth; /* * The constructor for the crowdsale was removed given it didn&#39;t receive any arguments nor had any body. * * The configuration from the constructor was moved to the configurationCrowdsale function which creates the token contract and also calls the configuration functions from GenericCrowdsale and TokenTranchePricing. * * * @param team_multisig Address of the multisignature wallet of the team that will receive all the funds contributed in the crowdsale. * @param start Timestamp where the crowdsale will be officially started. It should be greater than the timestamp in which the contract is deployed. * @param end Timestamp where the crowdsale finishes. No tokens can be sold through this contract after this timestamp. * @param token_retriever Address that will handle tokens accidentally sent to the token contract. See the LostAndFoundToken and CrowdsaleToken contracts for further details. */ function configurationCrowdsale(address team_multisig, uint start, uint end, address token_retriever, uint[] init_tranches, uint multisig_supply, uint crowdsale_supply, uint8 token_decimals, uint max_tokens_to_sell) public onlyOwner { initial_tokens = multisig_supply; token = new CrowdsaleToken(multisig_supply, token_decimals, team_multisig, token_retriever); // Necessary if assignTokens mints token.setMintAgent(address(this), true); // Necessary if finalize is overriden to release the tokens for public trading. token.setReleaseAgent(address(this)); // Necessary for the execution of buy function and of the subsequent CrowdsaleToken&#39;s transfer function. token.setTransferAgent(address(this), true); // Crowdsale mints to himself the initial supply token.mint(address(this), crowdsale_supply); sellable_tokens = max_tokens_to_sell; // Configuration functionality for GenericCrowdsale. configurationGenericCrowdsale(team_multisig, start, end); // Configuration functionality for TokenTranchePricing. configurationTokenTranchePricing(init_tranches); } //token assignation function assignTokens(address receiver, uint tokenAmount) internal { token.transfer(receiver, tokenAmount); } //token amount calculation function calculateTokenAmount(uint weiAmount, address receiver) internal view returns (uint weiAllowed, uint tokenAmount) { uint tokensPerEth = getCurrentPrice(tokensSold).mul(milieurs_per_eth).div(1000); uint maxWeiAllowed = sellable_tokens.sub(tokensSold).mul(1 ether).div(tokensPerEth); weiAllowed = maxWeiAllowed.min256(weiAmount); require(token.balanceOf(receiver).add(weiAllowed) >= 100); if (weiAmount < maxWeiAllowed) { //Divided by 1000 because eth eth_price_in_eurs is multiplied by 1000 tokenAmount = tokensPerEth.mul(weiAmount).div(1 ether); } // With this case we let the crowdsale end even when there are rounding errors due to the tokens to wei ratio else { tokenAmount = sellable_tokens.sub(tokensSold); } } //TODO: implement to control funding state criterion function isCrowdsaleFull() internal view returns (bool full) { return tokensSold >= sellable_tokens; } /** * Finalize a successful crowdsale. * * The owner can trigger post-crowdsale actions, like releasing the tokens. * Note that by default tokens are not in a released state. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { //Tokens sold + bounties represent 75% of the total, the other 25% goes ti the multisig to the partners and to regulate market uint sold = tokensSold.add( initial_tokens); uint toShare = sold.mul(25).div(75).mul(10**uint(token.decimals())); token.setMintAgent(address(this), true); token.mint(multisigWallet, toShare); token.setMintAgent(address(this), false); token.releaseTokenTransfer(); token.burn(token.balanceOf(address(this))); super.finalize(); } /** * This function decides who handles lost tokens. * Do note that this function is NOT meant to be used in a token refund mecahnism. * Its sole purpose is determining who can move around ERC20 tokens accidentally sent to this contract. */ function getLostAndFoundMaster() internal view returns (address) { return owner; } // These two setters are present only to correct timestamps if they are off from their target date by more than, say, a day function setStartingTime(uint startingTime) public onlyOwner inState(State.PreFunding) { require(startingTime > now && startingTime < endsAt); startsAt = startingTime; } function setEndingTime(uint endingTime) public onlyOwner notFinished { require(endingTime > now && endingTime > startsAt); endsAt = endingTime; } function updateEursPerEth (uint milieurs_amount) public onlyOwner { require(milieurs_amount >= 100); milieurs_per_eth = milieurs_amount; } }
Investing function that recognizes the receiver. customerId UUIDv4 that identifies this contributor/
function buyOnBehalfWithCustomerId(address receiver, uint128 customerId) public payable validCustomerId(customerId) unsignedBuyAllowed { investInternal(receiver, customerId); }
7,800,431
./full_match/4/0xa0c032e28e06f772845B4E753aE115395c848E68/sources/contracts/ERC721Lending.sol
assuming token transfer is approved get balance that is not streamed during period, it will be returned to borrower check if lending has fees lending did not go through full period, fees percent will be lower, lets refund to lender check if fees collecting address set and lending has fees
function stopBorrowing(address tokenAddress, uint256 tokenId) public { address _borrower = lentERC721List[tokenAddress][tokenId].borrower; require(_borrower == msg.sender, 'Borrowing: Can be stopped only by active borrower'); if (lentERC721List[tokenAddress][tokenId].lenderClaimedNFT == false) { IERC721(tokenAddress).transferFrom(msg.sender, address(this), tokenId); uint256 _initialWorth = lentERC721List[tokenAddress][tokenId].initialWorth; IERC20(acceptedPayTokenAddress).transfer(_borrower, _initialWorth); lentERC721List[tokenAddress][tokenId].borrower = address(0); lentERC721List[tokenAddress][tokenId].borrowedAtTimestamp = 0; address lenderAddress = lentERC721List[tokenAddress][tokenId].lender; uint256 _sablierSalaryId = lentERC721List[tokenAddress][tokenId].sablierSalaryId; if (_sablierSalaryId != 0) { ( , , uint256 _streamSalaryAmount, , uint256 _streamStartTime, uint256 _streamStopTime, , uint256 _streamRatePerSecond ) = Sablier(sablierContractAddress).getSalary(_sablierSalaryId); int256 _balanceNotStreamed = 0; if (block.timestamp < _streamStopTime) { _balanceNotStreamed = int256(_streamSalaryAmount) - int256(SafeMath.mul(block.timestamp - _streamStartTime, _streamRatePerSecond)); } lentERC721List[tokenAddress][tokenId].sablierSalaryId = 0; uint256 _feesPercent = lentERC721List[tokenAddress][tokenId].platformFeesPercent; if (_feesPercent > 0) { _platformFeeToCollect = SafeMath.mul(SafeMath.div(_streamSalaryAmount, 100), _feesPercent); } if (_balanceNotStreamed > 0) { if (_platformFeeToCollect > 0) { uint256 _actualSalaryLenderReceives = SafeMath.sub(_streamSalaryAmount, uint256(_balanceNotStreamed)); uint256 _platformFeeToCollectUpdated = SafeMath.mul(SafeMath.div(_actualSalaryLenderReceives, 100), _feesPercent); uint256 _platformFeeToRefund = SafeMath.sub(_platformFeeToCollect, _platformFeeToCollectUpdated); _platformFeeToCollect =_platformFeeToCollectUpdated; IERC20(acceptedPayTokenAddress).transfer(lenderAddress, uint256(_platformFeeToRefund)); } } if (feesContractAddress != address(0) && _platformFeeToCollect > 0) { IERC20(acceptedPayTokenAddress).transfer(feesContractAddress, _platformFeeToCollect); } IERC20(acceptedPayTokenAddress).transfer(lenderAddress, _earningGoal); } emit ERC721ForLendUpdated(tokenAddress, tokenId); }
12,435,049
./full_match/4/0x08F83aB11F63336ad7647706705b643fD9d575BA/sources/contracts/EthProject.sol
Update Project Status based on the Project Goal and Project Expiry Date/
function _updateProjectStatus() private { if(projectBalance >= projectGoal){ projectStatus = ProjectStatus.Successful; emit ProjectSuccess(projectCreator, projectBalance); projectStatus = ProjectStatus.Expired; emit ProjectExpired(projectCreator, projectBalance); } }
12,319,514
/* Copyright 2021 Dolomite. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.7; pragma experimental ABIEncoderV2; library EnumerableSet { struct Set { // Storage of set values uint256[] _values; // Value to the index in `_values` array, plus 1 because index 0 means a value is not in the set. mapping(uint256 => uint256) _valueToIndexMap; } /** * @dev Add a value to a set. O(1). * * @return true if the value was added to the set, that is if it was not already present. */ function add(Set storage set, uint256 value) internal 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._valueToIndexMap[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * @return true if the value was removed from the set, that is if it was present. */ function remove(Set storage set, uint256 value) internal returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._valueToIndexMap[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { uint256 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._valueToIndexMap[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored, which is the last index set._values.pop(); // Delete the index for the deleted slot delete set._valueToIndexMap[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Set storage set, uint256 value) internal view returns (bool) { return set._valueToIndexMap[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(Set storage set) internal view returns (uint256) { return set._values.length; } /** * @dev Returns the value at the corresponding index. O(1). */ function getAtIndex(Set storage set, uint256 index) internal view returns (uint256) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Set storage set) internal view returns (uint256[] memory) { return set._values; } }
Returns true if the value is in the set. O(1)./
function contains(Set storage set, uint256 value) internal view returns (bool) { return set._valueToIndexMap[value] != 0; }
2,513,303
// 1.컴파일 버전에 대한 명시 // 0.4.22을 기반으로 작성되었고, 0.6.0까지 정상 작동함을 보장한다. // pragma solidity >=0.4.22 <0.6.0; pragma solidity ^0.5.7; // 2.import // 3. contract section // 3-1. type contract BasicType { function numTest() public pure returns(int, int8, uint, bool) { // 기본문장의 끝에는 ;를 반들시 붙인다 int a = 10; // 수치형 확인 // bool : true, false // int, uint : 부호가 있는 정수, 부호가 없는 정수 // int8~ : 8bit // int → int256으로 간략하게 사용 가능 int8 b=10; uint c =1; bool d = true; return (a,b,c,d); } // enum enum Level { Gold, Silver, Normal } function enumTest () public pure returns (Level, Level, Level) { Level a = Level.Gold; Level b = Level.Silver; Level c = Level.Normal; return (a, b,c); } // address : 주소형 function addrTest() public view returns (address, address, address) { /* - 20 byte 크기의 자료형 - contract의 주소, 계좌의 주소등을 담는 변수 - 함수를 가지고 있고, 송금행위등 지원 transfer(10), send(), .. */ // 주소값은 address(해쉬값) address payable x = address(0x124); // this 현 contract의 주소:자기자신 address myAddr = address(this); // msg.sender → 현 contract를 구동한자의 주소 return (x, myAddr, msg.sender); } // tuple function tupleTest() public pure returns (int, int) { /* tuple - 여러 데이터를 묶는다 - 타입이 달라도 ok - 여러 데이터를 한덩어리 묶어서 처리할때 → return */ return (1, 2); } function tupleTest2() public pure returns (int, int, int) { (int x, int y) = tupleTest(); // 그룹별 사용 (x, y) = (y, x); int c = x; return (x, y, c); } } // contract // 솔리디티 관점에서 컨트랙트는 많은함수(코드)와 // 데이터(상태)가 이더리움 블록체인 네트워크상에 // 특정 주소로 존재하는것 contract ContractIs { // 변수의 저장 위치 // 1. storage : 상태변수, 함수내 지역변수 // 2. memory: 함수의 매개변수, 함수의 리턴값 // 3. callback : memory와 유사하나 external을 사용 매개변수쪽에 사용 // 스토리지 공간인데 memory를 써서 명시적으로 저장 공간을 바꿀수 있다. // 상태변수 int a = 10; // 함수 function main() public view returns (int, int) { // 지역변수 int b = a; return (b, a); } // 생성자 constructor (int _a) public { a = _a; } } // getter, setter contract GetSetIs { uint private data; // getter, setter 사용 function setData( uint a) public {data =a;} // 상태변수를 함수 내부에서 읽겠다면 view 키워드 추가 function getData() public view returns(uint) { return data; } } contract GetSetIsTest { function main() public returns (uint) { // contract create GetSetIs gs = new GetSetIs(); gs.setData(3); return gs.getData(); } } // function contract FuncIs { /* - 구조 function 함수명 [] [] returns () {} function 함수명 [ (가시성: visablity) external : contract상에서 명시된것만 외부에 공개 public : 모든 contract의 내부, 외부에 공개 internal : 해당 contract와 상속된 contract에만 공개 private : 오직 해당 contract 계정에만 공개 ] [ (옵션:option) (구버전 contant → view, pure → gas 발생이 안된다) view : 열거하는 내용이 해당 함수에는 없어야 한다. - 상태변수 값 변경 - 이벤트 발생 - 다른 contract 생성 - ether 전송 - view난 pure로 선언되지 않은 함수를 호출 - 인라인 어셈블 사용 pure : 열거하는 내용이 해당 함수에는 없어야 한다. - 상태변수 읽기 - xx.balance 접근 시도 - contract 기본 멤버 변수 (msg, tx, block, ...) 접근 행위 - pure로 정의되어 있지 않는 함수 호출 - 인라인 어셈블 사용 payable : contract가 자신의 함수를 통해 다름 지갑, 다른 contract에 ether를 송금받는 행위등등 → 함수자체가 지불 가능한 상태로 제작하는 경우 ] returns ( 타입 or 타입 변수명 ) { statement; // 리턴값이 존재하면 return 값; or return (값, 값); } */ int age = 1; // 해당 함수의 가시성은 생략하면 public에 대한 가시시성 // 부분에 불명확해짐으로 표시 // 코드 자체를 살펴보니 상태변수를 읽기만 할뿐 // 뭔가 값을 변경하거나 하는 행위가 없어서 // 비용이 발생될만한 소지가 없으니 view를 넣어서 // 처리를 해라 function t() public view returns (int) { return age; } function t2() public view returns (int) { // age++; //상태변수 변경시도 return age; } // remove view function t3() public returns (int) { age++; return age; } function t4() public pure returns (int) { // return age; //상태변수를 읽으려고 했다. return 10; } // return ========================================= // 리턴되는 값이 타입을 명시 function add(uint x, uint y) public pure returns (uint) { uint results = x + y; return results; } // 리턴되는 값의 타입과 변수명 명시 function add2(uint x, uint y) public pure returns (uint results) { // 해당 변수는 이미 타입이 정해져 있으르로 사용시 타입을 명시 하지 않는다. results = x + y; return results; } function a() external pure { } function b() private pure { } /* 함수 구현은 - 기능을 먼저 구현하고 - 다루는 데이터(조건)에 따라 옵션조건 부여 - 비용적인 측면, 사용되는 가시성 측면 고려 - 함수의 정의를 계속 수정 */ } // 생성자 테스트 contract ContractShape { uint cnt; address from; address to; // 생성자 constructor (uint _cnt, address _from, address _to) public { cnt = _cnt; from = _from; to = _to; } function checkCnt() public view returns (uint) { return cnt; } } contract ContractShapeTest { // contract 생성을 상태변수 진행 : ok ContractShape cs = new ContractShape(10, address(0xFF), address(0xAB)); function log() public view returns (uint) { return cs.checkCnt(); } } // 조건문, 반복문, 제어문 contract CondiLoopTest { /* - 조건문, 반복문, 제어문 - 기존언어 자바계열과 크게 다르지 않다 - if, for, while, do~wihile, break, continue - 삼항 연산자 */ function getCoffePriceCheck(uint price) public pure returns(int8) { if (price > 1500) return 1; else if (price < 1500) return -1; else return 0; } // 삼항 연산자 // 조건 ? 참이면코드 : 거짓이면 코드 function threeCheck(uint x) public pure returns (uint result) { // 리턴 형식에 변수명을 사용하면 return 생략 가능 result = x > 10 ? (x > 2 ? 11 : 1004):0; } // for // forCheck(uint value), → 누적합 : forCheck(5) → 0+1+2+3+4+5 function forCheck(uint value) public pure returns (uint result) { result = 0; for(uint i=value; i > 0; i--) result += i; } function forCheck2(uint value) public pure returns (uint sum, uint mul) { sum = 0; mul = 1; for(uint i=value; i > 0; i--) { sum += i; if(i>0) mul *= i; } } // while : 0~무한대(언제끌날지 모르겠다), do~while : 1~무한대(언제끝날지 모르겠다) function whileCheck(uint param) public pure returns(uint, uint){ (uint n, uint n2, uint i) = (0, 0, 0); while(i< param) { n += i; if(i> 10) break; i++; } i=0; do { i++; if(i%2 == 0) { continue; } if (i > 10) { break; } n2 += i; } while(i <param); return (n, n2); } } // 타입의 형변환 contract AsTypeTest { /* - 암묵적 형변환 > 작은타입 → 큰타입 - 명시적 형변환 > 큰타입 → 작은타입 */ function asType() public pure returns (uint256, int8) { uint8 a = 1; uint256 b = 1; // 암묵적 형변환 uint256 c = a; // 명시적 형변환 int8 d = int8(b); return (c, d); } } // Array contract ArrayTest { // 상태변수 → stroage // 배열선언 uint8[2] myArr1; // 배열선언 + 초기화 uint8[2] myArr2 = [1,2]; uint[] myArr3 = [1,2]; uint[] myArr4 = new uint[](2); // 복합 타입을 리턴할 경우 memory, 키워드를 같이 표방 // → 리턴하는 변수가 storage이면 리턴 불가 // → 변수가 선언될때 변수명 앞에 사용한 키워드 그대로 사용(가시성 제거) function arrTest1() public view returns (uint256, uint256[] memory) { // 지역변수 → storage // define uint8[2] memory arr4; // 지역변수에서 배열생성시 사이즈를 부여하여 값넣고 초기화 uint8[3] memory arr1 = [1,2,3]; // new를 통해서 사이즈 넣고 생성 uint8[] memory arr2 = new uint8[](arr1.length); // error // uint8[] memory arr3 = [1,2,3]; // 포인터가 대입되었다 // storage → memory에 대입하는 케이스 uint256[] memory arr5 = myArr3; return (arr5[0], arr5); } // 바이트 배열(고정, 동적) // byte, bytes(1~32) <-> byte <->string function byteTest() public pure returns(byte and_v, byte or_v, byte xor_v, byte neg_v) { // byte → 1 byte byte a = 0x00; byte b = 0xFF; // bit 연산 and_v = a & b; or_v = a | b; xor_v = a ^ b; neg_v = ~a; } // bytes : 정적 바이트 배열 function bytesTest() public pure returns (bytes2 staticBytesArr) { // bytes : 이미 선언시 고정 크기를 가진다 // error // staticBytesArr = "ABC"; staticBytesArr = "AB"; // 바이트배열을 동적으로 만들어서 제공하면 값이 사이즈를 넘는다 → 유동적 조절→ gas 발생→ 고정크기 추천 // bytes는 이미 배열이라서 [] 기호 안써도 됩니다. bytes memory dyBytestArr = new bytes(2); dyBytestArr = "AB"; // 유동적 크기변화가 발생 dyBytestArr = "ABC"; } // 정적 바이트 배열 생성 → 값부여 → 바이트 배열 카피 → 리턴 function bytesToByteArrayTest() public pure returns(byte[] memory){ // bytes → byte[] bytes memory tmp = new bytes(5); tmp = "ABCDE"; byte[] memory result = new byte[](tmp.length); // copy with for for(uint8 i = 0; i < tmp.length; i++) { result[i] = tmp[i]; } return result; } // bytes <-> string function bytesToString() public pure returns (string memory) { bytes memory tmp = new bytes(5); tmp = "ABCD가나다123!@#"; string memory s = string(tmp); return s; } } // byte <-> bytes(1~32) <-> string // string : 라이브러리 contract StringTest { // 문자열 사용간 필요한 라이브러리 정의 // 1. byteArrayToString() // 2. 입력 : byteArray // 출력 : string function byteArrayToString(byte[] memory str) public pure returns(string memory) { bytes memory strbytes = new bytes(str.length); for(uint i = 0; i < str.length; i++) { strbytes[i] = str[i]; } // string memory s = string(strbytes); // return s; return string(strbytes); } // stringToByteArray // string → bytes → byte[] // bytes(string) byte(bytes) function stringToByteArray(string memory str) public pure returns(byte[] memory) { // string → bytes bytes memory buffer = bytes(str); // bytes → byte[] byte[] memory buff = new byte[](buffer.length); for(uint i=0; i < buffer.length; i++ ){ buff[i] = byte(buffer[i]); } return buff; } function testBATS(string memory src) public pure returns(string memory) { return byteArrayToString(stringToByteArray(src)); } // 1. 문자열 더하기 addString(string, string) → string function addString(string memory str1, string memory str2) public pure returns(string memory) { // string → bytes bytes memory tmp1 = bytes(str1); bytes memory tmp2 = bytes(str2); // bytes buffer bytes memory tmp3 = new bytes(tmp1.length + tmp2.length); for(uint i=0 ;i < tmp1.length; i++) { tmp3[i] = tmp1[i]; } for(uint i=0 ;i < tmp2.length; i++) { tmp3[tmp1.length+i] = tmp2[i]; } return string(tmp3); } // 2. 문자열 자르기 subString(string, sIdx, size) → string // 한글처리는 일단배제 // 직접적용해보니 3byte로 처리가 되었다 // 인코딩(utf8 or euc-kr등 한글처리에 대한 고민) function subString(string memory str1, uint sIdx, uint size) public pure returns(string memory) { // string → bytes bytes memory tmp1 = bytes(str1); // checking sIdx + size > bytes.length → error, 원본리턴 if(sIdx + size > tmp1.length) { return str1; } // buffer create bytes memory tmp2 = new bytes(size); for(uint i=0 ;i < size; i++) { tmp2[i] = tmp1[sIdx+i]; } return string(tmp2); } } // mapping → dictionary /* 매핑 - dictionary 구조 → key, value 쌍으로 구성 - mapping ( address => uint) public balance; 키 : 모든 자료형이 가능 public getter 자동생성 */ contract MappingMod { mapping(address =>uint) public balance; function setBalance(address addr, uint value) public { balance[addr] = value; } // 내가 구동한 contract에서 다른 contract를 생성했을시 // 다른 contract의 msg.sender는 누구인가? // blance[msg.sender] = value 는 동작 하지 않는다. } contract MappingTest { MappingMod mm = new MappingMod(); function test(uint value) public returns(uint) { // 매핑 변수에 값 설정 mm.setBalance(msg.sender, value); // 매핑 변수에서 데이터 힉득 // 변수(키) return mm.balance(msg.sender); } } // struct // 구조체 반환시 pragma experimental ABIEncoderV2; contract StructTest { /* 구조체 - 사용자 정의 타입 - 어떤 타입도 맴버로 담을 수 있다 - 매핑의 키로 사용은 불가 - 구조체는 스토리지에 저장 - 원본 주의(자기 참조시) → depth 제한 : 3 depth 구조체 3depth mapping의 값으로 사용시 2depth */ // define struct person { uint32 birth; bool isMale; } struct player { person p; uint8 team; uint8[2] points; } mapping (address=>player) players; // create player p1 = player( person(990919, true), 10, [90, 80]); constructor() public { // 매핑에 데이터 추가 players[ msg.sender ] = p1; } // getPlayer() => player function getPlayer() public view returns(player memory) { return players[msg.sender]; } // player's mean function getPlayerMean() public view returns(uint) { uint sum = players[msg.sender].points[0] + players[msg.sender].points[1]; uint mean = uint( sum / players[msg.sender].points.length); return mean; } // 매핑, 배열구조로 사용이 가능하나 depth 제한 // B tree : 자기 자신을 자식으로 3번 struct caseA { uint a; caseA[] b; } // binary tree :자기자신을 자식으로 2개 struct caseB { uint a; mapping(bool => caseB) b; } } // 상속, 추상, 인터페이스 /* 상속 - contract 상속 - 부모의 맴버를 그대로 사용 - 자식은 재정의, 추가 가능 - 인터페이스, 추상 */ contract A { function f() public pure returns (uint) { return 10; } } contract B { function f() public pure returns (uint) { return 20; } function f2() public pure returns (uint) { return 30; } } // 상속 // 부모들이 함수명이 동일하면 // 나중에 상속받은 소속 함수가 최종 contract C is A, B {} contract D is B, A {} contract E is B, A { // override function f() public pure returns(uint) { return 1004; } } /* 추상 컨트랙트 - contract 내부가 함수 선언만 but 구현된 함수도 포함 ok - 스스로 생성 불가 - 틀이라는 형태로 많이 사용 */ contract Form { function eat(string memory food) public pure returns(bool); function f() public pure returns (uint) { return 11; } } contract F { function f() public pure returns (uint) { return 50; } } contract G is F, Form { // 추상화된 함수를 구현 function eat(string memory food) public pure returns(bool) { return true; } } // 인터페이스 interface Form2 { // 함수들은 external로 선언되어야 한다. function eat2(string calldata food) external pure returns(bool); } contract H is F, Form2 { function eat2(string calldata food) external pure returns(bool) { return true; } } // event(contract에서 이벤트를 발생 → 예를 들면 NODE 전달) /* 이벤트 - 함수 실행 중간에 이벤트를 발생시켜 - 특정 데이터를 외부(web3사용하는)로 전달하는 역할 - javascript에서는 콜백함수를 통해서 전달 - 비동기 */ contract EventTest { event myEvent ( address _from, address _to, uint _amt ); // 비동기 상황이 존재했고 function pay(address _to) public payable { // 예를 들어 송금하는 행위는 비동기식이여서 리턴을 잡아주면 블럭이 발생 // 이벤트를 발생 → 이벤트가 전달되면 그때 따음 스텝 처리 emit myEvent(msg.sender, _to, msg.value); } } // library /* 라이브러리 - 특정 주소에 한번 배포되면, 다양한 contract들이 재사용 가능 - 라이브러리 함수가 호출되면 호출한 contract에서 실행 - contract는 라이브러리의 저장소(스토리지)접근 가능 - 라이브러리는 상태변수를 가질수 없고, 상속 미지원, 이더도 받을 수 없다. */ library math { function addInt(int a, int b) public pure returns (int c) { return a + b; } } library math2 { // 라이브러리는 상태변수를 가질수 없고 → 우회적으로 해결 struct m1Struct { int a; } struct m2Struct { int a; } function addInt (m1Struct storage s, int value) public view returns(int c) { return s.a + value; } function mulInt (m2Struct storage s, int value) public view returns(int c) { return s.a * value; } } contract LibTest { using math2 for *; math2.m1Struct m1; math2.m2Struct m2; function test() public returns (int, int, int) { m1 = math2.m1Struct(10); m2 = math2.m2Struct(5); return (math.addInt(1,2), m1.addInt(10), m2.mulInt(2)); } }
지역변수 → storage define 지역변수에서 배열생성시 사이즈를 부여하여 값넣고 초기화 new를 통해서 사이즈 넣고 생성 error uint8[] memory arr3 = [1,2,3]; 포인터가 대입되었다 storage → memory에 대입하는 케이스
function arrTest1() public view returns (uint256, uint256[] memory) { uint8[2] memory arr4; uint8[3] memory arr1 = [1,2,3]; uint8[] memory arr2 = new uint8[](arr1.length); uint256[] memory arr5 = myArr3; return (arr5[0], arr5); }
12,557,027
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // 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.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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: 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) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) { if (_y > 3) { z_ = _y; uint256 x = _y / 2 + 1; while (x < z_) { z_ = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z_ = 1; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.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 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
Get a list of enabled policies for a given fund _comptrollerProxy The ComptrollerProxy of the fund return enabledPolicies_ An array of enabled policy addresses
function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } }
1,696,706
pragma solidity ^0.4.24; // 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 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. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/controller/Reputation.sol /** * @title Reputation system * @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust . * A reputation is use to assign influence measure to a DAO'S peers. * Reputation is similar to regular tokens but with one crucial difference: It is non-transferable. * The Reputation contract maintain a map of address to reputation value. * It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address. */ contract Reputation is Ownable { using SafeMath for uint; mapping (address => uint256) public balances; uint256 public totalSupply; uint public decimals = 18; // Event indicating minting of reputation to an address. event Mint(address indexed _to, uint256 _amount); // Event indicating burning of reputation for an address. event Burn(address indexed _from, uint256 _amount); /** * @dev return the reputation amount of a given owner * @param _owner an address of the owner which we want to get his reputation */ function reputationOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Generates `_amount` of reputation that are assigned to `_to` * @param _to The address that will be assigned the new reputation * @param _amount The quantity of reputation to be generated * @return True if the reputation are generated correctly */ function mint(address _to, uint _amount) public onlyOwner returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } /** * @dev Burns `_amount` of reputation from `_from` * if _amount tokens to burn > balances[_from] the balance of _from will turn to zero. * @param _from The address that will lose the reputation * @param _amount The quantity of reputation to burn * @return True if the reputation are burned correctly */ function burn(address _from, uint _amount) public onlyOwner returns (bool) { uint amountMinted = _amount; if (balances[_from] < _amount) { amountMinted = balances[_from]; } totalSupply = totalSupply.sub(amountMinted); balances[_from] = balances[_from].sub(amountMinted); emit Burn(_from, amountMinted); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: openzeppelin-solidity/contracts/token/ERC827/ERC827.sol /** * @title ERC827 interface, an extension of ERC20 token standard * * @dev Interface of a ERC827 token, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. */ contract ERC827 is ERC20 { function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable returns (bool); function transferAndCall( address _to, uint256 _value, bytes _data ) public payable returns (bool); function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC827/ERC827Token.sol /* solium-disable security/no-low-level-calls */ pragma solidity ^0.4.23; /** * @title ERC827, an extension of ERC20 token standard * * @dev Implementation the ERC827, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. * * @dev Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** * @dev Addition to ERC20 token methods. It allows to * @dev approve the transfer of value and execute a call with the sent data. * * @dev Beware that changing an allowance with this method brings the risk that * @dev someone may use both the old and the new allowance by unfortunate * @dev transaction ordering. One possible solution to mitigate this race condition * @dev is to first reduce the spender's allowance to 0 and set the desired value * @dev afterwards: * @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @param _spender The address that will spend the funds. * @param _value The amount of tokens to be spent. * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens to a specified * @dev address and execute a call with the sent data on the same transaction * * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferAndCall( address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transfer(_to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens from one address to * @dev another and make a contract call on the same transaction * * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amout of tokens to be transferred * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To increment * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApprovalAndCall( address _spender, uint _addedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To decrement * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApprovalAndCall( address _spender, uint _subtractedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } } // File: contracts/controller/DAOToken.sol /** * @title DAOToken, base on zeppelin contract. * @dev ERC20 compatible token. It is a mintable, destructible, burnable token. */ contract DAOToken is ERC827Token,MintableToken,BurnableToken { string public name; string public symbol; // solium-disable-next-line uppercase uint8 public constant decimals = 18; uint public cap; /** * @dev Constructor * @param _name - token name * @param _symbol - token symbol * @param _cap - token cap - 0 value means no cap */ constructor(string _name, string _symbol,uint _cap) public { name = _name; symbol = _symbol; cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { if (cap > 0) require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/controller/Avatar.sol /** * @title An Avatar holds tokens, reputation and ether for a controller */ contract Avatar is Ownable { bytes32 public orgName; DAOToken public nativeToken; Reputation public nativeReputation; event GenericAction(address indexed _action, bytes32[] _params); event SendEther(uint _amountInWei, address indexed _to); event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint _value); event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint _value); event ExternalTokenIncreaseApproval(StandardToken indexed _externalToken, address _spender, uint _addedValue); event ExternalTokenDecreaseApproval(StandardToken indexed _externalToken, address _spender, uint _subtractedValue); event ReceiveEther(address indexed _sender, uint _value); /** * @dev the constructor takes organization name, native token and reputation system and creates an avatar for a controller */ constructor(bytes32 _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } /** * @dev enables an avatar to receive ethers */ function() public payable { emit ReceiveEther(msg.sender, msg.value); } /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @return the return bytes of the called contract's function. */ function genericCall(address _contract,bytes _data) public onlyOwner { // solium-disable-next-line security/no-low-level-calls bool result = _contract.call(_data); // solium-disable-next-line security/no-inline-assembly assembly { // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // call returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev send ethers from the avatar's wallet * @param _amountInWei amount to send in Wei units * @param _to send the ethers to this address * @return bool which represents success */ function sendEther(uint _amountInWei, address _to) public onlyOwner returns(bool) { _to.transfer(_amountInWei); emit SendEther(_amountInWei, _to); return true; } /** * @dev external token transfer * @param _externalToken the token contract * @param _to the destination address * @param _value the amount of tokens to transfer * @return bool which represents success */ function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value) public onlyOwner returns(bool) { _externalToken.transfer(_to, _value); emit ExternalTokenTransfer(_externalToken, _to, _value); return true; } /** * @dev external token transfer from a specific account * @param _externalToken the token contract * @param _from the account to spend token from * @param _to the destination address * @param _value the amount of tokens to transfer * @return bool which represents success */ function externalTokenTransferFrom( StandardToken _externalToken, address _from, address _to, uint _value ) public onlyOwner returns(bool) { _externalToken.transferFrom(_from, _to, _value); emit ExternalTokenTransferFrom(_externalToken, _from, _to, _value); return true; } /** * @dev increase approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _addedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue) public onlyOwner returns(bool) { _externalToken.increaseApproval(_spender, _addedValue); emit ExternalTokenIncreaseApproval(_externalToken, _spender, _addedValue); return true; } /** * @dev decrease approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _subtractedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue ) public onlyOwner returns(bool) { _externalToken.decreaseApproval(_spender, _subtractedValue); emit ExternalTokenDecreaseApproval(_externalToken,_spender, _subtractedValue); return true; } } // File: contracts/globalConstraints/GlobalConstraintInterface.sol contract GlobalConstraintInterface { enum CallPhase { Pre, Post,PreAndPost } function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); /** * @dev when return if this globalConstraints is pre, post or both. * @return CallPhase enum indication Pre, Post or PreAndPost. */ function when() public returns(CallPhase); } // File: contracts/controller/ControllerInterface.sol /** * @title Controller contract * @dev A controller controls the organizations tokens ,reputation and avatar. * It is subject to a set of schemes and constraints that determine its behavior. * Each scheme has it own parameters and operation permissions. */ interface ControllerInterface { /** * @dev Mint `_amount` of reputation that are assigned to `_to` . * @param _amount amount of reputation to mint * @param _to beneficiary address * @return bool which represents a success */ function mintReputation(uint256 _amount, address _to,address _avatar) external returns(bool); /** * @dev Burns `_amount` of reputation from `_from` * @param _amount amount of reputation to burn * @param _from The address that will lose the reputation * @return bool which represents a success */ function burnReputation(uint256 _amount, address _from,address _avatar) external returns(bool); /** * @dev mint tokens . * @param _amount amount of token to mint * @param _beneficiary beneficiary address * @param _avatar address * @return bool which represents a success */ function mintTokens(uint256 _amount, address _beneficiary,address _avatar) external returns(bool); /** * @dev register or update a scheme * @param _scheme the address of the scheme * @param _paramsHash a hashed configuration of the usage of the scheme * @param _permissions the permissions the new scheme will have * @param _avatar address * @return bool which represents a success */ function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar) external returns(bool); /** * @dev unregister a scheme * @param _avatar address * @param _scheme the address of the scheme * @return bool which represents a success */ function unregisterScheme(address _scheme,address _avatar) external returns(bool); /** * @dev unregister the caller's scheme * @param _avatar address * @return bool which represents a success */ function unregisterSelf(address _avatar) external returns(bool); function isSchemeRegistered( address _scheme,address _avatar) external view returns(bool); function getSchemeParameters(address _scheme,address _avatar) external view returns(bytes32); function getGlobalConstraintParameters(address _globalConstraint,address _avatar) external view returns(bytes32); function getSchemePermissions(address _scheme,address _avatar) external view returns(bytes4); /** * @dev globalConstraintsCount return the global constraint pre and post count * @return uint globalConstraintsPre count. * @return uint globalConstraintsPost count. */ function globalConstraintsCount(address _avatar) external view returns(uint,uint); function isGlobalConstraintRegistered(address _globalConstraint,address _avatar) external view returns(bool); /** * @dev add or update Global Constraint * @param _globalConstraint the address of the global constraint to be added. * @param _params the constraint parameters hash. * @param _avatar the avatar of the organization * @return bool which represents a success */ function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar) external returns(bool); /** * @dev remove Global Constraint * @param _globalConstraint the address of the global constraint to be remove. * @param _avatar the organization avatar. * @return bool which represents a success */ function removeGlobalConstraint (address _globalConstraint,address _avatar) external returns(bool); /** * @dev upgrade the Controller * The function will trigger an event 'UpgradeController'. * @param _newController the address of the new controller. * @param _avatar address * @return bool which represents a success */ function upgradeController(address _newController,address _avatar) external returns(bool); /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @param _avatar the controller's avatar address * @return bytes32 - the return value of the called _contract's function. */ function genericCall(address _contract,bytes _data,address _avatar) external returns(bytes32); /** * @dev send some ether * @param _amountInWei the amount of ether (in Wei) to send * @param _to address of the beneficiary * @param _avatar address * @return bool which represents a success */ function sendEther(uint _amountInWei, address _to,address _avatar) external returns(bool); /** * @dev send some amount of arbitrary ERC20 Tokens * @param _externalToken the address of the Token Contract * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @param _avatar address * @return bool which represents a success */ function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar) external returns(bool); /** * @dev transfer token "from" address "to" address * One must to approve the amount of tokens which can be spend from the * "from" account.This can be done using externalTokenApprove. * @param _externalToken the address of the Token Contract * @param _from address of the account to send from * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @param _avatar address * @return bool which represents a success */ function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar) external returns(bool); /** * @dev increase approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _addedValue the amount of ether (in Wei) which the approval is referring to. * @param _avatar address * @return bool which represents a success */ function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar) external returns(bool); /** * @dev decrease approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _subtractedValue the amount of ether (in Wei) which the approval is referring to. * @param _avatar address * @return bool which represents a success */ function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar) external returns(bool); /** * @dev getNativeReputation * @param _avatar the organization avatar. * @return organization native reputation */ function getNativeReputation(address _avatar) external view returns(address); } // File: contracts/controller/Controller.sol /** * @title Controller contract * @dev A controller controls the organizations tokens,reputation and avatar. * It is subject to a set of schemes and constraints that determine its behavior. * Each scheme has it own parameters and operation permissions. */ contract Controller is ControllerInterface { struct Scheme { bytes32 paramsHash; // a hash "configuration" of the scheme bytes4 permissions; // A bitwise flags of permissions, // All 0: Not registered, // 1st bit: Flag if the scheme is registered, // 2nd bit: Scheme can register other schemes // 3rd bit: Scheme can add/remove global constraints // 4th bit: Scheme can upgrade the controller // 5th bit: Scheme can call genericCall on behalf of // the organization avatar } struct GlobalConstraint { address gcAddress; bytes32 params; } struct GlobalConstraintRegister { bool isRegistered; //is registered uint index; //index at globalConstraints } mapping(address=>Scheme) public schemes; Avatar public avatar; DAOToken public nativeToken; Reputation public nativeReputation; // newController will point to the new controller after the present controller is upgraded address public newController; // globalConstraintsPre that determine pre conditions for all actions on the controller GlobalConstraint[] public globalConstraintsPre; // globalConstraintsPost that determine post conditions for all actions on the controller GlobalConstraint[] public globalConstraintsPost; // globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre; // globalConstraintsRegisterPost indicate if a globalConstraints is registered as a post global constraint mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost; event MintReputation (address indexed _sender, address indexed _to, uint256 _amount); event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount); event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount); event RegisterScheme (address indexed _sender, address indexed _scheme); event UnregisterScheme (address indexed _sender, address indexed _scheme); event GenericAction (address indexed _sender, bytes32[] _params); event SendEther (address indexed _sender, uint _amountInWei, address indexed _to); event ExternalTokenTransfer (address indexed _sender, address indexed _externalToken, address indexed _to, uint _value); event ExternalTokenTransferFrom (address indexed _sender, address indexed _externalToken, address _from, address _to, uint _value); event ExternalTokenIncreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value); event ExternalTokenDecreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value); event UpgradeController(address indexed _oldController,address _newController); event AddGlobalConstraint(address indexed _globalConstraint, bytes32 _params,GlobalConstraintInterface.CallPhase _when); event RemoveGlobalConstraint(address indexed _globalConstraint ,uint256 _index,bool _isPre); event GenericCall(address indexed _contract,bytes _data); constructor( Avatar _avatar) public { avatar = _avatar; nativeToken = avatar.nativeToken(); nativeReputation = avatar.nativeReputation(); schemes[msg.sender] = Scheme({paramsHash: bytes32(0),permissions: bytes4(0x1F)}); } // Do not allow mistaken calls: function() external { revert(); } // Modifiers: modifier onlyRegisteredScheme() { require(schemes[msg.sender].permissions&bytes4(1) == bytes4(1)); _; } modifier onlyRegisteringSchemes() { require(schemes[msg.sender].permissions&bytes4(2) == bytes4(2)); _; } modifier onlyGlobalConstraintsScheme() { require(schemes[msg.sender].permissions&bytes4(4) == bytes4(4)); _; } modifier onlyUpgradingScheme() { require(schemes[msg.sender].permissions&bytes4(8) == bytes4(8)); _; } modifier onlyGenericCallScheme() { require(schemes[msg.sender].permissions&bytes4(16) == bytes4(16)); _; } modifier onlySubjectToConstraint(bytes32 func) { uint idx; for (idx = 0;idx<globalConstraintsPre.length;idx++) { require((GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)).pre(msg.sender,globalConstraintsPre[idx].params,func)); } _; for (idx = 0;idx<globalConstraintsPost.length;idx++) { require((GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)).post(msg.sender,globalConstraintsPost[idx].params,func)); } } modifier isAvatarValid(address _avatar) { require(_avatar == address(avatar)); _; } /** * @dev Mint `_amount` of reputation that are assigned to `_to` . * @param _amount amount of reputation to mint * @param _to beneficiary address * @return bool which represents a success */ function mintReputation(uint256 _amount, address _to,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintReputation") isAvatarValid(_avatar) returns(bool) { emit MintReputation(msg.sender, _to, _amount); return nativeReputation.mint(_to, _amount); } /** * @dev Burns `_amount` of reputation from `_from` * @param _amount amount of reputation to burn * @param _from The address that will lose the reputation * @return bool which represents a success */ function burnReputation(uint256 _amount, address _from,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("burnReputation") isAvatarValid(_avatar) returns(bool) { emit BurnReputation(msg.sender, _from, _amount); return nativeReputation.burn(_from, _amount); } /** * @dev mint tokens . * @param _amount amount of token to mint * @param _beneficiary beneficiary address * @return bool which represents a success */ function mintTokens(uint256 _amount, address _beneficiary,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintTokens") isAvatarValid(_avatar) returns(bool) { emit MintTokens(msg.sender, _beneficiary, _amount); return nativeToken.mint(_beneficiary, _amount); } /** * @dev register a scheme * @param _scheme the address of the scheme * @param _paramsHash a hashed configuration of the usage of the scheme * @param _permissions the permissions the new scheme will have * @return bool which represents a success */ function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("registerScheme") isAvatarValid(_avatar) returns(bool) { Scheme memory scheme = schemes[_scheme]; // Check scheme has at least the permissions it is changing, and at least the current permissions: // Implementation is a bit messy. One must recall logic-circuits ^^ // produces non-zero if sender does not have all of the perms that are changing between old and new require(bytes4(0x1F)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0)); // produces non-zero if sender does not have all of the perms in the old scheme require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); // Add or change the scheme: schemes[_scheme].paramsHash = _paramsHash; schemes[_scheme].permissions = _permissions|bytes4(1); emit RegisterScheme(msg.sender, _scheme); return true; } /** * @dev unregister a scheme * @param _scheme the address of the scheme * @return bool which represents a success */ function unregisterScheme( address _scheme,address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("unregisterScheme") isAvatarValid(_avatar) returns(bool) { //check if the scheme is registered if (schemes[_scheme].permissions&bytes4(1) == bytes4(0)) { return false; } // Check the unregistering scheme has enough permissions: require(bytes4(0x1F)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); // Unregister: emit UnregisterScheme(msg.sender, _scheme); delete schemes[_scheme]; return true; } /** * @dev unregister the caller's scheme * @return bool which represents a success */ function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(msg.sender,_avatar) == false) { return false; } delete schemes[msg.sender]; emit UnregisterScheme(msg.sender, msg.sender); return true; } function isSchemeRegistered(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bool) { return _isSchemeRegistered(_scheme,_avatar); } function getSchemeParameters(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes32) { return schemes[_scheme].paramsHash; } function getSchemePermissions(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes4) { return schemes[_scheme].permissions; } function getGlobalConstraintParameters(address _globalConstraint,address) external view returns(bytes32) { GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPre[register.index].params; } register = globalConstraintsRegisterPost[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPost[register.index].params; } } /** * @dev globalConstraintsCount return the global constraint pre and post count * @return uint globalConstraintsPre count. * @return uint globalConstraintsPost count. */ function globalConstraintsCount(address _avatar) external isAvatarValid(_avatar) view returns(uint,uint) { return (globalConstraintsPre.length,globalConstraintsPost.length); } function isGlobalConstraintRegistered(address _globalConstraint,address _avatar) external isAvatarValid(_avatar) view returns(bool) { return (globalConstraintsRegisterPre[_globalConstraint].isRegistered || globalConstraintsRegisterPost[_globalConstraint].isRegistered); } /** * @dev add or update Global Constraint * @param _globalConstraint the address of the global constraint to be added. * @param _params the constraint parameters hash. * @return bool which represents a success */ function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint,_params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPre.length-1); }else { globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint,_params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPost.length-1); }else { globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params,when); return true; } /** * @dev remove Global Constraint * @param _globalConstraint the address of the global constraint to be remove. * @return bool which represents a success */ function removeGlobalConstraint (address _globalConstraint,address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint(_globalConstraint,globalConstraintRegister.index,when == GlobalConstraintInterface.CallPhase.Pre); } return retVal; } /** * @dev upgrade the Controller * The function will trigger an event 'UpgradeController'. * @param _newController the address of the new controller. * @return bool which represents a success */ function upgradeController(address _newController,address _avatar) external onlyUpgradingScheme isAvatarValid(_avatar) returns(bool) { require(newController == address(0)); // so the upgrade could be done once for a contract. require(_newController != address(0)); newController = _newController; avatar.transferOwnership(_newController); require(avatar.owner()==_newController); if (nativeToken.owner() == address(this)) { nativeToken.transferOwnership(_newController); require(nativeToken.owner()==_newController); } if (nativeReputation.owner() == address(this)) { nativeReputation.transferOwnership(_newController); require(nativeReputation.owner()==_newController); } emit UpgradeController(this,newController); return true; } /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @param _avatar the controller's avatar address * @return bytes32 - the return value of the called _contract's function. */ function genericCall(address _contract,bytes _data,address _avatar) external onlyGenericCallScheme onlySubjectToConstraint("genericCall") isAvatarValid(_avatar) returns (bytes32) { emit GenericCall(_contract, _data); avatar.genericCall(_contract, _data); // solium-disable-next-line security/no-inline-assembly assembly { // Copy the returned data. returndatacopy(0, 0, returndatasize) return(0, returndatasize) } } /** * @dev send some ether * @param _amountInWei the amount of ether (in Wei) to send * @param _to address of the beneficiary * @return bool which represents a success */ function sendEther(uint _amountInWei, address _to,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("sendEther") isAvatarValid(_avatar) returns(bool) { emit SendEther(msg.sender, _amountInWei, _to); return avatar.sendEther(_amountInWei, _to); } /** * @dev send some amount of arbitrary ERC20 Tokens * @param _externalToken the address of the Token Contract * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @return bool which represents a success */ function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransfer") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenTransfer(msg.sender, _externalToken, _to, _value); return avatar.externalTokenTransfer(_externalToken, _to, _value); } /** * @dev transfer token "from" address "to" address * One must to approve the amount of tokens which can be spend from the * "from" account.This can be done using externalTokenApprove. * @param _externalToken the address of the Token Contract * @param _from address of the account to send from * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @return bool which represents a success */ function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransferFrom") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenTransferFrom(msg.sender, _externalToken, _from, _to, _value); return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value); } /** * @dev increase approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _addedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenIncreaseApproval") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenIncreaseApproval(msg.sender,_externalToken,_spender,_addedValue); return avatar.externalTokenIncreaseApproval(_externalToken, _spender, _addedValue); } /** * @dev decrease approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _subtractedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenDecreaseApproval") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenDecreaseApproval(msg.sender,_externalToken,_spender,_subtractedValue); return avatar.externalTokenDecreaseApproval(_externalToken, _spender, _subtractedValue); } /** * @dev getNativeReputation * @param _avatar the organization avatar. * @return organization native reputation */ function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) { return address(nativeReputation); } function _isSchemeRegistered(address _scheme,address _avatar) private isAvatarValid(_avatar) view returns(bool) { return (schemes[_scheme].permissions&bytes4(1) != bytes4(0)); } } // File: contracts/universalSchemes/ExecutableInterface.sol contract ExecutableInterface { function execute(bytes32 _proposalId, address _avatar, int _param) public returns(bool); } // File: contracts/VotingMachines/IntVoteInterface.sol interface IntVoteInterface { //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;} modifier votable(bytes32 _proposalId) {revert(); _;} event NewProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _numOfChoices, address _proposer, bytes32 _paramsHash); event ExecuteProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _decision, uint _totalReputation); event VoteProposal(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter, uint _vote, uint _reputation); event CancelProposal(bytes32 indexed _proposalId, address indexed _avatar ); event CancelVoting(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter); /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _numOfChoices number of voting choices * @param _proposalParameters defines the parameters of the voting machine used for this proposal * @param _avatar an address to be sent as the payload to the _executable contract. * @param _executable This contract will be executed when vote is over. * @param _proposer address * @return proposal's id. */ function propose( uint _numOfChoices, bytes32 _proposalParameters, address _avatar, ExecutableInterface _executable, address _proposer ) external returns(bytes32); // Only owned proposals and only the owner: function cancelProposal(bytes32 _proposalId) external onlyProposalOwner(_proposalId) votable(_proposalId) returns(bool); // Only owned proposals and only the owner: function ownerVote(bytes32 _proposalId, uint _vote, address _voter) external onlyProposalOwner(_proposalId) returns(bool); function vote(bytes32 _proposalId, uint _vote) external votable(_proposalId) returns(bool); function voteWithSpecifiedAmounts( bytes32 _proposalId, uint _vote, uint _rep, uint _token) external votable(_proposalId) returns(bool); function cancelVote(bytes32 _proposalId) external votable(_proposalId); //@dev execute check if the proposal has been decided, and if so, execute the proposal //@param _proposalId the id of the proposal //@return bool true - the proposal has been executed // false - otherwise. function execute(bytes32 _proposalId) public votable(_proposalId) returns(bool); function getNumberOfChoices(bytes32 _proposalId) external view returns(uint); function isVotable(bytes32 _proposalId) external view returns(bool); /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint); /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool); /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint min,uint max); } // File: contracts/VotingMachines/AbsoluteVote.sol contract AbsoluteVote is IntVoteInterface { using SafeMath for uint; struct Parameters { Reputation reputationSystem; // the reputation system that is being used uint precReq; // how many percentages required for the proposal to be passed bool allowOwner; // does this proposal has an owner who has owner rights? } struct Voter { uint vote; // 0 - 'abstain' uint reputation; // amount of voter's reputation } struct Proposal { address owner; // the proposal's owner address avatar; // the avatar of the organization that owns the proposal uint numOfChoices; ExecutableInterface executable; // will be executed if the proposal will pass bytes32 paramsHash; // the hash of the parameters of the proposal uint totalVotes; mapping(uint=>uint) votes; mapping(address=>Voter) voters; bool open; // voting open flag } event AVVoteProposal(bytes32 indexed _proposalId, bool _isOwnerVote); event RefreshReputation(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter,uint _reputation); mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. uint public constant MAX_NUM_OF_CHOICES = 10; uint public proposalsCnt; // Total amount of proposals /** * @dev Check that there is owner for the proposal and he sent the transaction */ modifier onlyProposalOwner(bytes32 _proposalId) { require(msg.sender == proposals[_proposalId].owner); _; } /** * @dev Check that the proposal is votable (open and not executed yet) */ modifier votable(bytes32 _proposalId) { require(proposals[_proposalId].open); _; } /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _numOfChoices number of voting choices * @param _paramsHash defined the parameters of the voting machine used for this proposal * @param _avatar an address to be sent as the payload to the _executable contract. * @param _executable This contract will be executed when vote is over. * @return proposal's id. */ function propose(uint _numOfChoices, bytes32 _paramsHash, address _avatar, ExecutableInterface _executable,address) external returns(bytes32) { // Check valid params and number of choices: require(parameters[_paramsHash].reputationSystem != address(0)); require(_numOfChoices > 0 && _numOfChoices <= MAX_NUM_OF_CHOICES); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt++; // Open proposal: Proposal memory proposal; proposal.numOfChoices = _numOfChoices; proposal.paramsHash = _paramsHash; proposal.avatar = _avatar; proposal.executable = _executable; proposal.owner = msg.sender; proposal.open = true; proposals[proposalId] = proposal; emit NewProposal(proposalId, _avatar, _numOfChoices, msg.sender, _paramsHash); return proposalId; } /** * @dev Cancel a proposal, only the owner can call this function and only if allowOwner flag is true. * @param _proposalId the proposal ID */ function cancelProposal(bytes32 _proposalId) external onlyProposalOwner(_proposalId) votable(_proposalId) returns(bool) { if (! parameters[proposals[_proposalId].paramsHash].allowOwner) { return false; } address avatar = proposals[_proposalId].avatar; deleteProposal(_proposalId); emit CancelProposal(_proposalId, avatar); return true; } /** * @dev voting function * @param _proposalId id of the proposal * @param _vote a value between 0 to and the proposal number of choices. * @return bool true - the proposal has been executed * false - otherwise. */ function vote(bytes32 _proposalId, uint _vote) external votable(_proposalId) returns(bool) { return internalVote(_proposalId, msg.sender, _vote, 0); } /** * @dev voting function with owner functionality (can vote on behalf of someone else) * @param _proposalId id of the proposal * @param _vote a value between 0 to and the proposal number of choices. * @param _voter will be voted with that voter's address * @return bool true - the proposal has been executed * false - otherwise. */ function ownerVote(bytes32 _proposalId, uint _vote, address _voter) external onlyProposalOwner(_proposalId) votable(_proposalId) returns(bool) { if (! parameters[proposals[_proposalId].paramsHash].allowOwner) { return false; } return internalVote(_proposalId, _voter, _vote, 0); } function voteWithSpecifiedAmounts(bytes32 _proposalId,uint _vote,uint _rep,uint) external votable(_proposalId) returns(bool) { return internalVote(_proposalId,msg.sender,_vote,_rep); } /** * @dev Cancel the vote of the msg.sender: subtract the reputation amount from the votes * and delete the voter from the proposal struct * @param _proposalId id of the proposal */ function cancelVote(bytes32 _proposalId) external votable(_proposalId) { cancelVoteInternal(_proposalId, msg.sender); } /** * @dev getNumberOfChoices returns the number of choices possible in this proposal * @param _proposalId the ID of the proposal * @return uint that contains number of choices */ function getNumberOfChoices(bytes32 _proposalId) external view returns(uint) { return proposals[_proposalId].numOfChoices; } /** * @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal * @param _proposalId the ID of the proposal * @param _voter the address of the voter * @return uint vote - the voters vote * uint reputation - amount of reputation committed by _voter to _proposalId */ function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint) { return proposals[_proposalId].votes[_choice]; } /** * @dev isVotable check if the proposal is votable * @param _proposalId the ID of the proposal * @return bool true or false */ function isVotable(bytes32 _proposalId) external view returns(bool) { return proposals[_proposalId].open; } /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool) { return true; } /** * @dev refreshReputation refresh the reputation for a given voters list * @param _proposalId the ID of the proposal * @param _voters list to be refreshed * @return bool true or false */ function refreshReputation(bytes32 _proposalId, address[] _voters) external returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; for (uint i = 0; i < _voters.length; i++) { Voter storage voter = proposal.voters[_voters[i]]; //check that the voters already votes. if (voter.reputation > 0) { //update only if there is a mismatch between the voter's system reputation //and the reputation stored in the voting machine for the voter. uint rep = params.reputationSystem.reputationOf(_voters[i]); if (rep > voter.reputation) { proposal.votes[voter.vote] = proposal.votes[voter.vote].add(rep - voter.reputation); proposal.totalVotes = (proposal.totalVotes).add(rep - voter.reputation); } else if (rep < voter.reputation) { proposal.votes[voter.vote] = proposal.votes[voter.vote].sub(voter.reputation - rep); proposal.totalVotes = (proposal.totalVotes).sub(voter.reputation - rep); } if (rep != voter.reputation) { voter.reputation = rep; emit RefreshReputation(_proposalId, proposal.avatar, _voters[i],rep); } } } return true; } /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint min,uint max) { return (1,MAX_NUM_OF_CHOICES); } /** * @dev execute check if the proposal has been decided, and if so, execute the proposal * @param _proposalId the id of the proposal * @return bool true - the proposal has been executed * false - otherwise. */ function execute(bytes32 _proposalId) public votable(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Reputation reputation = parameters[proposal.paramsHash].reputationSystem; require(reputation != address(0)); uint totalReputation = reputation.totalSupply(); uint precReq = parameters[proposal.paramsHash].precReq; // Check if someone crossed the bar: for (uint cnt = 0; cnt <= proposal.numOfChoices; cnt++) { if (proposal.votes[cnt] > totalReputation*precReq/100) { Proposal memory tmpProposal = proposal; deleteProposal(_proposalId); emit ExecuteProposal(_proposalId, tmpProposal.avatar, cnt, totalReputation); (tmpProposal.executable).execute(_proposalId, tmpProposal.avatar, int(cnt)); return true; } } return false; } /** * @dev hash the parameters, save them if necessary, and return the hash value */ function setParameters(Reputation _reputationSystem, uint _precReq, bool _allowOwner) public returns(bytes32) { require(_precReq <= 100 && _precReq > 0); bytes32 hashedParameters = getParametersHash(_reputationSystem, _precReq, _allowOwner); parameters[hashedParameters] = Parameters({ reputationSystem: _reputationSystem, precReq: _precReq, allowOwner: _allowOwner }); return hashedParameters; } /** * @dev hashParameters returns a hash of the given parameters */ function getParametersHash(Reputation _reputationSystem, uint _precReq, bool _allowOwner) public pure returns(bytes32) { return keccak256(abi.encodePacked(_reputationSystem, _precReq, _allowOwner)); } function cancelVoteInternal(bytes32 _proposalId, address _voter) internal { Proposal storage proposal = proposals[_proposalId]; Voter memory voter = proposal.voters[_voter]; proposal.votes[voter.vote] = (proposal.votes[voter.vote]).sub(voter.reputation); proposal.totalVotes = (proposal.totalVotes).sub(voter.reputation); delete proposal.voters[_voter]; emit CancelVoting(_proposalId, proposal.avatar, _voter); } function deleteProposal(bytes32 _proposalId) internal { Proposal storage proposal = proposals[_proposalId]; for (uint cnt = 0; cnt <= proposal.numOfChoices; cnt++) { delete proposal.votes[cnt]; } delete proposals[_proposalId]; } /** * @dev Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead * @param _proposalId id of the proposal * @param _voter used in case the vote is cast for someone else * @param _vote a value between 0 to and the proposal's number of choices. * @return true in case of proposal execution otherwise false * throws if proposal is not open or if it has been executed * NB: executes the proposal if a decision has been reached */ function internalVote(bytes32 _proposalId, address _voter, uint _vote, uint _rep) private returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; // Check valid vote: require(_vote <= proposal.numOfChoices); // Check voter has enough reputation: uint reputation = params.reputationSystem.reputationOf(_voter); require(reputation >= _rep); uint rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, first cancel the vote: if (proposal.voters[_voter].reputation != 0) { cancelVoteInternal(_proposalId, _voter); } // The voting itself: proposal.votes[_vote] = rep.add(proposal.votes[_vote]); proposal.totalVotes = rep.add(proposal.totalVotes); proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote }); // Event: emit VoteProposal(_proposalId, proposal.avatar, _voter, _vote, reputation); emit AVVoteProposal(_proposalId, (_voter != msg.sender)); // execute the proposal if this vote was decisive: return execute(_proposalId); } }
Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead _proposalId id of the proposal _voter used in case the vote is cast for someone else _vote a value between 0 to and the proposal's number of choices. return true in case of proposal execution otherwise false throws if proposal is not open or if it has been executed NB: executes the proposal if a decision has been reached/ Check valid vote: Check voter has enough reputation: If this voter has already voted, first cancel the vote:
function internalVote(bytes32 _proposalId, address _voter, uint _vote, uint _rep) private returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; require(_vote <= proposal.numOfChoices); uint reputation = params.reputationSystem.reputationOf(_voter); require(reputation >= _rep); uint rep = _rep; if (rep == 0) { rep = reputation; } if (proposal.voters[_voter].reputation != 0) { cancelVoteInternal(_proposalId, _voter); } proposal.totalVotes = rep.add(proposal.totalVotes); proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote }); emit AVVoteProposal(_proposalId, (_voter != msg.sender)); }
11,880,274
./full_match/43114/0xb17A67F28645FAC19856f4F36A5985e91ecB8Ec9/sources/contracts/Strategies.sol
OWNER-ONlY FUNCTIONS
function deposit(address caller, address to, uint256 tokenAmount, uint256 shareAmount) external override onlyOwner { _claimRewards(); _harvest(caller, to); if (tokenAmount > 0) { joeMasterChefV2.deposit(joePid, tokenAmount); } if (shareAmount > 0) { iglooStrategyStorage.increaseRewardDebt(to, shareAmount); } }
4,518,073
pragma solidity ^0.4.23; // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: node_modules/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 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. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ constructor(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } // File: node_modules/openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } // File: node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/crowdsale/OraclizeContractInterface.sol /** * @title OraclizeContractInterface * @dev OraclizeContractInterface **/ contract OraclizeContractInterface { function finalize() public; function buyTokensWithLTC(address _ethWallet, string _ltcWallet, uint256 _ltcAmount) public; function buyTokensWithBTC(address _ethWallet, string _btcWallet, uint256 _btcAmount) public; function buyTokensWithBNB(address _ethWallet, string _bnbWallet, uint256 _bnbAmount) public payable; function buyTokensWithBCH(address _ethWallet, string _bchWallet, uint256 _bchAmount) public payable; function getMultiCurrencyInvestorContribution(string _currencyWallet) public view returns(uint256); } // File: contracts/crowdsale/BurnableTokenInterface.sol /** * @title BurnableTokenInterface, defining one single function to burn tokens. * @dev BurnableTokenInterface **/ contract BurnableTokenInterface { /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public; } // File: installed_contracts/oraclize-api/contracts/usingOraclize.sol // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // File: contracts/crowdsale/FiatContractInterface.sol /** * @title FiatContractInterface, defining one single function to get 0,01 $ price. * @dev FiatContractInterface **/ contract FiatContractInterface { function USD(uint _id) view public returns (uint256); } // File: contracts/utils/strings.sol /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <arachnid@notdot.net> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: contracts/crowdsale/MultiCurrencyRates.sol /** * @title MultiCurrencyRates * @dev MultiCurrencyRates */ // solium-disable-next-line max-len contract MultiCurrencyRates is usingOraclize, Ownable { using SafeMath for uint256; using strings for *; FiatContractInterface public fiatContract; /** * @param _fiatContract Address of fiatContract */ constructor(address _fiatContract) public { require(_fiatContract != address(0)); fiatContract = FiatContractInterface(_fiatContract); } /** * @dev Set fiat contract * @param _fiatContract Address of new fiatContract */ function setFiatContract(address _fiatContract) public onlyOwner { fiatContract = FiatContractInterface(_fiatContract); } /** * @dev Returns the current 0.01$ => ETH wei rate */ function getUSDCentToWeiRate() internal view returns (uint256) { return fiatContract.USD(0); } /** * @dev Returns the current 0.01$ => BTC satoshi rate */ function getUSDCentToBTCSatoshiRate() internal view returns (uint256) { return fiatContract.USD(1); } /** * @dev Returns the current 0.01$ => LTC satoshi rate */ function getUSDCentToLTCSatoshiRate() internal view returns (uint256) { return fiatContract.USD(2); } /** * @dev Returns the current BNB => 0.01$ rate */ function getBNBToUSDCentRate(string oraclizeResult) internal pure returns (uint256) { return parseInt(parseCurrencyRate(oraclizeResult, "BNB"), 2); } /** * @dev Returns the current BCH => 0.01$ rate */ function getBCHToUSDCentRate(string oraclizeResult) internal pure returns (uint256) { return parseInt(parseCurrencyRate(oraclizeResult, "BCH"), 2); } /** * @dev Parse currency rate from oraclize response * @param oraclizeResult Result from Oraclize with currencies prices * @param _currencyTicker Currency tiker * @return Currency price string in USD */ function parseCurrencyRate(string oraclizeResult, string _currencyTicker) internal pure returns(string) { strings.slice memory response = oraclizeResult.toSlice(); strings.slice memory needle = _currencyTicker.toSlice(); strings.slice memory tickerPrice = response.find(needle).split("}".toSlice()).find(" ".toSlice()).rsplit(" ".toSlice()); return tickerPrice.toString(); } } // File: contracts/crowdsale/PhaseCrowdsaleInterface.sol /** * @title PhaseCrowdsaleInterface * @dev PhaseCrowdsaleInterface */ contract PhaseCrowdsaleInterface { /** * @dev Get phase number depending on the current time */ function getPhaseNumber() public view returns (uint256); /** * @dev Returns the current token price in $ cents depending on the current time */ function getCurrentTokenPriceInCents() public view returns (uint256); /** * @dev Returns the token sale bonus percentage depending on the current time */ function getCurrentBonusPercentage() public view returns (uint256); } // File: contracts/crowdsale/CryptonityCrowdsale.sol /** * @title CryptonityCrowdsale * @dev CryptonityCrowdsale */ // solium-disable-next-line max-len contract CryptonityCrowdsale is TimedCrowdsale, WhitelistedCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale, MultiCurrencyRates, Pausable { using SafeMath for uint256; OraclizeContractInterface public oraclizeContract; PhaseCrowdsaleInterface public phaseCrowdsale; // Public supply of token uint256 public publicSupply = 60000000 * 1 ether; // Remaining public supply of token for each phase uint256[3] public remainingPublicSupplyPerPhase = [15000000 * 1 ether, 26000000 * 1 ether, 19000000 * 1 ether]; // When tokens will be available for withdraw uint256 public deliveryTime; // A limit for total contributions in USD cents uint256 public cap; // Is goal reached bool public isGoalReached = false; event LogInfo(string description); /** * @param _phasesTime Crowdsale phases time [openingTime, closingTime, secondPhaseStartTime, thirdPhaseStartTime] * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold * @param _softCapUSDInCents Funding goal in USD cents * @param _hardCapUSDInCents Max amount of USD cents to be contributed * @param _fiatContract FiatContract * @param _phaseCrowdsale info about current phase * @param _oraclizeContract oraclize contract */ constructor( uint256[4] _phasesTime, uint256 _rate, address _wallet, ERC20 _token, uint256 _softCapUSDInCents, uint256 _hardCapUSDInCents, address _fiatContract, address _phaseCrowdsale, address _oraclizeContract ) public Crowdsale(_rate, _wallet, _token) RefundableCrowdsale(_softCapUSDInCents) TimedCrowdsale(_phasesTime[0], _phasesTime[1]) MultiCurrencyRates(_fiatContract) { require(_phasesTime[2] >= _phasesTime[0]); require(_phasesTime[3] >= _phasesTime[2]); require(_phasesTime[1] >= _phasesTime[3]); require(_hardCapUSDInCents > 0); require(_softCapUSDInCents <= _hardCapUSDInCents); cap = _hardCapUSDInCents; // token delivery starts 15 days after the crowdsale ends deliveryTime = _phasesTime[1].add(15 days); oraclizeContract = OraclizeContractInterface(_oraclizeContract); phaseCrowdsale = PhaseCrowdsaleInterface(_phaseCrowdsale); } /** * @dev Reverts if crowdsale is not finalized */ modifier whenFinalized { require(isFinalized); _; } /** * @dev Reverts if caller isn't oraclizeContract */ modifier onlyOraclize { require(msg.sender == address(oraclizeContract)); _; } /** * @dev Get multi currency investor contribution. * @param _currencyWallet Address of currency wallet * @return Amount of currency contribution */ function getMultiCurrencyInvestorContribution(string _currencyWallet) public view returns(uint256) { return oraclizeContract.getMultiCurrencyInvestorContribution(_currencyWallet); } /** * @dev Calculates the sum amount of tokens which were unsold or remaining during all crowdsale phases. * @return The total amount of unsold tokens */ function calculateTotalRemainingPublicSupply() private view returns (uint256) { uint256 totalRemainingPublicSupply = 0; for (uint i = 0; i < remainingPublicSupplyPerPhase.length; i++) { totalRemainingPublicSupply = totalRemainingPublicSupply.add(remainingPublicSupplyPerPhase[i]); } return totalRemainingPublicSupply; } /** * @dev Validation of an incoming purchase. Allowas purchases only when crowdsale is not paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { super._preValidatePurchase(_beneficiary, _weiAmount); rate = uint256(1 ether).mul(1 ether).div(getUSDCentToWeiRate()).div(phaseCrowdsale.getCurrentTokenPriceInCents()); } /** * @dev Executed by oraclize when a purchase has been validated and is ready to be executed. * It computes the bonus. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function processPurchase(address _beneficiary, uint256 _tokenAmount) public onlyOraclize onlyWhileOpen isWhitelisted(_beneficiary) { _processPurchase(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * It computes the bonus. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { uint256 totalAmount = _tokenAmount; uint256 bonusPercent = phaseCrowdsale.getCurrentBonusPercentage(); if (bonusPercent > 0) { uint256 bonusAmount = totalAmount.mul(bonusPercent).div(100); // tokens * bonus (%) / 100% totalAmount = totalAmount.add(bonusAmount); } uint256 phaseNumber = phaseCrowdsale.getPhaseNumber(); require(remainingPublicSupplyPerPhase[phaseNumber] >= totalAmount); super._processPurchase(_beneficiary, totalAmount); remainingPublicSupplyPerPhase[phaseNumber] = remainingPublicSupplyPerPhase[phaseNumber].sub(totalAmount); } /** * @dev Withdraw tokens only after the deliveryTime */ function withdrawTokens() public whenFinalized { require(isGoalReached); // solium-disable-next-line security/no-block-members require(now > deliveryTime); super.withdrawTokens(); } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public whenFinalized { require(!isGoalReached); vault.refund(msg.sender); } /** * @dev Token purchase with LTC * @param _ethWallet Address receiving the tokens * @param _ltcWallet LTC address who paid for the tokens * @param _ltcAmount Value in LTC involved in the purchase */ function buyTokensWithLTC(address _ethWallet, string _ltcWallet, uint256 _ltcAmount) public onlyOwner { oraclizeContract.buyTokensWithLTC(_ethWallet, _ltcWallet, _ltcAmount); } /** * @dev Token purchase with BTC * @param _ethWallet Address receiving the tokens * @param _btcWallet BTC address who paid for the tokens * @param _btcAmount Value in BTC involved in the purchase */ function buyTokensWithBTC(address _ethWallet, string _btcWallet, uint256 _btcAmount) public onlyOwner { oraclizeContract.buyTokensWithBTC(_ethWallet, _btcWallet, _btcAmount); } /** * @dev Token purchase with BNB * @param _ethWallet Address receiving the tokens * @param _bnbWallet BNB address who paid for the tokens * @param _bnbAmount Value in BNB involved in the purchase */ function buyTokensWithBNB(address _ethWallet, string _bnbWallet, uint256 _bnbAmount) public payable onlyOwner { oraclizeContract.buyTokensWithBNB.value(msg.value)(_ethWallet, _bnbWallet, _bnbAmount); } /** * @dev Token purchase with BCH * @param _ethWallet Address receiving the tokens * @param _bchWallet BCH address who paid for the tokens * @param _bchAmount Value in BCH involved in the purchase */ function buyTokensWithBCH(address _ethWallet, string _bchWallet, uint256 _bchAmount) public payable onlyOwner { oraclizeContract.buyTokensWithBCH.value(msg.value)(_ethWallet, _bchWallet, _bchAmount); } /** * @dev The way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate).div(1 ether); // divisor 10^18 to nullify multiplier from _calculateCurrentRate } /** * @dev Finalization logic. * Burn the remaining tokens. * Transfer token ownership to contract owner. */ function finalization() internal { oraclizeContract.finalize(); } /** * @dev Executed by oraclize when multicurrency finalization is calculated * @param _usdRaised usdCent reised with multicurrency */ function finalizationCallback(uint256 _usdRaised) public onlyOraclize { uint256 usdRaised = weiRaised.div(getUSDCentToWeiRate()).add(_usdRaised); if(usdRaised >= goal) { emit LogInfo("Finalization completed"); isGoalReached = true; vault.close(); } else { emit LogInfo("Finalization failed"); vault.enableRefunds(); } uint256 totalRemainingPublicSupply = calculateTotalRemainingPublicSupply(); if (totalRemainingPublicSupply > 0) { BurnableTokenInterface(address(token)).burn(totalRemainingPublicSupply); delete remainingPublicSupplyPerPhase; } Ownable(address(token)).transferOwnership(owner); } }
Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. It computes the bonus. _beneficiary Address receiving the tokens _tokenAmount Number of tokens to be purchased/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { uint256 totalAmount = _tokenAmount; uint256 bonusPercent = phaseCrowdsale.getCurrentBonusPercentage(); if (bonusPercent > 0) { totalAmount = totalAmount.add(bonusAmount); } uint256 phaseNumber = phaseCrowdsale.getPhaseNumber(); require(remainingPublicSupplyPerPhase[phaseNumber] >= totalAmount); super._processPurchase(_beneficiary, totalAmount); remainingPublicSupplyPerPhase[phaseNumber] = remainingPublicSupplyPerPhase[phaseNumber].sub(totalAmount); }
14,096,993
./full_match/5/0xa488161a4F64cC9bEC991de87d722e5Dc340174A/sources/contracts/DPS.sol
change the merkle root for the whitelist phase
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; }
1,854,221
./partial_match/1/0x409bf77A8E3Fe384497227eA508029B5364933DE/sources/contracts/staking/TokenStaking.sol
Sets cached legacy stake amount to 0, sets the liquid T stake amount to 0 and withdraws all liquid T from the stake to the owner. Reverts if there is at least one non-zero authorization. Can be called only by the delegation owner or the staking provider. Can only be called when 24h passed since the stake has been delegated. solhint-disable-next-line not-rely-on-time /
function unstakeAll(address stakingProvider) external override onlyOwnerOrStakingProvider(stakingProvider) { StakingProviderInfo storage stakingProviderStruct = stakingProviders[ stakingProvider ]; require( stakingProviderStruct.authorizedApplications.length == 0, "Stake still authorized" ); require( stakingProviderStruct.startStakingTimestamp + MIN_STAKE_TIME <= block.timestamp, "Can't unstake earlier than 24h" ); uint96 unstaked = stakingProviderStruct.tStake + stakingProviderStruct.keepInTStake + stakingProviderStruct.nuInTStake; emit Unstaked(stakingProvider, unstaked); uint96 amount = stakingProviderStruct.tStake; stakingProviderStruct.tStake = 0; stakingProviderStruct.keepInTStake = 0; stakingProviderStruct.nuInTStake = 0; decreaseStakeCheckpoint(stakingProvider, unstaked); if (amount > 0) { token.safeTransfer(stakingProviderStruct.owner, amount); } }
2,586,917
./full_match/43113/0x72d62b0f3a0CEAdcD771b90537151774BD746FEA/sources/apps/avai/src/contracts/OrcaStaking.sol
Withdraw tokens from Staking, claiming rewards. pid pool id amount number of tokens to withdraw/
function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, 'Staking::withdraw: amount must be > 0'); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); }
13,153,946
./full_match/4/0x9Fa3D6EE31268Cd815BB9bA35E85eD5e18CA7e65/sources/browser/Untitled2.sol
Destroy tokens Remove `_value` tokens from the system irreversibly _value the amount of money to burn/checking of enough token balance is done by SafeMathalthogh we can track all the "burn" from the Transfer function, we just kept it as it is. As that is no much harm
function burn(uint256 _value) public returns (bool success) { require(!globalHalt, "paused by admin"); burnTracker = burnTracker.add(_value); emit Transfer(msg.sender, address(0), _value); emit Burn(msg.sender, _value); return true; }
778,371
pragma solidity ^0.4.25; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ bool private operational = true; FlightSuretyData data; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract /* struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } mapping(bytes32 => Flight) private flights; */ // Incremented to add pseudo-randomness at various points uint8 private nonce1 = 1; uint16 private nonce2 = 999; uint8 private switcher = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, uint32 flight, uint32 timestamp, uint8 status); event OracleReport(address airline, uint32 flight, uint32 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, uint32 flight, uint32 timestamp); /********************************************************************************************/ /* 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() { // Modify to call data contract's status require(isOperational(), "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"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor (address _data ) public { contractOwner = msg.sender; data = FlightSuretyData(_data); data.registerAirline(msg.sender,"Air One",msg.sender); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns(bool) { return operational && data.isOperational(); // Modify to call data contract's status } function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function setAppAddress (address _app) public pure { _app = address(0); } /** * @dev Add an airline to the registration queue * */ function registerAirline ( string _name, address _address ) external requireIsOperational { data.registerAirline(msg.sender,_name,_address); } function AirlineStatus(address _address) external view requireIsOperational returns (bool status){ return data.AirlineStatus(_address); } function approveAirline (address _address) external requireIsOperational { data.approveAirline(msg.sender,_address); } /** * @dev Register a future flight for insuring. * */ function setFlightStatus (address _airline_address, uint32 _flight_id, uint32 _departure_time, uint32 _status) internal requireIsOperational { //sec data.setFlightStatus(_airline_address,_flight_id,_departure_time,_status); } function getFlightStatus (address _airline_address, uint32 _flight_id, uint32 _departure_time) external view requireIsOperational returns (uint32 status) { //sec return data.getFlightStatus(_airline_address,_flight_id,_departure_time); } /** * @dev Buy insurance for a flight * */ function buy (address _airline_address, uint32 _flight_id, uint32 _departure_time ) external payable requireIsOperational { data.buy.value(msg.value)(msg.sender,_airline_address,_flight_id,_departure_time); } /** * @dev Credits payouts to insurees */ function creditInsurees ( uint _policy ) external requireIsOperational { data.creditInsurees(msg.sender, _policy); } /** * @dev Transfers eligible payout funds to insuree * */ function pay () external requireIsOperational { data.pay(msg.sender); } /** * @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 () external payable requireIsOperational { data.fund.value(msg.value)(msg.sender); } /** * @dev Called after oracle has updated flight status * */ /* function processFlightStatus ( address airline, string memory flight, uint256 timestamp, uint8 statusCode ) internal pure { } */ // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, uint32 flight, uint32 timestamp ) public { uint8 index = getRandomIndex(); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); require(oracles[msg.sender].isRegistered == false,"Oracle already Registered"); uint8[3] memory indexes = generateIndexes(); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes () view external returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, uint32 flight, uint32 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); require(statusCode > 0 , "Unknown status is not acceptable input"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { // Handle flight status as appropriate data.setFlightStatus(airline,flight,timestamp,statusCode); oracleResponses[key].isOpen = false; emit FlightStatusInfo(airline, flight, timestamp, statusCode); } } /* function getFlightKey ( address airline, string flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } */ // Returns array of three non-duplicating integers from 0-9// function generateIndexes () internal returns (uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint32((nonce2) - (nonce1)) % maxValue); nonce1++; nonce2--; if (random < 9 && switcher == 0){ random++; switcher = 1; } else if (switcher == 1){ switcher = 2; } else if (switcher == 2){ switcher = 3; } else if (switcher == 3){ switcher = 0; } if (nonce1 > 250) { nonce1 = 1; } if (nonce2 <= 260) { nonce2 = 1000; } return random; } /** * @dev Fallback function for funding smart contract. * */ function() public payable { //fund(); } // endregion } /************************************************** */ /* Interface for Data Contract */ /************************************************** */ contract FlightSuretyData { function isOperational() public view returns(bool); function setOperatingStatus (bool mode) external; function registerAirline (address _from,string _name,address _address) external; function approveAirline (address _from,address _address) external; function buy (address _from, address _airline_address, uint32 _flight_id, uint32 _departure_time ) external payable; function creditInsurees (address _from, uint _policy ) external; function pay (address _from) external; function fund (address _from ) external payable; function setAppAddress (address _app) public; function setFlightStatus (address _airline_address, uint32 _flight_id, uint32 _departure_time, uint32 _status) external; function getFlightStatus (address _airline_address, uint32 _flight_id, uint32 _departure_time) external view returns (uint32 status); function AirlineStatus (address _address) external view returns (bool status); }
Generate a request for oracles to fetch flight information Generate a unique key for storing the request
function fetchFlightStatus ( address airline, uint32 flight, uint32 timestamp ) public { uint8 index = getRandomIndex(); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); }
6,371,108
pragma solidity 0.4.16; // implement safemath as a library library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } // Used for function invoke restriction contract Owned { address public owner; // temporary address function Owned() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) revert(); _; // function code inserted here } function transferOwnership(address _newOwner) onlyOwner returns (bool success) { if (msg.sender != owner) revert(); owner = _newOwner; return true; } } contract Vezt is Owned { using SafeMath for uint256; address[] public veztUsers; uint256 public totalSupply; uint8 public decimals; string public name; string public symbol; bool public tokenTransfersFrozen; bool public tokenMintingEnabled; bool public contractLaunched; mapping (address => mapping (address => uint256)) public allowance; mapping (address => uint256) public balances; mapping (address => uint256) public royaltyTracking; mapping (address => uint256) public icoBalances; mapping (address => uint256) public veztUserArrayIdentifier; mapping (address => bool) public veztUserRegistered; event Transfer(address indexed _sender, address indexed _recipient, uint256 _amount); event Approve(address indexed _owner, address indexed _spender, uint256 _amount); event LaunchContract(address indexed _launcher, bool _launched); event FreezeTokenTransfers(address indexed _invoker, bool _frozen); event ThawTokenTransfers(address indexed _invoker, bool _thawed); event MintTokens(address indexed _minter, uint256 _amount, bool indexed _minted); event TokenMintingDisabled(address indexed _invoker, bool indexed _disabled); event TokenMintingEnabled(address indexed _invoker, bool indexed _enabled); function Vezt() { name = "Vezt"; symbol = "VZT"; decimals = 18; //125 million in wei totalSupply = 125000000000000000000000000; balances[msg.sender] = balances[msg.sender].add(totalSupply); tokenTransfersFrozen = true; tokenMintingEnabled = false; contractLaunched = false; } /// @notice Used to log royalties /// @param _receiver The eth address of person to receive VZT Tokens /// @param _amount The amount of VZT Tokens in wei to send function logRoyalty(address _receiver, uint256 _amount) onlyOwner public returns (bool logged) { require(transferCheck(msg.sender, _receiver, _amount)); if (!veztUserRegistered[_receiver]) { veztUsers.push(_receiver); veztUserRegistered[_receiver] = true; } require(royaltyTracking[_receiver].add(_amount) > 0); require(royaltyTracking[_receiver].add(_amount) > royaltyTracking[_receiver]); royaltyTracking[_receiver] = royaltyTracking[_receiver].add(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_receiver] = balances[_receiver].add(_amount); Transfer(owner, _receiver, _amount); return true; } function transactionReplay(address _receiver, uint256 _amount) onlyOwner public returns (bool replayed) { require(transferCheck(msg.sender, _receiver, _amount)); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_receiver] = balances[_receiver].add(_amount); Transfer(msg.sender, _receiver, _amount); return true; } /// @notice Used to launch the contract, and enabled token minting function launchContract() onlyOwner { require(!contractLaunched); tokenTransfersFrozen = false; tokenMintingEnabled = true; contractLaunched = true; LaunchContract(msg.sender, true); } function disableTokenMinting() onlyOwner returns (bool disabled) { tokenMintingEnabled = false; TokenMintingDisabled(msg.sender, true); return true; } function enableTokenMinting() onlyOwner returns (bool enabled) { tokenMintingEnabled = true; TokenMintingEnabled(msg.sender, true); return true; } function freezeTokenTransfers() onlyOwner returns (bool success) { tokenTransfersFrozen = true; FreezeTokenTransfers(msg.sender, true); return true; } function thawTokenTransfers() onlyOwner returns (bool success) { tokenTransfersFrozen = false; ThawTokenTransfers(msg.sender, true); return true; } /// @notice Used to transfer funds /// @param _receiver Eth address to send VZT tokens too /// @param _amount The amount of VZT tokens in wei to send function transfer(address _receiver, uint256 _amount) public returns (bool success) { require(transferCheck(msg.sender, _receiver, _amount)); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_receiver] = balances[_receiver].add(_amount); Transfer(msg.sender, _receiver, _amount); return true; } /// @notice Used to transfer funds on behalf of owner to receiver /// @param _owner The person you are allowed to sends funds on bhhalf of /// @param _receiver The person to receive the funds /// @param _amount The amount of VZT tokens in wei to send function transferFrom(address _owner, address _receiver, uint256 _amount) public returns (bool success) { require(allowance[_owner][msg.sender] >= _amount); require(transferCheck(_owner, _receiver, _amount)); allowance[_owner][msg.sender] = allowance[_owner][msg.sender].sub(_amount); balances[_owner] = balances[_owner].sub(_amount); balances[_receiver] = balances[_receiver].add(_amount); Transfer(_owner, _receiver, _amount); return true; } /// @notice Used to approve someone to send funds on your behalf /// @param _spender The eth address of the person you are approving /// @param _amount The amount of VZT tokens _spender is allowed to send (in wei) function approve(address _spender, uint256 _amount) public returns (bool approved) { require(_amount > 0); require(balances[msg.sender] >= _amount); allowance[msg.sender][_spender] = allowance[msg.sender][_spender].add(_amount); return true; } /// @notice Used to burn tokens and decrease total supply /// @param _amount The amount of VZT tokens in wei to burn function tokenBurner(uint256 _amount) onlyOwner returns (bool burned) { require(_amount > 0); require(totalSupply.sub(_amount) > 0); require(balances[msg.sender] > _amount); require(balances[msg.sender].sub(_amount) > 0); totalSupply = totalSupply.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); Transfer(msg.sender, 0, _amount); return true; } /// @notice Low level function Used to create new tokens and increase total supply /// @param _amount The amount of VZT tokens in wei to create function tokenMinter(uint256 _amount) private returns (bool minted) { require(tokenMintingEnabled); require(_amount > 0); require(totalSupply.add(_amount) > 0); require(totalSupply.add(_amount) > totalSupply); require(balances[owner].add(_amount) > 0); require(balances[owner].add(_amount) > balances[owner]); return true; } /// @notice Used to create new tokens and increase total supply /// @param _amount The amount of VZT tokens in wei to create function tokenFactory(uint256 _amount) onlyOwner returns (bool success) { require(tokenMinter(_amount)); totalSupply = totalSupply.add(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); Transfer(0, msg.sender, _amount); return true; } // GETTER // function lookupRoyalty(address _veztUser) public constant returns (uint256 royalties) { return royaltyTracking[_veztUser]; } /// @notice Reusable code to do sanity check of transfer variables function transferCheck(address _sender, address _receiver, uint256 _amount) private constant returns (bool success) { require(!tokenTransfersFrozen); require(_amount > 0); require(_receiver != address(0)); require(balances[_sender].sub(_amount) >= 0); require(balances[_receiver].add(_amount) > 0); require(balances[_receiver].add(_amount) > balances[_receiver]); return true; } /// @notice Used to retrieve total supply function totalSupply() public constant returns (uint256 _totalSupply) { return totalSupply; } /// @notice Used to look up balance of a person function balanceOf(address _person) public constant returns (uint256 _balance) { return balances[_person]; } /// @notice Used to look up the allowance of someone function allowance(address _owner, address _spender) public constant returns (uint256 _amount) { return allowance[_owner][_spender]; } }
Used to burn tokens and decrease total supply _amount The amount of VZT tokens in wei to burn
function tokenBurner(uint256 _amount) onlyOwner returns (bool burned) { require(_amount > 0); require(totalSupply.sub(_amount) > 0); require(balances[msg.sender] > _amount); require(balances[msg.sender].sub(_amount) > 0); totalSupply = totalSupply.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); Transfer(msg.sender, 0, _amount); return true; }
1,810,800
./partial_match/1/0xcDdc0F6053432dE3dd0F8dB3786D696fffC3A860/sources/OriginEthStrategy.sol
depositng base token from bank to this smart-contract baseAmount - amount that depositing to strategy isSafeTransfer - turn on safe transfer/
function depositFromBank(uint256 baseAmount, bool isSafeTransfer) public onlyOperator{ uint256 allowance = IERC20(baseToken).allowance(bank, address(this)); require(allowance >= baseAmount, "depositFromBank: allowance less than baseAmount"); require(IERC20(baseToken).balanceOf(bank) >= baseAmount, "depositFromBank: balance less than baseAmount"); if (isSafeTransfer){ IERC20(baseToken).safeTransferFrom(bank, address(this), baseAmount); } else{ IERC20(baseToken).transferFrom(bank, address(this), baseAmount); } }
15,778,599
./partial_match/5/0x9e0861844F40B48207e6c5D384D53Dfe27f4a8EC/sources/DeporRPOSValidatorData.sol
start runningmodfiy status
function creatorStartRunningValidator(address _creator, uint256 vID) external whenNotPaused onlyWhitelistAdmin { Validator storage validator = idToValidators[vID]; validator.status = 2; validator.lastEpochBlockNumber = block.number; validator.lastEpochTimestamp = block.timestamp; runningValidatorCount++; }
16,833,347
./partial_match/1/0x17b1FF602d824eefFcdF6546FCb87A5C6BC69aDD/sources/RaiseFactory.sol
Investor can subscribe to the capital raise with the unique subscription hash. _subID Subscription unique identifier _shares Amount of shares to purchase./
function subscribe(bytes32 _subID, uint256 _shares) public whenNotPaused onlyInvestor onlyAtStage(Stage.Created) onlyWhileOpen { require(_shares <= getAvailableShares(), 'Raise: above available'); uint256 cost = _shares.mul(price); require(cost >= minSubscription, 'Raise: below minimum subscription'); require(cost <= dchf.allowance(msg.sender, address(this)), 'Raise: below allowance'); dchf.transferFrom(msg.sender, address(this), cost); totalPendingDeposits = totalPendingDeposits.add(cost); investor[msg.sender][false].insert(_subID); subscriptions[false].insert(_subID); subscription[_subID] = Subscription({ investor: msg.sender, shares: _shares, cost: cost }); emit SubscriptionProposal(issuer, msg.sender, _subID); }
2,859,472
./full_match/137/0xe8D2cb841a187C300641b306e5a85c9Fc06A781f/sources/contracts/Wallet.sol
/ HELPERS /
function _removeIndex(uint _indexIdentifier) private { require( userIndexes[_indexIdentifier].Exists == true, "CLAMP-V1: NO-INDEX-EXISTS" ); delete userIndexes[_indexIdentifier]; }
4,797,048
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 struct Airline { bool isExisting; bool isRegistered; bool isFunded; bytes32[] flightKeyList; Votes votes; uint256 numberOfInsurance; } mapping(address => Airline) private airlineMapping; mapping(address => bool) public authorizedCallerMapping; uint256 private airlinesCount = 0; uint256 private registeredAirlinesCount = 0; uint256 private fundedAirlinesCount = 0; struct Votes { uint256 votersCount; mapping(address => bool) voterMapping; } struct Insurance { address buyer; uint256 value; address airline; string flightName; uint256 departure; InsuranceState state; } enum InsuranceState { NotExist, WaitingForBuyer, Bought, Passed, Expired } struct FlightInsurance { mapping(address => Insurance) insurances; address[] keys; } mapping(bytes32 => FlightInsurance) private flightInsuranceMapping; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizeCaller(address caller); event AirlineExist(address airline, bool exist); event AirlineRegistered(address airline, bool exist, bool registered); event AirlineFunded( address airlineAddress, bool exist, bool registered, bool funded, uint256 fundedCount ); event InsuranceBought(bytes32 flightKey); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor( address airlineAddress ) public { contractOwner = msg.sender; airlineMapping[airlineAddress] = Airline({ isExisting: true, isRegistered: true, isFunded: false, flightKeyList: new bytes32[](0), votes: Votes(0), numberOfInsurance: 0 }); airlinesCount = airlinesCount.add(1); registeredAirlinesCount = registeredAirlinesCount.add(1); emit AirlineExist(airlineAddress, airlineMapping[airlineAddress].isExisting); emit AirlineRegistered( airlineAddress, airlineMapping[airlineAddress].isExisting, airlineMapping[airlineAddress].isRegistered ); } /********************************************************************************************/ /* 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"); _; } modifier requireAuthorizedCaller(address contractAddress) { require(authorizedCallerMapping[contractAddress], "Caller is not authorized"); _; } modifier requireIsAirlineExisting(address airlineAddress) { require(airlineMapping[airlineAddress].isExisting, "Airline does not exist"); _; } modifier requireIsAirlineRegistered(address airlineAddress) { require(airlineMapping[airlineAddress].isRegistered, "Airline 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; } // function authorizeCaller(address contractAddress) public requireContractOwner requireIsOperational { require(!authorizedCallerMapping[contractAddress], "Address is authorized"); authorizedCallerMapping[contractAddress] = true; emit AuthorizeCaller(contractAddress); } function getExistAirlinesCount() public view returns (uint256) { return airlinesCount; } function getRegisteredAirlinesCount() public view returns (uint256) { return registeredAirlinesCount; } function getFundedAirlinesCount() public view returns (uint256) { return fundedAirlinesCount; } function getAirlineVotesCount(address airlineAddress) public view returns (uint256) { return airlineMapping[airlineAddress].votes.votersCount; } function airlineExists(address airlineAddress) public view returns (bool) { return airlineMapping[airlineAddress].isExisting; } function airlineRegistered(address airlineAddress) public view returns (bool) { return ( airlineMapping[airlineAddress].isExisting ? airlineMapping[airlineAddress].isRegistered : false ); } function isAirlineFunded(address airlineAddress) public view returns (bool) { return airlineMapping[airlineAddress].isFunded; } function getInsurance( address buyer, address airlineAddress, string memory flightName, uint256 departure ) public view returns (uint256 value, InsuranceState state) { bytes32 flightKey = getFlightKey(airlineAddress, flightName, departure); FlightInsurance storage flightInsurance = flightInsuranceMapping[flightKey]; Insurance storage insurance = flightInsurance.insurances[buyer]; return (insurance.value, insurance.state); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airlineAddress, bool registered) public requireIsOperational { airlineMapping[airlineAddress] = Airline({ isExisting: true, isRegistered: registered, isFunded: false, flightKeyList: new bytes32[](0), votes: Votes(0), numberOfInsurance: 0 }); airlinesCount = airlinesCount.add(1); if (registered == true) { registeredAirlinesCount = registeredAirlinesCount.add(1); emit AirlineRegistered( airlineAddress, airlineMapping[airlineAddress].isExisting, airlineMapping[airlineAddress].isRegistered ); } else { emit AirlineExist(airlineAddress, airlineMapping[airlineAddress].isExisting); } } function setAirlineRegistered(address airlineAddress) public requireIsOperational requireIsAirlineExisting(airlineAddress) { require(airlineMapping[airlineAddress].isRegistered, "Airline is already registered"); airlineMapping[airlineAddress].isRegistered = true; registeredAirlinesCount = registeredAirlinesCount.add(1); emit AirlineRegistered( airlineAddress, airlineMapping[airlineAddress].isExisting, airlineMapping[airlineAddress].isRegistered ); } function getMinimumRequiredVotingCount() public view returns (uint256) { return registeredAirlinesCount.div(2); } function voteForAirline( address votingAirlineAddress, address airlineAddress ) public requireIsOperational { require(!airlineMapping[airlineAddress].votes.voterMapping[votingAirlineAddress], "Airline already voted"); airlineMapping[airlineAddress].votes.voterMapping[votingAirlineAddress] = true; uint256 startingVotes = getAirlineVotesCount(airlineAddress); airlineMapping[airlineAddress].votes.votersCount = startingVotes.add(1); } function registerFlightKey(address airlineAddress, bytes32 flightKey) public requireAuthorizedCaller(msg.sender) { airlineMapping[airlineAddress].flightKeyList.push(flightKey); } /** * @dev Buy insurance for a flight * */ function buyInsurance( address buyer, address airlineAddress, string memory flightName, uint256 departure ) public payable { bytes32 flightKey = getFlightKey(airlineAddress, flightName, departure); FlightInsurance storage flightInsurance = flightInsuranceMapping[flightKey]; flightInsurance.insurances[buyer] = Insurance({ buyer: buyer, value: msg.value, airline: airlineAddress, flightName: flightName, departure: departure, state: InsuranceState.Bought }); flightInsurance.keys.push(buyer); emit InsuranceBought(flightKey); } /** * @dev Credits payouts to insurees */ function creditInsurees(bytes32 flightKey, uint8 creditRate) public requireAuthorizedCaller(msg.sender) { FlightInsurance storage flightInsurance = flightInsuranceMapping[flightKey]; for (uint256 i = 0; i < flightInsurance.keys.length; i++) { Insurance storage insurance = flightInsurance.insurances[flightInsurance.keys[i]]; if (insurance.state == InsuranceState.Bought && creditRate > 0) { insurance.value = insurance.value.mul(creditRate).div(100); insurance.state = InsuranceState.Passed; } else { insurance.state = InsuranceState.Expired; } } } /** * @dev Transfers eligible payout funds to insuree * */ function pay(bytes32 flightKey) external payable { FlightInsurance storage flightInsurance = flightInsuranceMapping[flightKey]; Insurance storage insurance = flightInsurance.insurances[msg.sender]; require( insurance.state == InsuranceState.Passed, "Insuree is not eligible" ); require(address(this).balance > insurance.value, "Please try again later"); uint256 value = insurance.value; insurance.value = 0; insurance.state = InsuranceState.Expired; address payable insuree = address(uint160(insurance.buyer)); insuree.transfer(value); } /** * @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 airlineAddress) public payable requireIsOperational requireIsAirlineExisting(airlineAddress) requireIsAirlineRegistered(airlineAddress) { airlineMapping[airlineAddress].isFunded = true; fundedAirlinesCount = fundedAirlinesCount.add(1); emit AirlineFunded( airlineAddress, airlineMapping[airlineAddress].isExisting, airlineMapping[airlineAddress].isRegistered, airlineMapping[airlineAddress].isFunded, fundedAirlinesCount ); } 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(msg.sender); } }
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 airlineAddress) public payable requireIsOperational requireIsAirlineExisting(airlineAddress) requireIsAirlineRegistered(airlineAddress) { airlineMapping[airlineAddress].isFunded = true; fundedAirlinesCount = fundedAirlinesCount.add(1); emit AirlineFunded( airlineAddress, airlineMapping[airlineAddress].isExisting, airlineMapping[airlineAddress].isRegistered, airlineMapping[airlineAddress].isFunded, fundedAirlinesCount ); }
7,237,503
./full_match/3/0xcAb9D8f8c505dB3EA86DBcF97BfF03BA59b001F3/sources/workspace_1625825398961/SRSC.sol
Sewer Rats reserved for promotions and Dev Team/
function reserveRats() public onlyOwner { uint supply = totalSupply(); uint i; for (i = 0; i < 30; i++) { _safeMint(msg.sender, supply + i); } }
14,134,771
./partial_match/3/0xbD1c9AdF6AA78eB5092c73a55d72113e9DEDC0DE/sources/Invitation.sol
配置基金、预言机、空投、预言机回调、TSR合约地址
function setAddr(address _fundAddr, address _aggregateAddr, address _airdropAddr, address _oracleCallbackAddr, address __tokenContractAddr) public onlyOwner { fundAddr = _fundAddr; aggregate = AggregateApiI(_aggregateAddr); airdropAddr = _airdropAddr; oracleCallbackAddr = _oracleCallbackAddr; _tokenContractAddr = __tokenContractAddr; }
5,060,965
// File: browser/flattened.sol // File: browser/DateTime.sol pragma solidity >=0.4.21 <0.6.0; contract DateTime { /* * Date and Time utilities for ethereum contracts * */ struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) internal pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) internal pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) internal pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_DateTime memory dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) internal pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) internal pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) internal pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) internal pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) internal pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) internal pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) internal pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function toTimestamp(uint16 year, uint8 month, uint8 day) internal pure returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) internal pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) internal pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) internal pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } } // File: browser/Dependency.sol pragma solidity >=0.4.21 <0.6.0; contract Dependency is DateTime { /** * @dev struture to store File transfer related information */ struct FileProof { address sender; address receiver; bytes32 fileHash; uint256 timestamp; bytes32 QR; bytes32 QRTime; } /** * @dev structure to store Folder transfer related information */ struct FolderProof { address sender; address receiver; address folderAddress; bytes32 folderHash; uint256 timestamp; bytes32 QR; bytes32 QRTime; } struct FileQRWithIndex { bytes32 hashFile; uint256 index; } struct FolderQRWithIndex { address folderAddress; uint256 index; } /** * @dev mapping to map the proof and QR codes(both with and Without time) * @mapping fileProofs , map the struct of file proof with file hash as its key * @mapoing folderProofs , map the struct of folder proof with folder hash as its key * @mapping fileQrCodeWithoutTime , map the QR code with file hash as key . It helps in searching proof via QR * @mapping fileQrCodeWithTime , map the QR code with Time with file hash as key * @mapping folderQrCodeWithoutTime , map the QR code with folder address as key . It helps in searching proof via QR * @mapping folderQrCodeWithTime , map the QR code with Time with folder address as key */ mapping (bytes32 => FileProof[]) fileProofs; // this allows to look up proof of transfer by the hashfile mapping (address => FolderProof[]) folderProofs; mapping (bytes32 => FileQRWithIndex[]) fileQrCodeWithoutTime; // QrCode => hashFile mapping (bytes32 => FileQRWithIndex[]) fileQrCodeWithTime; mapping (bytes32 => FolderQRWithIndex[]) folderQrCodeWithoutTime; // QrCode => hashFile mapping (bytes32 => FolderQRWithIndex[]) folderQrCodeWithTime; mapping(bytes32 => bool) usedFileHashes; mapping(address => bool) usedFolderAddresses; /** * @dev supporting function for creating and storing Transfer proof */ function _inCreateFileTransferProof(address _sender, address _receiver, bytes32 _fileHash,uint256 time, bytes32 QRWithNoTime ,bytes32 QRWithTime) internal returns (bool) { FileProof memory currentInfo; currentInfo.sender = _sender; currentInfo.receiver = _receiver; currentInfo.fileHash = _fileHash; currentInfo.timestamp = time; currentInfo.QR = QRWithNoTime; currentInfo.QRTime = QRWithTime; // if the entry is already present in mapping with same File Proof then it add the info in the array of struct "FileProof" mapped to the specific file hash, // And if not present then creates the new entry fileProofs[_fileHash].push(currentInfo); uint256 index = fileProofs[_fileHash].length - 1; FileQRWithIndex memory indexInfo; indexInfo.hashFile = _fileHash; indexInfo.index = index; fileQrCodeWithoutTime[QRWithNoTime].push(indexInfo); fileQrCodeWithTime[QRWithTime].push(indexInfo); usedFileHashes[_fileHash] = true; return true; } /** * @dev supporting function for creating and storing Folder transfer proof */ function _inCreateFolderTransferProof(address _sender,address _receiver,address _folderAddress,bytes32 _folderHash,uint256 time,bytes32 QRWithNoTime,bytes32 QRWithTime) internal returns(bool) { FolderProof memory currentInfo; currentInfo.sender = _sender; currentInfo.receiver = _receiver; currentInfo.folderAddress = _folderAddress; currentInfo.folderHash = _folderHash; currentInfo.timestamp = time; currentInfo.QR = QRWithNoTime; currentInfo.QRTime = QRWithTime; // if the entry is already present in mapping with same folder address then it add the info in the array of struct "FolderProof" mapped to the specific address, // And if not present then creates the new entry folderProofs[_folderAddress].push(currentInfo); uint256 index = folderProofs[_folderAddress].length - 1; FolderQRWithIndex memory indexInfo; indexInfo.folderAddress = _folderAddress; indexInfo.index = index; folderQrCodeWithoutTime[QRWithNoTime].push(indexInfo); folderQrCodeWithTime[QRWithTime].push(indexInfo); usedFolderAddresses[_folderAddress] = true; return true; } /** * @dev returns array of all senders and receivers related to supplied file hash */ function _inGetFileTransferProofs(bytes32 fileHash, uint256 index) internal view returns (address[] memory, bytes32, bool) { address[] memory senderAndReceiver = new address[](2); senderAndReceiver[0] = fileProofs[fileHash][index].sender; senderAndReceiver[1] = fileProofs[fileHash][index].receiver; bytes32 QR = fileProofs[fileHash][index].QR; if(fileProofs[fileHash].length - 1 > index) { return(senderAndReceiver, QR, true); } else { return(senderAndReceiver, QR, false); } } /** * @dev calculates the day , month , year using the timestamp * @param time , timestamp whose day,month,year is to be calculated */ function getDateTime (uint256 time) internal pure returns(uint256,uint256,uint256) { uint256 year = getYear(time); uint256 month = getMonth(time); uint256 day = getDay(time); return (year, month, day ); } /** * @dev returns array of all day , month , year related to supplied file hash */ function _inGetFileTransferProofsDateTime(bytes32 fileHash,uint256 index ,uint256 len) internal view returns (address[] memory, bytes32, uint256[] memory,bool) { uint256 time = fileProofs[fileHash][index].timestamp; (uint256 year, uint256 month, uint256 day) = getDateTime(time); address[] memory senderAndReceiver = new address[](2); senderAndReceiver[0] = fileProofs[fileHash][index].sender; senderAndReceiver[1] = fileProofs[fileHash][index].receiver; bytes32 QR = fileProofs[fileHash][index].QRTime; uint256[] memory Date = new uint256[](3); Date[0] = day; Date[1] = month; Date[2] = year; if(len - 1 > index) { return(senderAndReceiver, QR, Date, true); } else { return(senderAndReceiver, QR, Date, false); } } /** * @dev returns array of all senders and receivers related to supplied folder Address */ function _inGetFolderTransferProofs(address folderAddress,uint256 index) internal view returns(address[] memory,bytes32 , bytes32, bool) { address[] memory senderAndReceiver = new address[](2); senderAndReceiver[0] = folderProofs[folderAddress][index].sender; senderAndReceiver[1] = folderProofs[folderAddress][index].receiver; bytes32 QR = folderProofs[folderAddress][index].QR; bytes32 folderHash = folderProofs[folderAddress][index].folderHash; if(folderProofs[folderAddress].length - 1 > index) { return(senderAndReceiver,folderHash, QR, true); } else { return(senderAndReceiver,folderHash,QR, false); } } /** * @dev returns array of all day , month , year related to supplied folder address */ function _inGetFolderTransferProofsWithDateTime(address folderAddress,uint256 index, uint256 len) internal view returns (address[] memory,bytes32,bytes32, uint256[] memory,bool) { uint256 time = folderProofs[folderAddress][index].timestamp; // (uint256 year, uint256 month, uint256 day) = getDateTime(time); address[] memory senderAndReceiver = new address[](2); senderAndReceiver[0] = folderProofs[folderAddress][index].sender; senderAndReceiver[1] = folderProofs[folderAddress][index].receiver; bytes32 folderHash = folderProofs[folderAddress][index].folderHash; bytes32 QR = folderProofs[folderAddress][index].QRTime; uint256[] memory Date = new uint256[](3); (Date[2],Date[1],Date[0])= getDateTime(time); if(len - 1 > index) { return(senderAndReceiver,folderHash ,QR,Date, true); } else { return(senderAndReceiver,folderHash, QR,Date, false); } } /** * @dev supporting function for searching file information via QR code */ function _InSearchFileTransferProof(bytes32 QRCode) internal view returns(address , address , bytes32) { bytes32 Hash; Hash = fileQrCodeWithoutTime[QRCode][0].hashFile; require(fileExists(Hash),"file does not exists"); uint256 index = fileQrCodeWithoutTime[QRCode][0].index; address sender = fileProofs[Hash][index].sender; address receiver = fileProofs[Hash][index].receiver; return (sender, receiver, Hash); } /** * @dev supporting function for searching file information with day , month , year via QR code */ function _InSearchFileTransferProofWithTime(bytes32 QRCode) internal view returns(address , address , uint256 , uint256 , uint256 ,bytes32) { bytes32 Hash; Hash = fileQrCodeWithTime[QRCode][0].hashFile; require(fileExists(Hash),"file does not exists"); uint256 index = fileQrCodeWithTime[QRCode][0].index; address sender = fileProofs[Hash][index].sender; address receiver = fileProofs[Hash][index].receiver; (uint256 year, uint256 month, uint256 day) = getDateTime(fileProofs[Hash][index].timestamp); return (sender, receiver, day, month, year, Hash); } /** * @dev supporting function for searching folder information via QR code */ function _InSearchFolderTransferProof(bytes32 QRCode) internal view returns(address , address , address , bytes32) { address folderAddress; folderAddress = folderQrCodeWithoutTime[QRCode][0].folderAddress; require(folderExists(folderAddress), "folder does not exist"); uint256 index = folderQrCodeWithoutTime[QRCode][0].index; address sender = folderProofs[folderAddress][index].sender; address receiver = folderProofs[folderAddress][index].receiver; bytes32 folderHash = folderProofs[folderAddress][index].folderHash; return (sender, receiver, folderAddress , folderHash); } /** * @dev supporting function for searching folder information with day , month , year via QR code */ function _InSearchFolderTransferProofWithTime(bytes32 QRCode) internal view returns(address ,address , address , bytes32,uint256 , uint256 , uint256) { address folderAddress; folderAddress = folderQrCodeWithTime[QRCode][0].folderAddress; require(folderExists(folderAddress), "folder does not exist"); uint256 index = folderQrCodeWithTime[QRCode][0].index; address sender = folderProofs[folderAddress][index].sender; address receiver = folderProofs[folderAddress][index].receiver; bytes32 folderHash = folderProofs[folderAddress][index].folderHash; (uint256 year, uint256 month, uint256 day) = getDateTime(folderProofs[folderAddress][index].timestamp); return (sender, receiver, folderAddress,folderHash, day, month, year); } /** * @dev checks file exists or not , using File Hash */ function fileExists(bytes32 fileHash)internal view returns (bool) { bool exists = false; if (usedFileHashes[fileHash]) { exists = true; } return exists; } /** * @dev checks folder exists or not , using folder addressn */ function folderExists(address folderAddress) internal view returns (bool) { bool exists = false; if (usedFolderAddresses[folderAddress]) { exists = true; } return exists; } } // File: browser/ProofOfTransfer.sol pragma solidity >=0.4.21 <0.6.0; contract ProofOfTransfer is Dependency { /** * @dev Creates and stores the File transfer proof at the block timestamp * timestamp in stored as no minor change in time shall be there at time of storing and creting QR hash * @param _sender , represents the entity who is sending the file * @param _receiver , represents the entity who is receiving the file * @param _fileHash , hash of file being transferred * @return bool , true if creates the file transfer proof entry successfully */ function createFileTransferProof(address _sender, address _receiver, bytes32 _fileHash) public returns (bool) { uint256 time = block.timestamp; bytes32 QRWithNoTime = getQRCodeForFile(_sender, _receiver, _fileHash, 0); bytes32 QRWithTime = getQRCodeForFile(_sender, _receiver,_fileHash, time); return _inCreateFileTransferProof(_sender,_receiver,_fileHash,time,QRWithNoTime,QRWithTime); } /** * @dev Creates and stores the Folder transfer proof at the block timestamp * @param _sender , represents the entity who is sending folder * @param _receiver , represents the entity who is receiving folder * @param _folderAddress , address of folder which is being send * @return bool , true if creates the fiolder transfer proof entry successfully */ function createFolderTransferProof(address _sender, address _receiver, address _folderAddress , bytes32 folderHash ) public returns(bool) { uint256 time = block.timestamp; bytes32 QRWithNoTime = getQRCodeForFolder(_sender, _receiver, _folderAddress,folderHash, 0); bytes32 QRWithTime = getQRCodeForFolder(_sender, _receiver, _folderAddress,folderHash, time); return _inCreateFolderTransferProof(_sender,_receiver,_folderAddress,folderHash,time,QRWithNoTime,QRWithTime); } /** * @dev get file transfer proof by using filehash * @param fileHash , hash of file , whose information is to be fetched * @return , address of sender , reciever and QR code */ function getFileTransferProofs(bytes32 fileHash, uint256 Index) public view returns(address[] memory,bytes32,bool) { require(fileExists(fileHash),"No file found"); (address[] memory senderAndReceiver,bytes32 QR,bool nextIndexPresent) = _inGetFileTransferProofs(fileHash, Index); return (senderAndReceiver,QR,nextIndexPresent); } /** * @dev get file transfer proof with time detail by using filehash * @param fileHash , hash of file , whose information is to be fetched * @return , address of sender , reciever and QR code with day ,month and year information also */ function getFileTransferProofWithTDateTime(bytes32 fileHash, uint256 Index) public view returns(address[] memory,bytes32, uint256[] memory,bool) { require(fileExists(fileHash),"No file found"); //sending length in this function to remove "STACK TOO DEEEP ERROR" uint256 len = fileProofs[fileHash].length; (address[] memory senderAndReceiver,bytes32 QR,uint256[] memory Date,bool nextIndexPresent) = _inGetFileTransferProofsDateTime(fileHash, Index ,len); return (senderAndReceiver,QR,Date,nextIndexPresent); } /** * @dev get folder transfer proof by using folder address * @param folderAddress , address of folder , whose information is to be fetched * @return , address of sender , reciever and QR code */ function getFolderTransferProofs(address folderAddress, uint256 Index) public view returns (address[] memory, bytes32,bytes32,bool) { require(folderExists(folderAddress),"No folder found"); (address[] memory senderAndReceiver ,bytes32 folderHash,bytes32 QR,bool nextIndexPresent) = _inGetFolderTransferProofs(folderAddress, Index); return (senderAndReceiver,folderHash,QR,nextIndexPresent); } /** * @dev get folder transfer proof by using folder address with date time details * @param folderAddress , address of folder , whose information is to be fetched * @return , address of sender , reciever and QR code with day ,month and year information also */ function getFolderTransferProofsWithDateTime(address folderAddress , uint256 Index) public view returns(address[] memory, bytes32,bytes32, uint256[] memory,bool) { require(folderExists(folderAddress),"No folder found"); //sending length in this function to remove "STACK TOO DEEEP ERROR" uint256 len = folderProofs[folderAddress].length; (address[] memory senderAndReceiver, bytes32 folderHash,bytes32 QR,uint256[] memory Date,bool nextIndexPresent) = _inGetFolderTransferProofsWithDateTime(folderAddress, Index, len); return (senderAndReceiver,folderHash,QR,Date,nextIndexPresent); } /** * @dev search file transfer proof using QR code * @param QRCode , whose information is to be fetched * @return , address of sender, reciever and fileHash */ function SearchFileTransferProof(bytes32 QRCode) public view returns(address , address ,bytes32) { return _InSearchFileTransferProof(QRCode); } /** * @dev search file transfer proof using QR code with time details * @param QRCodeTime , whose information is to be fetched * @return , address of sender, reciever and fileHash with day ,month and year information also */ function SearchFileTransferProofWithTime(bytes32 QRCodeTime) public view returns(address , address , uint256 , uint256 , uint256 ,bytes32) { return _InSearchFileTransferProofWithTime(QRCodeTime); } /** * @dev search folder transfer proof using QR code * @param QRCode , whose information is to be fetched * @return , address of sender, reciever and address of the folder */ function SearchFolderTransferProof(bytes32 QRCode) public view returns(address , address , address , bytes32) { return _InSearchFolderTransferProof(QRCode); } /** * @dev search folder transfer proof using QR code with time details * @param QRCodeTime , whose information is to be fetched * @return , address of sender, reciever and address of the folder with day ,month and year information also */ function SearchFolderTransferProofWithTime(bytes32 QRCodeTime) public view returns(address ,address , address, bytes32 , uint256 , uint256 , uint256) { return _InSearchFolderTransferProofWithTime(QRCodeTime); } /** * @dev generates the QR code using filehash ,etc * Can generate QR code with time and without time */ function getQRCodeForFile (address _sender, address _receiver,bytes32 fileHash, uint256 timestamp) internal pure returns (bytes32) { bytes32 QRCodeHash; if(timestamp == 0) //generate QR code without dateTime { QRCodeHash = keccak256(abi.encodePacked(_sender, _receiver,fileHash)); } else { (uint256 year, uint256 month, uint256 day) = getDateTime(timestamp); QRCodeHash = keccak256(abi.encodePacked(_sender, _receiver, fileHash, day, month, year)); } return QRCodeHash; } /** * @dev generates the QR code using Folder address , etc * Can generate QR code with time and without time */ function getQRCodeForFolder (address _sender, address _receiver,address folderAddress,bytes32 folderHash, uint256 timestamp) internal pure returns (bytes32) { bytes32 QRCodeHash; if(timestamp == 0) //generate QR code without dateTime { QRCodeHash = keccak256(abi.encodePacked(_sender, _receiver,folderAddress , folderHash)); } else { (uint256 year, uint256 month, uint256 day) = getDateTime(timestamp); QRCodeHash = keccak256(abi.encodePacked(_sender, _receiver,folderAddress,folderHash,day,month, year)); } return QRCodeHash; } }
calculates the day , month , year using the timestamp time , timestamp whose day,month,year is to be calculated/
function getDateTime (uint256 time) internal pure returns(uint256,uint256,uint256) { uint256 year = getYear(time); uint256 month = getMonth(time); uint256 day = getDay(time); return (year, month, day ); }
12,839,775
./partial_match/3/0x07262132632B7B965f22752cfC196427415e663e/sources/Dice.sol
Change Game Fee Percent/ Update Game Fee Percent Update Winner Fee Percent
function changeGameFeePercent(uint256 gameFeePercent) external onlyGovernance { _gameFeePercent = gameFeePercent; _winnerPercent = (uint256)(10000).sub(_gameFeePercent); emit ChangeGameFeePercent(governance(), gameFeePercent); emit ChangeWinnerPercent(governance(), _winnerPercent); }
5,260,641
./full_match/1/0xb40B94Cd4A9094DF607099fF8216Adb792733362/sources/contracts/AutomatedFunctionsConsumer.sol
Called by Automation to trigger a Functions request The function's argument is unused in this example, but there is an option to have Automation pass custom data returned by checkUpkeep (See Chainlink Automation documentation)/
function performUpkeep(bytes calldata) external override { (bool upkeepNeeded, ) = checkUpkeep(""); require(upkeepNeeded, "Time interval not met"); s_lastUpkeepTimeStamp = block.timestamp; _sendRequest(s_requestCBOR, s_subscriptionId, s_fulfillGasLimit, donId); }
17,068,605
./full_match/1/0xE2e3C6f8163a077cba241adc06dcE5828EF9cd8a/sources/DefiVeth.sol
1. User Accounting Redeem from most recent stake and go backwards in time. fully redeem a past stake partially redeem a past stake
function _withdraw(uint256 amount, bool unwrapFlag) internal { updateAccounting(); require(amount > 0, 'ERR: unstake amount is zero'); require(totalStakedFor(msg.sender) >= amount, 'ERR: unstake amount is greater than total user stakes'); uint256 stakingSharesToBurn = _totalStakingShares.mul(amount).div(totalStaked()); require(stakingSharesToBurn > 0, 'ERR: Unable to unstake amount this small'); UserTotals storage totals = _userTotals[msg.sender]; Stake[] storage accountStakes = _userStakes[msg.sender]; uint256 stakingShareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; while (sharesLeftToBurn > 0) { Stake storage lastStake = accountStakes[accountStakes.length - 1]; uint256 stakeTimeSec = now.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; if (lastStake.stakingShares <= sharesLeftToBurn) { newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares); accountStakes.pop(); newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn); sharesLeftToBurn = 0; } } totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn); totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn); _totalStakingShares = _totalStakingShares.sub(stakingSharesToBurn); uint256 stakingTokenBalance = _stakingToken.balanceOf(address(this)); uint256 vaultAmount = stakingTokenBalance.mul(totalStaked().sub(amount)).div(totalStaked()); _vTokenPool.withdraw(amount); stakingTokenBalance = _stakingToken.balanceOf(address(this)); if(vaultAmount < stakingTokenBalance) { uint256 withdrawAmount = stakingTokenBalance.sub(vaultAmount); if(unwrapFlag) { TokenLike(WETH).withdraw(withdrawAmount); msg.sender.transfer(withdrawAmount); } else _stakingToken.safeTransfer(msg.sender, withdrawAmount); } if(_stakingToken.balanceOf(address(this)) > 0) _vTokenPool.deposit(_stakingToken.balanceOf(address(this))); emit Unstaked(msg.sender, amount); require(_totalStakingShares == 0 || totalStaked() > 0, "ERR: Error unstaking. Staking shares exist, but no staking tokens do"); }
2,898,271
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IExchange.sol"; import "./interfaces/ISortedOracles.sol"; import "./interfaces/IReserve.sol"; import "./interfaces/IStableToken.sol"; import "../common/Initializable.sol"; import "../common/FixidityLib.sol"; import "../common/Freezable.sol"; import "../common/UsingRegistry.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title Contract that allows to exchange StableToken for GoldToken and vice versa * using a Constant Product Market Maker Model */ contract Exchange is IExchange, ICeloVersionedContract, Initializable, Ownable, UsingRegistry, ReentrancyGuard, Freezable { using SafeMath for uint256; using FixidityLib for FixidityLib.Fraction; event Exchanged(address indexed exchanger, uint256 sellAmount, uint256 buyAmount, bool soldGold); event UpdateFrequencySet(uint256 updateFrequency); event MinimumReportsSet(uint256 minimumReports); event StableTokenSet(address indexed stable); event SpreadSet(uint256 spread); event ReserveFractionSet(uint256 reserveFraction); event BucketsUpdated(uint256 goldBucket, uint256 stableBucket); FixidityLib.Fraction public spread; // Fraction of the Reserve that is committed to the gold bucket when updating // buckets. FixidityLib.Fraction public reserveFraction; address public stable; // Size of the Uniswap gold bucket uint256 public goldBucket; // Size of the Uniswap stable token bucket uint256 public stableBucket; uint256 public lastBucketUpdate = 0; uint256 public updateFrequency; uint256 public minimumReports; modifier updateBucketsIfNecessary() { _updateBucketsIfNecessary(); _; } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 1, 0); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param stableToken Address of the stable token * @param _spread Spread charged on exchanges * @param _reserveFraction Fraction to commit to the gold bucket * @param _updateFrequency The time period that needs to elapse between bucket * updates * @param _minimumReports The minimum number of fresh reports that need to be * present in the oracle to update buckets * commit to the gold bucket */ function initialize( address registryAddress, address stableToken, uint256 _spread, uint256 _reserveFraction, uint256 _updateFrequency, uint256 _minimumReports ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setStableToken(stableToken); setSpread(_spread); setReserveFraction(_reserveFraction); setUpdateFrequency(_updateFrequency); setMinimumReports(_minimumReports); _updateBucketsIfNecessary(); } /** * @notice Exchanges a specific amount of one token for an unspecified amount * (greater than a threshold) of another. * @param sellAmount The number of tokens to send to the exchange. * @param minBuyAmount The minimum number of tokens for the exchange to send in return. * @param sellGold True if the caller is sending CELO to the exchange, false otherwise. * @return The number of tokens sent by the exchange. * @dev The caller must first have approved `sellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function sell(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) public onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 buyAmount = _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); require(buyAmount >= minBuyAmount, "Calculated buyAmount was less than specified minBuyAmount"); _exchange(sellAmount, buyAmount, sellGold); return buyAmount; } /** * @dev DEPRECATED - Use `buy` or `sell`. * @notice Exchanges a specific amount of one token for an unspecified amount * (greater than a threshold) of another. * @param sellAmount The number of tokens to send to the exchange. * @param minBuyAmount The minimum number of tokens for the exchange to send in return. * @param sellGold True if the caller is sending CELO to the exchange, false otherwise. * @return The number of tokens sent by the exchange. * @dev The caller must first have approved `sellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function exchange(uint256 sellAmount, uint256 minBuyAmount, bool sellGold) external returns (uint256) { return sell(sellAmount, minBuyAmount, sellGold); } /** * @notice Exchanges an unspecified amount (up to a threshold) of one token for * a specific amount of another. * @param buyAmount The number of tokens for the exchange to send in return. * @param maxSellAmount The maximum number of tokens to send to the exchange. * @param buyGold True if the exchange is sending CELO to the caller, false otherwise. * @return The number of tokens sent to the exchange. * @dev The caller must first have approved `maxSellAmount` to the exchange. * @dev This function can be frozen via the Freezable interface. */ function buy(uint256 buyAmount, uint256 maxSellAmount, bool buyGold) external onlyWhenNotFrozen updateBucketsIfNecessary nonReentrant returns (uint256) { bool sellGold = !buyGold; (uint256 buyTokenBucket, uint256 sellTokenBucket) = _getBuyAndSellBuckets(sellGold); uint256 sellAmount = _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); require( sellAmount <= maxSellAmount, "Calculated sellAmount was greater than specified maxSellAmount" ); _exchange(sellAmount, buyAmount, sellGold); return sellAmount; } /** * @notice Exchanges a specific amount of one token for a specific amount of another. * @param sellAmount The number of tokens to send to the exchange. * @param buyAmount The number of tokens for the exchange to send in return. * @param sellGold True if the msg.sender is sending CELO to the exchange, false otherwise. */ function _exchange(uint256 sellAmount, uint256 buyAmount, bool sellGold) private { IReserve reserve = IReserve(registry.getAddressForOrDie(RESERVE_REGISTRY_ID)); if (sellGold) { goldBucket = goldBucket.add(sellAmount); stableBucket = stableBucket.sub(buyAmount); require( getGoldToken().transferFrom(msg.sender, address(reserve), sellAmount), "Transfer of sell token failed" ); require(IStableToken(stable).mint(msg.sender, buyAmount), "Mint of stable token failed"); } else { stableBucket = stableBucket.add(sellAmount); goldBucket = goldBucket.sub(buyAmount); require( IERC20(stable).transferFrom(msg.sender, address(this), sellAmount), "Transfer of sell token failed" ); IStableToken(stable).burn(sellAmount); require(reserve.transferExchangeGold(msg.sender, buyAmount), "Transfer of buyToken failed"); } emit Exchanged(msg.sender, sellAmount, buyAmount, sellGold); } /** * @notice Returns the amount of buy tokens a user would get for sellAmount of the sell token. * @param sellAmount The amount of sellToken the user is selling to the exchange. * @param sellGold `true` if gold is the sell token. * @return The corresponding buyToken amount. */ function getBuyTokenAmount(uint256 sellAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getBuyTokenAmount(buyTokenBucket, sellTokenBucket, sellAmount); } /** * @notice Returns the amount of sell tokens a user would need to exchange to receive buyAmount of * buy tokens. * @param buyAmount The amount of buyToken the user would like to purchase. * @param sellGold `true` if gold is the sell token. * @return The corresponding sellToken amount. */ function getSellTokenAmount(uint256 buyAmount, bool sellGold) external view returns (uint256) { (uint256 buyTokenBucket, uint256 sellTokenBucket) = getBuyAndSellBuckets(sellGold); return _getSellTokenAmount(buyTokenBucket, sellTokenBucket, buyAmount); } /** * @notice Returns the buy token and sell token bucket sizes, in order. The ratio of * the two also represents the exchange rate between the two. * @param sellGold `true` if gold is the sell token. * @return (buyTokenBucket, sellTokenBucket) */ function getBuyAndSellBuckets(bool sellGold) public view returns (uint256, uint256) { uint256 currentGoldBucket = goldBucket; uint256 currentStableBucket = stableBucket; if (shouldUpdateBuckets()) { (currentGoldBucket, currentStableBucket) = getUpdatedBuckets(); } if (sellGold) { return (currentStableBucket, currentGoldBucket); } else { return (currentGoldBucket, currentStableBucket); } } /** * @notice Allows owner to set the update frequency * @param newUpdateFrequency The new update frequency */ function setUpdateFrequency(uint256 newUpdateFrequency) public onlyOwner { updateFrequency = newUpdateFrequency; emit UpdateFrequencySet(newUpdateFrequency); } /** * @notice Allows owner to set the minimum number of reports required * @param newMininumReports The new update minimum number of reports required */ function setMinimumReports(uint256 newMininumReports) public onlyOwner { minimumReports = newMininumReports; emit MinimumReportsSet(newMininumReports); } /** * @notice Allows owner to set the Stable Token address * @param newStableToken The new address for Stable Token */ function setStableToken(address newStableToken) public onlyOwner { stable = newStableToken; emit StableTokenSet(newStableToken); } /** * @notice Allows owner to set the spread * @param newSpread The new value for the spread */ function setSpread(uint256 newSpread) public onlyOwner { spread = FixidityLib.wrap(newSpread); emit SpreadSet(newSpread); } /** * @notice Allows owner to set the Reserve Fraction * @param newReserveFraction The new value for the reserve fraction */ function setReserveFraction(uint256 newReserveFraction) public onlyOwner { reserveFraction = FixidityLib.wrap(newReserveFraction); require(reserveFraction.lt(FixidityLib.fixed1()), "reserve fraction must be smaller than 1"); emit ReserveFractionSet(newReserveFraction); } /** * @notice Returns the sell token and buy token bucket sizes, in order. The ratio of * the two also represents the exchange rate between the two. * @param sellGold `true` if gold is the sell token. * @return (sellTokenBucket, buyTokenBucket) */ function _getBuyAndSellBuckets(bool sellGold) private view returns (uint256, uint256) { if (sellGold) { return (stableBucket, goldBucket); } else { return (goldBucket, stableBucket); } } /** * @dev Returns the amount of buy tokens a user would get for sellAmount of the sell. * @param buyTokenBucket The buy token bucket size. * @param sellTokenBucket The sell token bucket size. * @param sellAmount The amount the user is selling to the exchange. * @return The corresponding buy amount. */ function _getBuyTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 sellAmount) private view returns (uint256) { if (sellAmount == 0) return 0; FixidityLib.Fraction memory reducedSellAmount = getReducedSellAmount(sellAmount); FixidityLib.Fraction memory numerator = reducedSellAmount.multiply( FixidityLib.newFixed(buyTokenBucket) ); FixidityLib.Fraction memory denominator = FixidityLib.newFixed(sellTokenBucket).add( reducedSellAmount ); // Can't use FixidityLib.divide because denominator can easily be greater // than maxFixedDivisor. // Fortunately, we expect an integer result, so integer division gives us as // much precision as we could hope for. return numerator.unwrap().div(denominator.unwrap()); } /** * @notice Returns the amount of sell tokens a user would need to exchange to receive buyAmount of * buy tokens. * @param buyTokenBucket The buy token bucket size. * @param sellTokenBucket The sell token bucket size. * @param buyAmount The amount the user is buying from the exchange. * @return The corresponding sell amount. */ function _getSellTokenAmount(uint256 buyTokenBucket, uint256 sellTokenBucket, uint256 buyAmount) private view returns (uint256) { if (buyAmount == 0) return 0; FixidityLib.Fraction memory numerator = FixidityLib.newFixed(buyAmount.mul(sellTokenBucket)); FixidityLib.Fraction memory denominator = FixidityLib .newFixed(buyTokenBucket.sub(buyAmount)) .multiply(FixidityLib.fixed1().subtract(spread)); // See comment in _getBuyTokenAmount return numerator.unwrap().div(denominator.unwrap()); } function getUpdatedBuckets() private view returns (uint256, uint256) { uint256 updatedGoldBucket = getUpdatedGoldBucket(); uint256 exchangeRateNumerator; uint256 exchangeRateDenominator; (exchangeRateNumerator, exchangeRateDenominator) = getOracleExchangeRate(); uint256 updatedStableBucket = exchangeRateNumerator.mul(updatedGoldBucket).div( exchangeRateDenominator ); return (updatedGoldBucket, updatedStableBucket); } function getUpdatedGoldBucket() private view returns (uint256) { uint256 reserveGoldBalance = getReserve().getUnfrozenReserveGoldBalance(); return reserveFraction.multiply(FixidityLib.newFixed(reserveGoldBalance)).fromFixed(); } /** * @notice If conditions are met, updates the Uniswap bucket sizes to track * the price reported by the Oracle. */ function _updateBucketsIfNecessary() private { if (shouldUpdateBuckets()) { // solhint-disable-next-line not-rely-on-time lastBucketUpdate = now; (goldBucket, stableBucket) = getUpdatedBuckets(); emit BucketsUpdated(goldBucket, stableBucket); } } /** * @notice Calculates the sell amount reduced by the spread. * @param sellAmount The original sell amount. * @return The reduced sell amount, computed as (1 - spread) * sellAmount */ function getReducedSellAmount(uint256 sellAmount) private view returns (FixidityLib.Fraction memory) { return FixidityLib.fixed1().subtract(spread).multiply(FixidityLib.newFixed(sellAmount)); } /* * @notice Checks conditions required for bucket updates. * @return Whether or not buckets should be updated. */ function shouldUpdateBuckets() private view returns (bool) { ISortedOracles sortedOracles = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ); (bool isReportExpired, ) = sortedOracles.isOldestReportExpired(stable); // solhint-disable-next-line not-rely-on-time bool timePassed = now >= lastBucketUpdate.add(updateFrequency); bool enoughReports = sortedOracles.numRates(stable) >= minimumReports; // solhint-disable-next-line not-rely-on-time bool medianReportRecent = sortedOracles.medianTimestamp(stable) > now.sub(updateFrequency); return timePassed && enoughReports && medianReportRecent && !isReportExpired; } function getOracleExchangeRate() private view returns (uint256, uint256) { uint256 rateNumerator; uint256 rateDenominator; (rateNumerator, rateDenominator) = ISortedOracles( registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID) ) .medianRate(stable); require(rateDenominator > 0, "exchange rate denominator must be greater than 0"); return (rateNumerator, rateDenominator); } }
Allows owner to set the update frequency newUpdateFrequency The new update frequency/
function setUpdateFrequency(uint256 newUpdateFrequency) public onlyOwner { updateFrequency = newUpdateFrequency; emit UpdateFrequencySet(newUpdateFrequency); }
2,472,857
./full_match/42/0x85782998fc924dB5803968F000367c844526e65c/sources/contracts/xtmcswap.sol
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); payOrLockupPendingXtmc(_pid); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accXtmcPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
9,576,229
pragma solidity ^0.4.18; /** * @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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner,newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface token { function balanceOf(address who) external constant returns (uint256); function transfer(address to, uint256 value) external returns (bool); function getTotalSupply() external view returns (uint256); } contract ApolloSeptemBaseCrowdsale { using SafeMath for uint256; // The token being sold token public tokenReward; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // token address address public tokenAddress; // amount of raised money in wei uint256 public weiRaised; // ICO period (includes holidays) uint public constant ICO_PERIOD = 180 days; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event ApolloSeptemTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event ApolloSeptemTokenSpecialPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); function ApolloSeptemBaseCrowdsale(address _wallet, address _tokens) public{ require(_wallet != address(0)); tokenAddress = _tokens; tokenReward = token(tokenAddress); wallet = _wallet; } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token to be substracted uint256 tokens = computeTokens(weiAmount); require(isWithinTokenAllocLimit(tokens)); // update state weiRaised = weiRaised.add(weiAmount); // send tokens to beneficiary tokenReward.transfer(beneficiary, tokens); ApolloSeptemTokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } //transfer used for special contribuitions function specialTransfer(address _to, uint _amount) internal returns(bool){ require(_to != address(0)); require(_amount > 0); // calculate token to be substracted uint256 tokens = _amount * (10 ** 18); tokenReward.transfer(_to, tokens); ApolloSeptemTokenSpecialPurchase(msg.sender, _to, tokens); return true; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase && isWithinICOTimeLimit(); } function isWithinICOTimeLimit() internal view returns (bool) { return now <= endTime; } function isWithinICOLimit(uint256 _tokens) internal view returns (bool) { return tokenReward.balanceOf(this).sub(_tokens) >= 0; } function isWithinTokenAllocLimit(uint256 _tokens) internal view returns (bool) { return (isWithinICOTimeLimit() && isWithinICOLimit(_tokens)); } function sendAllToOwner(address beneficiary) internal returns(bool){ tokenReward.transfer(beneficiary, tokenReward.balanceOf(this)); return true; } function computeTokens(uint256 weiAmount) internal pure returns (uint256) { // 1 ETH = 4200 APO return weiAmount.mul(4200); } } /** * @title ApolloSeptemCappedCrowdsale * @dev Extension of ApolloSeptemBaseCrowdsale with a max amount of funds raised */ contract ApolloSeptemCappedCrowdsale is ApolloSeptemBaseCrowdsale{ using SafeMath for uint256; // HARD_CAP = 30,000 ether uint256 public constant HARD_CAP = (3 ether)*(10**4); function ApolloSeptemCappedCrowdsale() public {} // overriding ApolloSeptemBaseCrowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= HARD_CAP; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= HARD_CAP; return super.hasEnded() || capReached; } } /** * @title ApolloSeptemCrowdsaleExtended * @dev This is ApolloSeptem's crowdsale contract. */ contract ApolloSeptemCrowdsaleExtended is ApolloSeptemCappedCrowdsale, Ownable { bool public isFinalized = false; bool public isStarted = false; event ApolloSeptemStarted(); event ApolloSeptemFinalized(); function ApolloSeptemCrowdsaleExtended(address _wallet,address _tokensAddress) public ApolloSeptemCappedCrowdsale() ApolloSeptemBaseCrowdsale(_wallet,_tokensAddress) {} /** * @dev Must be called to start the crowdsale. */ function start(uint256 _weiRaised) onlyOwner public { require(!isStarted); starting(_weiRaised); ApolloSeptemStarted(); isStarted = true; } function starting(uint256 _weiRaised) internal { startTime = now; weiRaised = _weiRaised; endTime = startTime + ICO_PERIOD; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); ApolloSeptemFinalized(); isFinalized = true; } /** * @dev Must be called only in special cases */ function apolloSpecialTransfer(address _beneficiary, uint _amount) onlyOwner public { specialTransfer(_beneficiary, _amount); } /** *@dev Must be called after the crowdsale ends, to send the remaining tokens back to owner **/ function sendRemaningBalanceToOwner(address _tokenOwner) onlyOwner public { require(_tokenOwner != address(0)); sendAllToOwner(_tokenOwner); } }
event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased/
function ApolloSeptemBaseCrowdsale(address _wallet, address _tokens) public{ require(_wallet != address(0)); tokenAddress = _tokens; tokenReward = token(tokenAddress); wallet = _wallet; }
224,841
pragma solidity ^0.4.24; // Sources: // - Open Zeppelin: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721BasicToken.sol // - CryptoKitties // - CryptoZombies import "./ERC721.sol"; import "./ERC165.sol"; import "./TicketSale.sol"; import "zeppelin/math/SafeMath.sol"; /** @title Ticket Ownership * This contract is the one that is deployed for this dApp. * It inherits TicketSale in order to deploye all the logic, * and it adds ERC721 nature to the ticket tokens. In order * for that to happen, ERC165 is also necessary. * * The documentation for all the implemented methods in this * file are in its respective interfaces contracts */ contract TicketOwnership is TicketSale, ERC721, ERC165 { using SafeMath for uint256; mapping (bytes4 => bool) internal supportedInterfaces; mapping (uint256 => address) tokenApprovals; mapping (address => mapping (address => bool)) internal operatorApprovals; // TicketSale modifier to inherit the contract constructor( string _name, string _ipfsMetaData, uint32 _maxTickets, uint8 _maxTicketsPerPerson, uint256 _ticketPrice ) public TicketSale(_name, _ipfsMetaData, _maxTickets, _maxTicketsPerPerson, _ticketPrice) { //ERC165 compliant: supports ER721 interface //supportedInterfaces[this.supportsInterface.selector] = true; supportedInterfaces[0x80ac58cd] = true; } function supportsInterface(bytes4 interfaceID) external view returns (bool){ return supportedInterfaces[interfaceID]; } 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) external view returns (uint256) { require(_owner != address(0)); return ownerToTickets[_owner].length; } function ownerOf(uint256 _tokenId) public view returns (address) { address ticketOwner = ticketToOwner[_tokenId]; require(ticketOwner != address(0)); return ticketToOwner[_tokenId]; } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable { transferFrom(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable { safeTransferFrom(_from, _to, _tokenId, ""); } function transferFrom(address _from, address _to, uint256 _tokenId) public payable { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_to != address(0)); tokenApprovals[_tokenId] = address(0); // Delete token for (uint i = 0; i < ownerToTickets[_from].length-1; i++){ if (ownerToTickets[_from][i] == _tokenId) { /*// delete token delete ownerToTickets[_from][i]; // fill the empty spot with the last element ownerToTickets[_from][i] = ownerToTickets[_from][ownerToTickets[_from].length-1]; // delete last element delete ownerToTickets[_from][ownerToTickets[_from].length-1]; // stop loop, we already found the ticket to delete ownerToTickets[_from].length--; */ // BETTER WAY // Assign last token to the token we are transferring ownerToTickets[_from][i] = ownerToTickets[_from][ownerToTickets[_from].length-1]; // Delete duplicate token at the end ownerToTickets[_from].length--; break; } } // Add token ticketToOwner[_tokenId] = _to; ownerToTickets[_to].push(_tokenId); emit Transfer(_from, _to, _tokenId); } function approve(address _approved, uint256 _tokenId) external payable { address token_owner = ownerOf(_tokenId); require(_approved != token_owner); require(msg.sender == token_owner || isApprovedForAll(token_owner, msg.sender)); // The receiver of the token can't possess more tokens than maxTicketsPerPerson require(ownerToTickets[_approved].length < maxTicketsPerPerson); tokenApprovals[_tokenId] = _approved; emit Approval(token_owner, _approved, _tokenId); } function setApprovalForAll(address _operator, bool _approved) external { require(_operator != msg.sender); operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @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) { address token_owner = ownerOf(_tokenId); return ( _spender == token_owner || getApproved(_tokenId) == _spender || isApprovedForAll(token_owner, _spender) ); } function ticketsOf(address _owner) external view returns (uint256[]) { return ownerToTickets[_owner]; } }
The receiver of the token can't possess more tokens than maxTicketsPerPerson
function approve(address _approved, uint256 _tokenId) external payable { address token_owner = ownerOf(_tokenId); require(_approved != token_owner); require(msg.sender == token_owner || isApprovedForAll(token_owner, msg.sender)); require(ownerToTickets[_approved].length < maxTicketsPerPerson); tokenApprovals[_tokenId] = _approved; emit Approval(token_owner, _approved, _tokenId); }
977,585
pragma solidity 0.5.12; import { Context } from "@openzeppelin/contracts/GSN/Context.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol"; import { IERC777Recipient } from "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import { IERC777Sender } from "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { IERC1820Registry } from "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import { RuntimeConstants } from "./RuntimeConstants.sol"; // ERC777 is inlined because we need to change `_callTokensToSend` to protect against Uniswap replay attacks /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is RuntimeConstants, Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; // KEYDONIX: Protect against Uniswap Exchange reentrancy bug: https://blog.openzeppelin.com/exploiting-uniswap-from-reentrancy-to-actual-profit/ bool uniswapExchangeReentrancyGuard = false; /** * @dev `defaultOperators` may be an empty array. */ constructor(string memory name, string memory symbol, address[] memory defaultOperators) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(_msgSender(), _msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes calldata data) external { _burn(_msgSender(), _msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend(address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(_msgSender(), sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(_msgSender(), account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); // KEYDONIX: Block re-entrancy specifically for uniswap, which is vulnerable to ERC-777 tokens if (msg.sender == uniswapExchange) { require(!uniswapExchangeReentrancyGuard, "Attempted to execute a Uniswap exchange while in the middle of a Uniswap exchange"); uniswapExchangeReentrancyGuard = true; } _callTokensToSend(spender, holder, recipient, amount, "", ""); if (msg.sender == uniswapExchange) { uniswapExchangeReentrancyGuard = false; } _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint(address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData) internal { require(account != address(0), "ERC777: mint to the zero address"); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } // KEYDONIX: changed visibility from private to internal, we reference this function in derived contract /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // KEYDONIX: changed visibility from private to internal, we reference this function in derived contract /** * @dev Burn tokens * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn(address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData) internal { require(from != address(0), "ERC777: burn from the zero address"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private { _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) private { // TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is // currently unnecessary. //require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private { address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) private { address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } } contract MakerFunctions { // KEYDONIX: Renamed from `rmul` for clarity // KEYDONIX: Changed ONE to 10**27 for clarity function safeMul27(uint x, uint y) internal pure returns (uint z) { z = safeMul(x, y) / 10 ** 27; } function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } // KEYDONIX: Renamed from `mul` due to shadowing warning from Solidity function safeMul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } } contract ReverseRegistrar { function setName(string memory name) public returns (bytes32 node); } contract DaiHrd is ERC777, MakerFunctions { event Deposit(address indexed from, uint256 depositedAttodai, uint256 mintedAttodaiHrd); event Withdrawal(address indexed from, address indexed to, uint256 withdrawnAttodai, uint256 burnedAttodaiHrd); event DepositVatDai(address indexed account, uint256 depositedAttorontodai, uint256 mintedAttodaiHrd); event WithdrawalVatDai(address indexed from, address indexed to, uint256 withdrawnAttorontodai, uint256 burnedAttodaiHrd); // uses this super constructor syntax instead of the preferred alternative syntax because my editor doesn't like the class syntax constructor(ReverseRegistrar reverseRegistrar) ERC777("DAI-HRD", "DAI-HRD", new address[](0)) public { dai.approve(address(daiJoin), uint(-1)); vat.hope(address(pot)); vat.hope(address(daiJoin)); if (reverseRegistrar != ReverseRegistrar(0)) { reverseRegistrar.setName("dai-hrd.eth"); } } function deposit(uint256 attodai) external returns(uint256 attodaiHrd) { dai.transferFrom(msg.sender, address(this), attodai); daiJoin.join(address(this), dai.balanceOf(address(this))); uint256 depositedAttopot = depositVatDaiForAccount(msg.sender); emit Deposit(msg.sender, attodai, depositedAttopot); return depositedAttopot; } // If the user has vat dai directly (after performing vault actions, for instance), they don't need to create the DAI ERC20 just so we can burn it, we'll accept vat dai function depositVatDai(uint256 attorontovatDai) external returns(uint256 attodaiHrd) { vat.move(msg.sender, address(this), attorontovatDai); uint256 depositedAttopot = depositVatDaiForAccount(msg.sender); emit DepositVatDai(msg.sender, attorontovatDai, depositedAttopot); return depositedAttopot; } function withdrawTo(address recipient, uint256 attodaiHrd) external returns(uint256 attodai) { // Don't need rontodaiPerPot, so we don't call updateAndFetchChi if (pot.rho() != now) pot.drip(); return withdraw(recipient, attodaiHrd); } function withdrawToDenominatedInDai(address recipient, uint256 attodai) external returns(uint256 attodaiHrd) { uint256 rontodaiPerPot = updateAndFetchChi(); attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); uint256 attodaiWithdrawn = withdraw(recipient, attodaiHrd); require(attodaiWithdrawn >= attodai, "DaiHrd/withdrawToDenominatedInDai: Not withdrawing enough DAI to cover request"); return attodaiHrd; } function withdrawVatDai(address recipient, uint256 attodaiHrd) external returns(uint256 attorontodai) { require(recipient != address(0) && recipient != address(this), "DaiHrd/withdrawVatDai: Invalid recipient"); // Don't need rontodaiPerPot, so we don't call updateAndFetchChi if (pot.rho() != now) pot.drip(); _burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0)); pot.exit(attodaiHrd); attorontodai = vat.dai(address(this)); vat.move(address(this), recipient, attorontodai); emit WithdrawalVatDai(msg.sender, recipient, attorontodai, attodaiHrd); return attorontodai; } // Dai specific functions. These functions all behave similar to standard ERC777 functions with input or output denominated in Dai instead of DaiHrd function balanceOfDenominatedInDai(address tokenHolder) external view returns(uint256 attodai) { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = balanceOf(tokenHolder); return convertAttodaiHrdToAttodai(attodaiHrd, rontodaiPerPot); } function totalSupplyDenominatedInDai() external view returns(uint256 attodai) { uint256 rontodaiPerPot = calculatedChi(); return convertAttodaiHrdToAttodai(totalSupply(), rontodaiPerPot); } function sendDenominatedInDai(address recipient, uint256 attodai, bytes calldata data) external { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _send(_msgSender(), _msgSender(), recipient, attodaiHrd, data, "", true); } function burnDenominatedInDai(uint256 attodai, bytes calldata data) external { uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _burn(_msgSender(), _msgSender(), attodaiHrd, data, ""); } function operatorSendDenominatedInDai(address sender, address recipient, uint256 attodai, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _send(_msgSender(), sender, recipient, attodaiHrd, data, operatorData, true); } function operatorBurnDenominatedInDai(address account, uint256 attodai, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); uint256 rontodaiPerPot = calculatedChi(); uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot); _burn(_msgSender(), account, attodaiHrd, data, operatorData); } // Utility Functions function calculatedChi() public view returns (uint256 rontodaiPerPot) { // mirrors Maker's calculation: rmul(rpow(dsr, now - rho, ONE), chi); return safeMul27(rpow(pot.dsr(), now - pot.rho(), 10 ** 27), pot.chi()); } function convertAttodaiToAttodaiHrd(uint256 attodai, uint256 rontodaiPerPot ) private pure returns (uint256 attodaiHrd) { // + 1 is to compensate rounding? since attodaiHrd is rounded down return attodai.mul(10 ** 27).add(rontodaiPerPot - 1).div(rontodaiPerPot); } function convertAttodaiHrdToAttodai(uint256 attodaiHrd, uint256 rontodaiPerPot ) private pure returns (uint256 attodai) { return attodaiHrd.mul(rontodaiPerPot).div(10 ** 27); } function updateAndFetchChi() private returns (uint256 rontodaiPerPot) { return (pot.rho() == now) ? pot.chi() : pot.drip(); } // Takes whatever vat dai has already been transferred to DaiHrd, gives to pot (DSR) and mints tokens for user function depositVatDaiForAccount(address account) private returns (uint256 attopotDeposited) { uint256 rontodaiPerPot = updateAndFetchChi(); uint256 attopotToDeposit = vat.dai(address(this)) / rontodaiPerPot; pot.join(attopotToDeposit); _mint(address(0), account, attopotToDeposit, new bytes(0), new bytes(0)); return attopotToDeposit; } // Internal implementations of functions with multiple entrypoints. drip() should be called prior to this call function withdraw(address recipient, uint256 attodaiHrd) private returns(uint256 attodaiWithdrawn) { require(recipient != address(0) && recipient != address(this), "DaiHrd/withdraw: Invalid recipient"); _burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0)); pot.exit(attodaiHrd); daiJoin.exit(address(this), vat.dai(address(this)) / 10**27); uint256 attodai = dai.balanceOf(address(this)); dai.transfer(recipient, attodai); emit Withdrawal(msg.sender, recipient, attodai, attodaiHrd); return attodai; } }
Update state variables
function _burn(address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData) internal { require(from != address(0), "ERC777: burn from the zero address"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); }
2,521,565
./full_match/41/0x7fBF8BA56B0697ff2450cBf27F17954496a1c0c9/sources/contracts/ZombieVan.sol
Returns the multiplier needed to calculate the user shares
function userMultiplier(address user) public view returns (uint256) { uint256 multiplier = 0; for (uint256 c = 0; c < _nftCollections.length; c++) { IERC721 nftCollection = _nftCollections[c]; uint256 nftBalance = nftCollection.balanceOf(user); if (nftBalance == 0) continue; multiplier += nftBalance * nftMultipliers[c]; } return multiplier; }
16,375,993
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "./IERC1190.sol"; import "./IERC1190Metadata.sol"; import "./IERC1190OwnershipLicenseReceiver.sol"; import "./IERC1190CreativeLicenseReceiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of IERC1190.sol and IERC1190Metadata.sol. */ contract ERC1190 is Context, ERC165, IERC1190, IERC1190Metadata { 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 from token ID to creative owner address mapping(uint256 => address) private _creativeOwners; // Mapping from token ID to renters address mapping(uint256 => mapping(address => uint256)) private _renters; // Mapping from token ID to renters addresses mapping(uint256 => address[]) private _renterLists; // Mapping owner address to token count mapping(address => uint256) private _ownerBalances; // Mapping creative owner address to token count mapping(address => uint256) private _creativeOwnerBalances; // Mapping renter address to token count mapping(address => uint256) private _renterBalances; // Mapping from token ID to approved address for ownership license mapping(uint256 => address) private _tokenApprovalsFromOwner; // Mapping from owner to operator approvals for ownership license mapping(address => mapping(address => bool)) private _operatorApprovalsFromOwner; // Mapping from token ID to approved address for creative license mapping(uint256 => address) private _tokenApprovalsFromCreativeOwner; // Mapping from owner to operator approvals for creative license mapping(address => mapping(address => bool)) private _operatorApprovalsFromCreativeOwner; // Mapping from token ID to rotyaltyForRental mapping(uint256 => uint8) private _royaltiesForRental; // Mapping from token ID to rotyaltyForOwnershipTransfer mapping(uint256 => uint8) private _royaltiesForOwnershipTransfer; // Mapping from token to file. mapping(uint256 => string) private _files; /** * @dev Initializes the contract by setting a `tokenName` and a `tokenSymbol` to the token collection. */ constructor(string memory tokenName, string memory tokenSymbol) { _name = tokenName; _symbol = tokenSymbol; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1190).interfaceId || interfaceId == type(IERC1190Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1190-balanceOfOwner}. */ function balanceOfOwner(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC1190: owner cannot be the zero address." ); return _ownerBalances[owner]; } /** * @dev See {IERC1190-balanceOfCreativeOwner}. */ function balanceOfCreativeOwner(address creativeOwner) public view virtual override returns (uint256) { require( creativeOwner != address(0), "ERC1190: creativeOwner cannot be the zero address." ); return _creativeOwnerBalances[creativeOwner]; } /** * @dev See {IERC1190-balanceOfRenter}. */ function balanceOfRenter(address renter) public view virtual override returns (uint256) { require( renter != address(0), "ERC1190: renter cannot be the zero address." ); return _renterBalances[renter]; } /** * @dev See {IERC1190-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC1190: Nobody has ownership over tokenId." ); return owner; } /** * @dev See {IERC1190-creativeOwnerOf}. */ function creativeOwnerOf(uint256 tokenId) public view virtual override returns (address) { address creativeOwner = _creativeOwners[tokenId]; require( creativeOwner != address(0), "ERC1190: Nobody has creative ownership over tokenId." ); return creativeOwner; } /** * @dev See {IERC1190-rentersOf}. */ function rentersOf(uint256 tokenId) public view virtual override returns (address[] memory) { return _renterLists[tokenId]; } /** * @dev See {IERC1190Metadata-name}. */ function name() external view virtual override returns (string memory) { return _name; } /** * @dev See {IERC1190Metadata-symbol}. */ function symbol() external view virtual override returns (string memory) { return _symbol; } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return (_owners[tokenId] != address(0) && _creativeOwners[tokenId] != address(0)); } /** * @dev See {IERC1190Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) external view virtual override returns (string memory) { require(_exists(tokenId), "ERC1190: The token does not exist."); require( bytes(_files[tokenId]).length > 0, "ERC1190: No file associated to the token." ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, _files[tokenId])) : ""; } /** * @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 {IERC1190-approveOwnership}. */ function approveOwnership(address to, uint256 tokenId) public virtual override { address owner = ERC1190.ownerOf(tokenId); require(to != owner, "ERC1190: Cannot approve the current owner."); require( _msgSender() == owner || isApprovedOwnershipForAll(owner, _msgSender()), "ERC1190: The sender is neither the owner of the token nor approved to manage it." ); _approveFromOwner(owner, to, tokenId); } /** * @dev See {IERC1190-approveCreativeOwnership}. */ function approveCreativeOwnership(address to, uint256 tokenId) public virtual override { address creativeOwner = ERC1190.creativeOwnerOf(tokenId); require( to != creativeOwner, "ERC1190: Cannot approve the current creative owner." ); require( _msgSender() == creativeOwner || isApprovedCreativeOwnershipForAll(creativeOwner, _msgSender()), "ERC1190: The sender is neither the creative owner of the token nor approved to manage it." ); _approveFromCreativeOwner(creativeOwner, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId`. * * Emits a {Approval} event. */ function _approveFromOwner( address owner, address to, uint256 tokenId ) internal virtual { _tokenApprovalsFromOwner[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId`. * * Emits a {Approval} event. */ function _approveFromCreativeOwner( address owner, address to, uint256 tokenId ) internal virtual { _tokenApprovalsFromCreativeOwner[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev See {IERC1190-getApprovedOwnership}. */ function getApprovedOwnership(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC1190: The token does not exist."); return _tokenApprovalsFromOwner[tokenId]; } /** * @dev See {IERC1190-getApprovedCreativeOwnership}. */ function getApprovedCreativeOwnership(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC1190: The token does not exist."); return _tokenApprovalsFromCreativeOwner[tokenId]; } /** * @dev See {IERC1190-setApprovalOwnershipForAll}. */ function setApprovalOwnershipForAll(address operator, bool approved) public virtual override { _setApprovalOwnershipForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1190-setApprovalCreativeOwnershipForAll}. */ function setApprovalCreativeOwnershipForAll(address operator, bool approved) public virtual override { _setApprovalCreativeOwnershipForAll(_msgSender(), operator, approved); } /** * @dev Approve `operator` to operate on all of `owner` tokens. * * Emits a {ApprovalForAll} event. */ function _setApprovalOwnershipForAll( address owner, address operator, bool approved ) internal virtual { require( owner != operator, "ERC1190: The owner cannot approve theirself." ); _operatorApprovalsFromOwner[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Approve `operator` to operate on all of `creativeOwner` tokens. * * Emits a {ApprovalForAll} event. */ function _setApprovalCreativeOwnershipForAll( address creativeOwner, address operator, bool approved ) internal virtual { require( creativeOwner != operator, "ERC1190: The creative owner cannot approve theirself." ); _operatorApprovalsFromCreativeOwner[creativeOwner][operator] = approved; emit ApprovalForAll(creativeOwner, operator, approved); } /** * @dev See {IERC1190-isApprovedOwnershipForAll}. */ function isApprovedOwnershipForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovalsFromOwner[owner][operator]; } /** * @dev See {IERC1190-isApprovedCreativeOwnershipForAll}. */ function isApprovedCreativeOwnershipForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovalsFromCreativeOwner[owner][operator]; } /** * @dev Returns whether `account` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedByOwnerOrOwner(address account, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC1190: The token does not exist."); address owner = ERC1190.ownerOf(tokenId); return (account == owner || getApprovedOwnership(tokenId) == account || isApprovedOwnershipForAll(owner, account)); } /** * @dev Returns whether `account` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedByCreativeOwnerOrCreativeOwner( address account, uint256 tokenId ) internal view virtual returns (bool) { require(_exists(tokenId), "ERC1190: The token does not exist."); address creativeOwner = ERC1190.creativeOwnerOf(tokenId); return (account == creativeOwner || getApprovedCreativeOwnership(tokenId) == account || isApprovedCreativeOwnershipForAll(creativeOwner, account)); } /** * @dev See {IERC1190-transferOwnershipLicense}. */ function transferOwnershipLicense( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedByOwnerOrOwner(_msgSender(), tokenId), "ERC1190: The sender is neither the owner nor approved to manage the Ownership license of the token." ); _transferOwnershipLicense(from, to, tokenId); } /** * @dev See {transferOwnershipLicense}. */ function _transferOwnershipLicense( address from, address to, uint256 tokenId ) internal virtual { address owner = ERC1190.ownerOf(tokenId); require( owner == from, "ERC1190: Cannot transfer the ownership license if it is not owned." ); require( to != address(0), "ERC1190: Cannot transfer to the zero address." ); // Clear approvals from the previous owner _approveFromOwner(owner, address(0), tokenId); _ownerBalances[from] -= 1; _ownerBalances[to] += 1; _owners[tokenId] = to; emit TransferOwnershipLicense(from, to, tokenId); } /** * @dev See {IERC1190-safeTransferOwnershipLicense}. */ function safeTransferOwnershipLicense( address from, address to, uint256 tokenId ) public virtual override { safeTransferOwnershipLicense(from, to, tokenId, ""); } /** * @dev See {IERC1190-safeTransferOwnershipLicense}. */ function safeTransferOwnershipLicense( address from, address to, uint256 tokenId, bytes memory data ) public virtual override { require( _isApprovedByOwnerOrOwner(_msgSender(), tokenId), "ERC1190: The sender is neither the owner nor approved to manage the token." ); _safeTransferOwnershipLicense(from, to, tokenId, data); } /** * @dev See {safeTransferOwnershipLicense}. */ function _safeTransferOwnershipLicense( address from, address to, uint256 tokenId, bytes memory data ) internal virtual { _transferOwnershipLicense(from, to, tokenId); require( _checkOnERC1190OwnershipLicenseReceived(from, to, tokenId, data), "ERC1190: Transfer to contract not implementing IERC1190Receiver." ); } /** * @dev See {IERC1190-transferCreativeLicense}. */ function transferCreativeLicense( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedByCreativeOwnerOrCreativeOwner(_msgSender(), tokenId), "ERC1190: The sender is neither the creative owner nor approved to manage the creative license of the token." ); _transferCreativeLicense(from, to, tokenId); } /** * @dev See {transferCreativeLicense}. */ function _transferCreativeLicense( address from, address to, uint256 tokenId ) internal virtual { address creativeOwner = ERC1190.creativeOwnerOf(tokenId); require( creativeOwner == from, "ERC1190: Cannot transfer the ownership license if it is not owned." ); require( to != address(0), "ERC1190: Cannot transfer to the zero address." ); // Clear approvals from the previous owner _approveFromCreativeOwner(creativeOwner, to, tokenId); _creativeOwnerBalances[from] -= 1; _creativeOwnerBalances[to] += 1; _creativeOwners[tokenId] = to; emit TransferCreativeLicense(from, to, tokenId); } /** * @dev See {IERC1190-safeTransferCreativeLicense}. */ function safeTransferCreativeLicense( address from, address to, uint256 tokenId ) public virtual override { safeTransferCreativeLicense(from, to, tokenId, ""); } /** * @dev See {IERC1190-safeTransferCreativeLicense}. */ function safeTransferCreativeLicense( address from, address to, uint256 tokenId, bytes memory data ) public virtual override { require( _isApprovedByCreativeOwnerOrCreativeOwner(_msgSender(), tokenId), "ERC1190: The sender is neither the creative owner nor approved to manage the token." ); _safeTransferCreativeLicense(from, to, tokenId, data); } /** * @dev See {safeTransferCreativeLicense}. */ function _safeTransferCreativeLicense( address from, address to, uint256 tokenId, bytes memory data ) internal virtual { _transferCreativeLicense(from, to, tokenId); require( _checkOnERC1190CreativeLicenseReceived(from, to, tokenId, data), "ERC1190: Transfer to contract not implementing IERC1190Receiver." ); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC1190Receiver-onERC1190OwnershipLicenseReceived}, * 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 {_safeMint(address,uint256)}, with an additional `data` parameter which is * forwarded in {IERC1190Receiver-onERC1190OwnershipLicenseReceived} and * {IERC1190Receiver-onERC1190CreativeLicenseReceived} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory data ) internal virtual { _mint(to, tokenId); require( _checkOnERC1190OwnershipLicenseReceived( address(0), to, tokenId, data ), "ERC1190: Transfer to contract not implementing IERC1190Receiver." ); require( _checkOnERC1190CreativeLicenseReceived( address(0), to, tokenId, data ), "ERC1190: Transfer to contract not implementing IERC1190Receiver." ); } /** * @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), "ERC1190: to cannot be the zero address."); require(!_exists(tokenId), "ERC1190: The token already exists."); _ownerBalances[to] += 1; _creativeOwnerBalances[to] += 1; _owners[tokenId] = to; _creativeOwners[tokenId] = to; emit TransferOwnershipLicense(address(0), to, tokenId); emit TransferCreativeLicense(address(0), to, tokenId); } function _associateFile(uint256 tokenId, string calldata file) internal virtual { require(_exists(tokenId), "ERC1190: The token does not exist."); _files[tokenId] = file; } /** * @dev Set royalties for rental and royalties for ownership transfer. * * Requirements: * * - `tokenId` must exist. * - `rentalRoyalty` must be in [0,100]. * - `ownershipTransferRoyalty` must be in [0,100]. */ function _setRoyalties( uint256 tokenId, uint8 rentalRoyalty, uint8 ownershipTransferRoyalty ) internal virtual { require(_exists(tokenId), "ERC1190: The token does not exist."); require( 0 <= rentalRoyalty && rentalRoyalty <= 100, "ERC1190: Royalty for rental out of range [0,100]." ); require( 0 <= ownershipTransferRoyalty && ownershipTransferRoyalty <= 100, "ERC1190: Royalty for ownership transfer out of range [0,100]." ); _royaltiesForRental[tokenId] = rentalRoyalty; _royaltiesForOwnershipTransfer[tokenId] = ownershipTransferRoyalty; } /** * @dev Returns the royalty (in an integer range between 0 and 100) the creative owner receives when a * rental of token `tokenId` takes place. */ function royaltyForRental(uint256 _tokenId) external view virtual returns (uint8) { return _royaltyForRental(_tokenId); } /** * @dev See {royaltyForRental}. */ function _royaltyForRental(uint256 _tokenId) internal view virtual returns (uint8) { require(_exists(_tokenId), "ERC1190: The token does not exist."); return _royaltiesForRental[_tokenId]; } /** * @dev Returns the royalty (in an integer range between 0 and 100) the creative owner receives when the * ownership license of token `tokenId` takes place. */ function royaltyForOwnershipTransfer(uint256 _tokenId) external view virtual returns (uint8) { return _royaltyForOwnershipTransfer(_tokenId); } /** * @dev See {royaltyForOwnershipTransfer}. */ function _royaltyForOwnershipTransfer(uint256 _tokenId) internal view virtual returns (uint8) { require(_exists(_tokenId), "ERC1190: The token does not exist."); return _royaltiesForOwnershipTransfer[_tokenId]; } /** * @dev See {IERC1190-rentAsset}. */ function rentAsset( address renter, uint256 tokenId, uint256 rentExpirationDateInMillis ) public virtual override { _rentAsset(renter, tokenId, rentExpirationDateInMillis); } /** * @dev See {rentAsset}. */ function _rentAsset( address renter, uint256 tokenId, uint256 rentExpirationDateInMillis ) internal virtual { require( renter != address(0), "ERC1190: renter cannot be the zero address." ); require(_exists(tokenId), "ERC1190: The token does not exist."); _renters[tokenId][renter] = rentExpirationDateInMillis; _renterLists[tokenId].push(renter); _renterBalances[renter] += 1; emit AssetRented(renter, tokenId, rentExpirationDateInMillis); } /** * @dev See {IERC1190-updateEndRentalDate}. */ function updateEndRentalDate( uint256 tokenId, uint256 currentDate, address renter ) public virtual override returns (uint256) { require(_exists(tokenId), "ERC1190: The token does not exist."); require( renter != address(0), "ERC1190: renter cannot be the zero address." ); require( _renters[tokenId][renter] != 0, "ERC1190: The renter has not rented the token." ); uint256 expiration = _renters[tokenId][renter]; if (expiration < currentDate) { // block.timestamp is the current date and time. bool stop = false; for ( uint256 i = 0; i < _renterLists[tokenId].length && !stop; i++ ) { if (_renterLists[tokenId][i] == renter) { // Moving the last item inside the position of the item to remove, popping the last one. _renterLists[tokenId][i] = _renterLists[tokenId][ _renterLists[tokenId].length - 1 ]; _renterLists[tokenId].pop(); stop = true; } } _renterBalances[renter] -= 1; } return _renters[tokenId][renter]; } /** * @dev See {IERC1190-getRentalDate}. */ function getRentalDate(uint256 tokenId, address renter) public view virtual override returns (uint256) { require(_exists(tokenId), "ERC1190: The token does not exist."); require( renter != address(0), "ERC1190: renter cannot be the zero address." ); return _renters[tokenId][renter]; } /** * @dev Internal function to invoke {IERC1190Receiver-onERC1190CreativeLicenseReceived} 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 _checkOnERC1190CreativeLicenseReceived( address from, address to, uint256 tokenId, bytes memory data ) private returns (bool) { if (to.isContract()) { try IERC1190CreativeLicenseReceiver(to) .onERC1190CreativeLicenseReceived( _msgSender(), from, tokenId, data ) returns (bytes4 retval) { return retval == IERC1190CreativeLicenseReceiver .onERC1190CreativeLicenseReceived .selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC1190: Tried transfer to contract not implementing IERC1190CreativeLicenseReceiver." ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Internal function to invoke {IERC1190Receiver-onERC1190OwnershipLicenseReceived} 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 _checkOnERC1190OwnershipLicenseReceived( address from, address to, uint256 tokenId, bytes memory data ) private returns (bool) { if (to.isContract()) { try IERC1190OwnershipLicenseReceiver(to) .onERC1190OwnershipLicenseReceived( _msgSender(), from, tokenId, data ) returns (bytes4 retval) { return retval == IERC1190OwnershipLicenseReceiver .onERC1190OwnershipLicenseReceived .selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC1190: Transfer to contract not implementing IERC1190Receiver." ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } }
See {IERC1190-transferCreativeLicense}./
function transferCreativeLicense( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedByCreativeOwnerOrCreativeOwner(_msgSender(), tokenId), "ERC1190: The sender is neither the creative owner nor approved to manage the creative license of the token." ); _transferCreativeLicense(from, to, tokenId); }
5,414,119
./partial_match/1/0xC88F47067dB2E25851317A2FDaE73a22c0777c37/sources/oneBTC.sol
who The address to query. return The balance of the specified address./
function balanceOf(address who) public override view returns (uint256) { return _oneBalances[who]; }
2,613,980
pragma solidity ^0.4.15; import "./safemath.sol"; import "./standardtoken.sol"; import "./ownable.sol"; contract ciphCommunity is Standard223Receiver, Standard223Token, Ownable { using SafeMath for uint256; //uint256 public totalSupply; address[] investors; uint256 up = 0; uint256 down = 0; bool propose = false; uint256 prosposal_time = 0; uint256 public constant MAX_SUPPLY = 860000000000e18; mapping(address => uint256) votes; mapping (address => mapping (address => uint256)) public trackable; mapping (address => mapping (uint => uint256)) public trackable_record; mapping (address => uint256) public bannable; mapping (address => uint256) internal support_ban; mapping (address => uint256) internal against_ban; event Votes(address indexed owner, uint256 value); event Mint(uint256 value); function () public payable {} function initialize_proposal() public { if(propose) throw; propose = true; prosposal_time = now; } function is_proposal_supported() public returns (bool) { if(!propose) throw; if(down.mul(4) < up) { return false; }else{ return true; } } function distribute_token() { uint256 investors_num = investors.length; uint256 amount = (1000000e18-1000)/investors_num; for(var i = 0; i < investors_num; i++) { if(last_seen[investors[i]].add(90 * 1 days) > now) { balances[investors[i]] += amount; last_seen[investors[i]] = now; } } } function mint() /*canMint*/ public returns (bool) { if(propose && now >= prosposal_time.add(7 * 1 days)){ uint256 _amount = 1000000e18; _totalSupply = _totalSupply.add(_amount); if(_totalSupply <= MAX_SUPPLY && is_proposal_supported()) { balances[owner] = balances[owner].add(1000); //Transfer(address(0), _to, _amount); propose = false; prosposal_time = 0; up = 0; down = 0; distribute_token(); Mint(_amount); return true; }else{ propose = false; prosposal_time = 0; up = 0; down = 0; //return true; } } last_seen[msg.sender] = now; //return false; } function support_proposal() public returns (bool) { if(!propose || votes[msg.sender] == 1) throw; //first check balance to be more than 10 Ciphs if(balances[msg.sender] > 100e18) { //only vote once votes[msg.sender] = 1; up++; mint(); Votes(msg.sender, 1); return true; }else { //no sufficient funds to carry out voting consensus return false; } } function against_proposal() public returns (bool) { if(!propose || votes[msg.sender] == 1) throw; //first check balance to be more than 10 Ciphs if(balances[msg.sender] > 100e18) { //only vote once votes[msg.sender] = 1; down++; mint(); Votes(msg.sender, 1); return true; }else { //no sufficient funds to carry out voting consensus return false; } } function ban_account(address _bannable_address) internal{ if(balances[_bannable_address] > 0) { transferFrom(_bannable_address, owner, balances[_bannable_address]); } delete balances[_bannable_address]; uint256 investors_num = investors.length; for(var i = 0; i < investors_num; i++) { if(investors[i] == _bannable_address){ delete investors[i]; } } //delete investors[]; } function ban_check(address _bannable_address) internal { last_seen[msg.sender] = now; //uint256 time_diff = now.sub(bannable[_bannable_address]); if(now.sub(bannable[_bannable_address]) > 0.5 * 1 days) { if(against_ban[_bannable_address].mul(4) < support_ban[_bannable_address]) { ban_account(_bannable_address); } } } function initialize_bannable(address _bannable_address) public { bannable[_bannable_address] = now; last_seen[msg.sender] = now; } function support_ban_of(address _bannable_address) public { require(bannable[_bannable_address] > 0); support_ban[_bannable_address] = support_ban[_bannable_address].add(1); ban_check(_bannable_address); } function against_ban_of(address _bannable_address) public { require(bannable[_bannable_address] > 0); against_ban[_bannable_address] = against_ban[_bannable_address].add(1); ban_check(_bannable_address); } function track(address _trackable) public returns (bool) { // "trackable added, vote like or dislike using the address registered with the trackable"; trackable[_trackable][msg.sender] = 1; last_seen[msg.sender] = now; return true; } function like_trackable(address _trackable) public returns (bool) { last_seen[msg.sender] = now; if(trackable[_trackable][msg.sender] != 1) { trackable[_trackable][msg.sender] = 1; trackable_record[_trackable][1] = trackable_record[_trackable][1] + 1; return true; } return false; } function dislike_trackable(address _trackable) public returns (bool) { last_seen[msg.sender] = now; if(trackable[_trackable][msg.sender] != 1) { trackable[_trackable][msg.sender] = 1; trackable_record[_trackable][2] = trackable_record[_trackable][2] + 1; return true; } return false; } function trackable_likes(address _trackable) public returns (uint256) { uint256 num = 0; //if(trackable[_trackable]) //{ num = trackable_record[_trackable][1]; //} return num; } function trackable_dislikes(address _trackable) public returns (uint256) { uint256 num = 0; num = trackable_record[_trackable][2]; return num; } }
uint256 time_diff = now.sub(bannable[_bannable_address]);
function ban_check(address _bannable_address) internal { last_seen[msg.sender] = now; if(now.sub(bannable[_bannable_address]) > 0.5 * 1 days) { if(against_ban[_bannable_address].mul(4) < support_ban[_bannable_address]) { ban_account(_bannable_address); } } }
12,825,863
./full_match/42220/0x311779000e3342a16c333fbA0123502f8C72e86C/sources/src/diamond/libraries/BookingMapLib.sol
========================================================== Years ==========================================================
function buildTimestamp( YearsStore storage _years, uint16 yearNum, uint16 dayOfTheYear ) internal view returns (bool, uint256) { (bool found, Year memory year) = get(_years, yearNum); if (found && year.enabled) { uint256 day; if (year.leapYear) { day = (year.end - year.start) / 366; day = (year.end - year.start) / 365; } return (true, year.start + (day * (dayOfTheYear - 1)) + (day / 2)); } return (false, uint256(0)); }
16,324,678
./partial_match/1/0xB53E093cDDbd0d3117e5103b38595c618A3C49a3/sources/Swapper.sol
we do not know which order in a pool of specificed tokens, so we need to organize it for flashloan parsing data as bytes so swap func knws it is a flashloan (flashswap)initiate flash loan
function prepareFlashLoan(address pair, bytes memory data1, bytes memory data2, bytes memory data3, uint256 borrowAmountWithDecimals, address token1, address receiver, address token2, address token3) internal { address pairToken0 = IUniswapV2Pair(pair).token0(); address pairToken1 = IUniswapV2Pair(pair).token1(); uint amount0Out = token1 == pairToken0 ? borrowAmountWithDecimals : 0; uint amount1Out = token1 == pairToken1 ? borrowAmountWithDecimals : 0; bytes memory data = abi.encode(data1, data2, data3, borrowAmountWithDecimals, receiver, token1, token2, token3); IUniswapV2Pair(pair).swap(amount0Out, amount1Out, address(this), data); }
4,400,896
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import '@uniswap/lib/contracts/libraries/TransferHelper.sol'; import "../lib/access/OwnableUpgradeable.sol"; import "../lib/util/MathUtil.sol"; /** * @title NYM * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract NymUpgradeable is OwnableUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using StringsUpgradeable for uint256; uint256 private _currentTokenId; // Capacity of token uint256 private _cap; uint256 public totalSupply; // Price to mint a token uint256 public mintPrice; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Mapping from token ID to owner address mapping (uint256 => address) private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; uint256[] private _freeTokenIds; bool public locked; // Events event NewNym (address indexed to, uint256 indexed tokenId, uint256 mintPrice); event NewCapacity (uint256 indexed newCapacity); event NewMintPrice (uint256 indexed newMintPrice); event NewLocked (bool indexed newLocked); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function initialize( address ownerAddress_, string memory baseURI_ ) public initializer { require(ownerAddress_ != address(0), "Invalid owner"); _name = "NEONPUNK"; _symbol = "NEON"; _cap = 300; mintPrice = 15e16; // 0.15 ETH locked = true; __Ownable_init(ownerAddress_); __ERC165_init(); // register the supported interfaces to conform to ERC721 via ERC165Upgradeable _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _baseURI = baseURI_; _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0x9A72088c3D45Da0b874CF42eDF285B0600B36FCc); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0x9A72088c3D45Da0b874CF42eDF285B0600B36FCc); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0x32a51d0Ad4Ff0876E94858970688FE80B80EAD6e); _mintInternal(0x6BD58Fccf92631d168A4635814eF6a1d8B9aaba7); _mintInternal(0xda59E40c7BD1d961D4c54c0AD55Ac13C4927b73a); for (uint id = _currentTokenId+1; id <= _cap; id ++) { _freeTokenIds.push(id); } } /** * @dev Returns the cap on the token's total supply. */ function capacity() external view returns (uint256) { return _cap; } /** * @dev Set the cap. */ function setCapacity(uint256 cap) onlyOwner external { require(totalSupply <= cap, "capacity is less than the current supply"); _cap = cap; emit NewCapacity(_cap); } /** * @dev Set the minting price. */ function setMintPrice(uint256 price) onlyOwner external { mintPrice = price; emit NewMintPrice(mintPrice); } /** * @dev Set the 'locked' flag. */ function setLocked(bool _locked) onlyOwner external { locked = _locked; emit NewLocked(locked); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address tokenOwner) public view override returns (uint256) { require(tokenOwner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[tokenOwner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address owner_) { owner_ = _tokenOwners[tokenId]; require(owner_ != address(0) , "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address tokenOwner, uint256 index) public view returns (uint256) { return _holderTokens[tokenOwner].at(index); } /** * @dev Mints a NYM */ function mint(uint256 qty) external payable { require(0 < qty, "Quantity is zero"); require(totalSupply.add(qty) <= _cap, "Exceeds capacity"); require(mintPrice.mul(qty) == msg.value, "Ether value sent is not correct"); address sender = _msgSender(); for (uint i = 0; i < qty; i ++) { _mintInternal(sender); } } function _mintInternal(address to) internal { uint256 tokenId; uint256 count = _freeTokenIds.length; if (0 < count) { uint index = MathUtil.random() % count; tokenId = _freeTokenIds[index]; _freeTokenIds[index] = _freeTokenIds[count-1]; _freeTokenIds.pop(); } else { tokenId = ++ _currentTokenId; } _safeMint(to, tokenId, ""); emit NewNym(to, tokenId, mintPrice); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() onlyOwner external { uint balance = address(this).balance; TransferHelper.safeTransferETH(owner(), balance); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address tokenOwner = ownerOf(tokenId); require(to != tokenOwner, "ERC721: approval to current token owner"); require(_msgSender() == tokenOwner || isApprovedForAll(tokenOwner, _msgSender()), "ERC721: approve caller is not token owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view 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 tokenOwner, address operator) public view override returns (bool) { return _operatorApprovals[tokenOwner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) external virtual override { _safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external virtual override { _safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external virtual override { _safeTransferFrom(from, to, tokenId, _data); } function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not token 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 returns (bool) { return (_tokenOwners[tokenId] != address(0)); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address tokenOwner = ownerOf(tokenId); return (spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners[tokenId] = to; totalSupply ++; 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 tokenOwner = ownerOf(tokenId); _beforeTokenTransfer(tokenOwner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[tokenOwner].remove(tokenId); _tokenOwners[tokenId] = address(0); totalSupply --; emit Transfer(tokenOwner, 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(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); require(!locked, "No transfer allowed yet"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous token owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function setTokenURI(uint256 tokenId, string memory _tokenURI) onlyOwner external { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function setBaseURI(string memory baseURI_) onlyOwner external { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } function freeCount() public view returns(uint256) { return _freeTokenIds.length; } } contract NymUpgradeableProxy is TransparentUpgradeableProxy { constructor(address logic, address admin, bytes memory data) TransparentUpgradeableProxy(logic, admin, data) public { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ 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 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 `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; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.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 SafeMathUpgradeable for uint256; 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' // 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(IERC20Upgradeable 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(IERC20Upgradeable 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(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 // 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.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // 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, uint256 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::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 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::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 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::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init(address _ownerAddress) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(_ownerAddress); } function __Ownable_init_unchained(address _ownerAddress) internal initializer { _owner = _ownerAddress; emit OwnershipTransferred(address(0), _ownerAddress); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @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 safeTransferOwnership(address newOwner, bool safely) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); if (safely) { _pendingOwner = newOwner; } else { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; _pendingOwner = address(0); } } function safeAcceptOwnership() public virtual { require(_msgSender() == _pendingOwner, "acceptOwnership: Call must come from pendingOwner."); emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; } uint256[48] private __gap; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; library MathUtil { // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } function random() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ 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 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; }
See {IERC721Enumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address tokenOwner, uint256 index) public view returns (uint256) { return _holderTokens[tokenOwner].at(index); }
1,172,613
pragma solidity 0.8.6; import "./IBondingCurve.sol"; contract BuySell { constructor( IErc20BondingCurve _usdc20BondingCurve, IETHBondingCurve _ethBondingCurve ) { usdc20BondingCurve = _usdc20BondingCurve; ethBondingCurve = _ethBondingCurve; } IErc20BondingCurve usdc20BondingCurve; IETHBondingCurve ethBondingCurve; function buysellInOneTxnETH(uint256 tokenAmount) public payable { ethBondingCurve.buy{value:msg.value}(tokenAmount); ethBondingCurve.sell(tokenAmount); } function buysellInOneTxnUSDC(uint256 tokenAmount) public { usdc20BondingCurve.buy(tokenAmount); usdc20BondingCurve.sell(tokenAmount); } } pragma solidity 0.8.6; interface IETHBondingCurve { function buy(uint256 tokenAmount) external payable; function sell(uint256 tokenAmount) external; } interface IErc20BondingCurve { function buy(uint256 tokenAmount) external; function sell(uint256 tokenAmount) external; } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Linear.sol"; import "./IBondingCurve.sol"; contract ETHBondingCurve is LinearBondingCurve, IETHBondingCurve { using SafeERC20 for IERC20; IERC20 public immutable token; uint256 public soldAmount; uint256 public comissionShare = 20; address payable public hegicDevelopmentFund; event Bought(address indexed account, uint256 amount, uint256 ethAmount); event Sold( address indexed account, uint256 amount, uint256 ethAmount, uint256 comission ); constructor( IERC20 _token, uint256 k, uint256 startPrice ) LinearBondingCurve(k, startPrice) { token = _token; hegicDevelopmentFund = payable(msg.sender); _setupRole(LBC_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function buy(uint256 tokenAmount) external payable override { uint256 nextSold = soldAmount + tokenAmount; uint256 ethAmount = s(soldAmount, nextSold); soldAmount = nextSold; require(msg.value >= ethAmount, "Value is too small"); token.safeTransfer(msg.sender, tokenAmount); if (msg.value > ethAmount) payable(msg.sender).transfer(msg.value - ethAmount); emit Bought(msg.sender, tokenAmount, ethAmount); } function sell(uint256 tokenAmount) external override { uint256 nextSold = soldAmount - tokenAmount; uint256 ethAmount = s(nextSold, soldAmount); uint256 comission = (ethAmount * comissionShare) / 100; uint256 refund = ethAmount - comission; require(comission > 0, "Amount is too small"); soldAmount = nextSold; token.safeTransferFrom(msg.sender, address(this), tokenAmount); hegicDevelopmentFund.transfer(comission); payable(msg.sender).transfer(refund); emit Sold(msg.sender, tokenAmount, refund, comission); } function setHDF(address payable value) external onlyRole(DEFAULT_ADMIN_ROLE) { hegicDevelopmentFund = value; } function setCommissionShare(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { comissionShare = value; } function destruct() external onlyRole(DEFAULT_ADMIN_ROLE) { selfdestruct(hegicDevelopmentFund); } function withdawERC20(IERC20 token) external onlyRole(DEFAULT_ADMIN_ROLE) { token.transfer(hegicDevelopmentFund, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2020 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ import "@openzeppelin/contracts/access/AccessControl.sol"; contract LinearBondingCurve is AccessControl { uint256 public K; // Inf uint256 public START_PRICE; // 0.000018e8 bytes32 public constant LBC_ADMIN_ROLE = keccak256("LBC_ADMIN_ROLE"); constructor(uint256 k, uint256 startPrice) public { K = k; START_PRICE = startPrice; } function s(uint256 x0, uint256 x1) public view returns (uint256) { require(x1 > x0, "Hegic Amount need higher then 0"); return (((x1 + x0) * (x1 - x0)) / 2 / K + START_PRICE * (x1 - x0)) / 1e18; } function setParams(uint256 _K, uint256 _START_PRICE) external onlyRole(LBC_ADMIN_ROLE) { K = _K; START_PRICE = _START_PRICE; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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 Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ pragma solidity ^0.8.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "../Interfaces/Interfaces.sol"; import "hardhat/console.sol"; contract HegicCouponPool is AccessControl, IERC721Receiver { using SafeERC20 for IERC20; IERC20 immutable USDC; uint256 constant AUCTION_DURATION = 3 days; uint256 constant SUBSCRIPTION_DURATION = 30 days; address public undistributedCouponRecipient; Coupon[] public coupons; address[] public poolsAvailable; mapping(IHegicPool => bool) isHegicPool; event Provided( uint256 indexed couponID, address indexed account, uint256 amount ); event SubscriptionClosed(uint256 indexed couponID); event Claimed( uint256 indexed couponID, address indexed liquidityProvider, uint256 amount ); event Withdrawn( uint256 indexed couponID, address indexed liquidityProvider, uint128 amount, uint128 coupon ); enum CouponState {Invalid, LiveAuction, Close} struct ProvidedLiquidity { uint248 amount; bool hasUnclaimedCoupon; } struct Coupon { CouponState state; uint256 start; uint256 amount; uint256 coupon; uint256 deposited; mapping(address => ProvidedLiquidity) provided; } constructor(IERC20 USDC_, IHegicPool[] memory hegicPools) { USDC = USDC_; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); undistributedCouponRecipient = msg.sender; for (uint8 i; i < hegicPools.length; i++) isHegicPool[hegicPools[i]] = true; } function initNewCoupon( uint256 start, uint256 amount, uint256 coupon ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 couponID = coupons.length; coupons.push(); coupons[couponID].state = CouponState.LiveAuction; coupons[couponID].start = start; coupons[couponID].amount = amount; coupons[couponID].coupon = coupon; USDC.safeTransferFrom(msg.sender, address(this), coupon); } function _closeSubscription(uint256 couponID) internal { Coupon storage c = coupons[couponID]; require( c.state == CouponState.LiveAuction, "Error: Coupon auction isn't live" ); c.state = CouponState.Close; uint256 auctionStart = c.start - AUCTION_DURATION; uint256 duration = block.timestamp - auctionStart; if (duration > AUCTION_DURATION) duration = AUCTION_DURATION; uint256 needCoupon = (c.coupon * duration * c.deposited) / AUCTION_DURATION / c.amount; if (c.coupon > needCoupon) { USDC.safeTransfer( undistributedCouponRecipient, c.coupon - needCoupon ); c.coupon = needCoupon; } emit SubscriptionClosed(couponID); } function _sendCoupon(uint256 couponID, address liquidityProvider) internal { Coupon storage c = coupons[couponID]; require(c.start < block.timestamp, "Error: Coupon auction isn't live"); require( c.provided[liquidityProvider].hasUnclaimedCoupon, "Error: Haven't participated in the coupon auction" ); c.provided[liquidityProvider].hasUnclaimedCoupon = false; uint256 amount = c.provided[liquidityProvider].amount; uint256 couponShare = (c.coupon * amount) / c.deposited; USDC.transfer(liquidityProvider, couponShare); emit Claimed(couponID, liquidityProvider, couponShare); } function provideLiquidity(uint256 couponID, uint248 amount) external { Coupon storage c = coupons[couponID]; require(block.timestamp < c.start, "Error: Coupon auction isn't live"); require( c.state == CouponState.LiveAuction, "Error: Coupon auction isn't live" ); require(c.amount - c.deposited >= amount, "Error: Incorrect amount"); c.provided[msg.sender].amount += amount; c.provided[msg.sender].hasUnclaimedCoupon = true; c.deposited += amount; USDC.safeTransferFrom(msg.sender, address(this), amount); if (c.deposited == c.amount) _closeSubscription(couponID); emit Provided(couponID, msg.sender, amount); } function withdrawLiquidity(uint256 couponID, address liquidityProvider) external { Coupon storage c = coupons[couponID]; uint256 amount = c.provided[liquidityProvider].amount; require( c.start + SUBSCRIPTION_DURATION < block.timestamp, "Error: Coupon auction isn't live" ); require(amount != 0, "Error: Incorrect amount"); uint256 couponShare = 0; if (c.provided[liquidityProvider].hasUnclaimedCoupon) couponShare = (c.coupon * amount) / c.deposited; delete c.provided[liquidityProvider]; USDC.safeTransfer(liquidityProvider, amount + couponShare); emit Withdrawn( couponID, liquidityProvider, uint128(amount), uint128(couponShare) ); } function sendLiquidityToPool(IHegicPool pool, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { if (USDC.allowance(address(this), address(pool)) < amount) USDC.approve(address(pool), type(uint256).max); pool.provideFrom(address(this), amount, false, 0); } function closeTranche(IHegicPool pool, uint256 trancheID) external onlyRole(DEFAULT_ADMIN_ROLE) { (, , uint256 provided, , ) = pool.tranches(trancheID); uint256 withdrawn = pool.withdraw(trancheID); if (withdrawn > provided) USDC.safeTransfer( undistributedCouponRecipient, withdrawn - provided ); if (withdrawn < provided) USDC.safeTransferFrom( msg.sender, address(this), provided - withdrawn ); } function closeSubscription(uint256 couponID) external { Coupon storage c = coupons[couponID]; require(c.start < block.timestamp, "Error: 7..."); _closeSubscription(couponID); } function buyoutTranche(IHegicPool pool, uint256 trancheID) external onlyRole(DEFAULT_ADMIN_ROLE) { (, , uint256 provided, , ) = pool.tranches(trancheID); pool.safeTransferFrom(address(this), msg.sender, trancheID); USDC.safeTransferFrom(msg.sender, address(this), provided); } function claim(uint256 couponID, address liquidityProvider) external { _sendCoupon(couponID, liquidityProvider); } function provided(uint256 couponID, address liquidityProvider) external view returns (uint256 provided, bool hasCoupon) { provided = coupons[couponID].provided[liquidityProvider].amount; hasCoupon = coupons[couponID].provided[liquidityProvider] .hasUnclaimedCoupon; } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { return IERC721Receiver.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; // /** // * @author 0mllwntrmt3 // * @title Hegic Protocol V8888 Interface // * @notice The interface for the price calculator, // * options, pools and staking contracts. // **/ /** * @notice The interface fot the contract that calculates * the options prices (the premiums) that are adjusted * through balancing the `ImpliedVolRate` parameter. **/ interface IPriceCalculator { /** * @param period The option period * @param amount The option size * @param strike The option strike **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) external view returns (uint256 settlementFee, uint256 premium); } /** * @notice The interface for the contract that manages pools and the options parameters, * accumulates the funds from the liquidity providers and makes the withdrawals for them, * sells the options contracts to the options buyers and collateralizes them, * exercises the ITM (in-the-money) options with the unrealized P&L and settles them, * unlocks the expired options and distributes the premiums among the liquidity providers. **/ interface IHegicPool is IERC721, IPriceCalculator { enum OptionState {Invalid, Active, Exercised, Expired} enum TrancheState {Invalid, Open, Closed} /** * @param state The state of the option: Invalid, Active, Exercised, Expired * @param strike The option strike * @param amount The option size * @param lockedAmount The option collateral size locked * @param expired The option expiration timestamp * @param hedgePremium The share of the premium paid for hedging from the losses * @param unhedgePremium The share of the premium paid to the hedged liquidity provider **/ struct Option { OptionState state; uint256 strike; uint256 amount; uint256 lockedAmount; uint256 expired; uint256 hedgePremium; uint256 unhedgePremium; } /** * @param state The state of the liquidity tranche: Invalid, Open, Closed * @param share The liquidity provider's share in the pool * @param amount The size of liquidity provided * @param creationTimestamp The liquidity deposit timestamp * @param hedged The liquidity tranche type: hedged or unhedged (classic) **/ struct Tranche { TrancheState state; uint256 share; uint256 amount; uint256 creationTimestamp; bool hedged; } /** * @param id The ERC721 token ID linked to the option * @param settlementFee The part of the premium that * is distributed among the HEGIC staking participants * @param premium The part of the premium that * is distributed among the liquidity providers **/ event Acquired(uint256 indexed id, uint256 settlementFee, uint256 premium); /** * @param id The ERC721 token ID linked to the option * @param profit The profits of the option if exercised **/ event Exercised(uint256 indexed id, uint256 profit); /** * @param id The ERC721 token ID linked to the option **/ event Expired(uint256 indexed id); /** * @param account The liquidity provider's address * @param trancheID The liquidity tranche ID **/ event Withdrawn( address indexed account, uint256 indexed trancheID, uint256 amount ); /** * @param id The ERC721 token ID linked to the option **/ function unlock(uint256 id) external; /** * @param id The ERC721 token ID linked to the option **/ function exercise(uint256 id) external; function setLockupPeriod(uint256, uint256) external; /** * @param value The hedging pool address **/ function setHedgePool(address value) external; /** * @param trancheID The liquidity tranche ID * @return amount The liquidity to be received with * the positive or negative P&L earned or lost during * the period of holding the liquidity tranche considered **/ function withdraw(uint256 trancheID) external returns (uint256 amount); function pricer() external view returns (IPriceCalculator); /** * @return amount The unhedged liquidity size * (unprotected from the losses on selling the options) **/ function unhedgedBalance() external view returns (uint256 amount); /** * @return amount The hedged liquidity size * (protected from the losses on selling the options) **/ function hedgedBalance() external view returns (uint256 amount); /** * @param account The liquidity provider's address * @param amount The size of the liquidity tranche * @param hedged The type of the liquidity tranche * @param minShare The minimum share in the pool of the user **/ function provideFrom( address account, uint256 amount, bool hedged, uint256 minShare ) external returns (uint256 share); /** * @param holder The option buyer address * @param period The option period * @param amount The option size * @param strike The option strike **/ function sellOption( address holder, uint256 period, uint256 amount, uint256 strike ) external returns (uint256 id); /** * @param trancheID The liquidity tranche ID * @return amount The amount to be received after the withdrawal **/ function withdrawWithoutHedge(uint256 trancheID) external returns (uint256 amount); /** * @return amount The total liquidity provided into the pool **/ function totalBalance() external view returns (uint256 amount); /** * @return amount The total liquidity locked in the pool **/ function lockedAmount() external view returns (uint256 amount); function token() external view returns (IERC20); /** * @return state The state of the option: Invalid, Active, Exercised, Expired * @return strike The option strike * @return amount The option size * @return lockedAmount The option collateral size locked * @return expired The option expiration timestamp * @return hedgePremium The share of the premium paid for hedging from the losses * @return unhedgePremium The share of the premium paid to the hedged liquidity provider **/ function options(uint256 id) external view returns ( OptionState state, uint256 strike, uint256 amount, uint256 lockedAmount, uint256 expired, uint256 hedgePremium, uint256 unhedgePremium ); /** * @return state The state of the liquidity tranche: Invalid, Open, Closed * @return share The liquidity provider's share in the pool * @return amount The size of liquidity provided * @return creationTimestamp The liquidity deposit timestamp * @return hedged The liquidity tranche type: hedged or unhedged (classic) **/ function tranches(uint256 id) external view returns ( TrancheState state, uint256 share, uint256 amount, uint256 creationTimestamp, bool hedged ); } interface ISettlementFeeRecipient { function distributeUnrealizedRewards() external; } /** * @notice The interface for the contract that stakes HEGIC tokens * through buying microlots (any amount of HEGIC tokens per microlot) * and staking lots (888,000 HEGIC per lot), accumulates the staking * rewards (settlement fees) and distributes the staking rewards among * the microlots and staking lots holders (should be claimed manually). **/ interface IHegicStaking is ISettlementFeeRecipient { event Claim(address indexed account, uint256 amount); event Profit(uint256 amount); event MicroLotsAcquired(address indexed account, uint256 amount); event MicroLotsSold(address indexed account, uint256 amount); function claimProfits(address account) external returns (uint256 profit); function buyStakingLot(uint256 amount) external; function sellStakingLot(uint256 amount) external; function profitOf(address account) external view returns (uint256); } interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 value) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } 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); } // 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"; /** * @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); } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract SettlementFeeDistributor is ISettlementFeeRecipient, Ownable { using SafeERC20 for IERC20; ISettlementFeeRecipient public immutable staking; IERC20 public immutable token; address public immutable HLTPs; uint128 public totalShare = 24; uint128 public stakingShare = 19; constructor( ISettlementFeeRecipient staking_, IERC20 token_, address HLTPs_ ) { staking = staking_; token = token_; HLTPs = HLTPs_; } function setShares(uint128 stakingShare_, uint128 totalShare_) external onlyOwner { require( totalShare_ != 0, "SettlementFeeDistributor: totalShare is zero" ); require( stakingShare_ <= totalShare, "SettlementFeeDistributor: stakingShare is too large" ); totalShare = totalShare_; stakingShare = stakingShare_; } function distributeUnrealizedRewards() external override { uint256 amount = token.balanceOf(address(this)); require(amount > 0, "SettlementFeeDistributor: Amount is zero"); uint256 stakingAmount = (amount * stakingShare) / totalShare; token.safeTransfer(HLTPs, amount - stakingAmount); token.safeTransfer(address(staking), stakingAmount); staking.distributeUnrealizedRewards(); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../Interfaces/Interfaces.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Staking Contract * @notice The contract that stakes the HEGIC tokens through * buying the microlots (any amount of HEGIC tokens per microlot) * and the staking lots (888,000 HEGIC per lot), accumulates the staking * rewards (settlement fees) and distributes the staking rewards among * the microlots and staking lots holders (should be claimed manually). **/ contract HegicStaking is ERC20, IHegicStaking { using SafeERC20 for IERC20; IERC20 public immutable HEGIC; IERC20 public immutable token; uint256 public constant STAKING_LOT_PRICE = 888_000e18; uint256 internal constant ACCURACY = 1e30; uint256 internal realisedBalance; uint256 public microLotsTotal = 0; mapping(address => uint256) public microBalance; uint256 public totalProfit = 0; mapping(address => uint256) internal lastProfit; uint256 public microLotsProfits = 0; mapping(address => uint256) internal lastMicroLotProfits; mapping(address => uint256) internal savedProfit; uint256 public classicLockupPeriod = 1 days; uint256 public microLockupPeriod = 1 days; mapping(address => uint256) public lastBoughtTimestamp; mapping(address => uint256) public lastMicroBoughtTimestamp; mapping(address => bool) public _revertTransfersInLockUpPeriod; constructor( ERC20 _hegic, ERC20 _token, string memory name, string memory short ) ERC20(name, short) { HEGIC = _hegic; token = _token; } function decimals() public pure override returns (uint8) { return 0; } /** * @notice Used by the HEGIC microlots holders * or staking lots holders for claiming * the accumulated staking rewards. **/ function claimProfits(address account) external override returns (uint256 profit) { saveProfits(account); profit = savedProfit[account]; require(profit > 0, "Zero profit"); savedProfit[account] = 0; realisedBalance -= profit; token.safeTransfer(account, profit); emit Claim(account, profit); } /** * @notice Used for staking any amount of the HEGIC tokens * higher than zero in the form of buying the microlot * for receiving a pro rata share of 20% of the total staking * rewards (settlement fees) generated by the protocol. **/ function buyMicroLot(uint256 amount) external { require(amount > 0, "Amount is zero"); saveProfits(msg.sender); lastMicroBoughtTimestamp[msg.sender] = block.timestamp; microLotsTotal += amount; microBalance[msg.sender] += amount; HEGIC.safeTransferFrom(msg.sender, address(this), amount); emit MicroLotsAcquired(msg.sender, amount); } /** * @notice Used for unstaking the HEGIC tokens * in the form of selling the microlot. **/ function sellMicroLot(uint256 amount) external { require(amount > 0, "Amount is zero"); require( lastMicroBoughtTimestamp[msg.sender] + microLockupPeriod < block.timestamp, "The action is suspended due to the lockup" ); saveProfits(msg.sender); microLotsTotal -= amount; microBalance[msg.sender] -= amount; HEGIC.safeTransfer(msg.sender, amount); emit MicroLotsSold(msg.sender, amount); } /** * @notice Used for staking the fixed amount of 888,000 HEGIC * tokens in the form of buying the staking lot (transferrable) * for receiving a pro rata share of 80% of the total staking * rewards (settlement fees) generated by the protocol. **/ function buyStakingLot(uint256 amount) external override { lastBoughtTimestamp[msg.sender] = block.timestamp; require(amount > 0, "Amount is zero"); _mint(msg.sender, amount); HEGIC.safeTransferFrom( msg.sender, address(this), amount * STAKING_LOT_PRICE ); } /** * @notice Used for unstaking 888,000 HEGIC * tokens in the form of selling the staking lot. **/ function sellStakingLot(uint256 amount) external override lockupFree { _burn(msg.sender, amount); HEGIC.safeTransfer(msg.sender, amount * STAKING_LOT_PRICE); } function revertTransfersInLockUpPeriod(bool value) external { _revertTransfersInLockUpPeriod[msg.sender] = value; } /** * @notice Returns the amount of unclaimed staking rewards. **/ function profitOf(address account) external view override returns (uint256) { (uint256 profit, uint256 micro) = getUnsavedProfits(account); return savedProfit[account] + profit + micro; } /** * @notice Used for calculating the amount of accumulated * staking rewards before the share of the staking participant * changes higher (buying more microlots or staking lots) * or lower (selling more microlots or staking lots). **/ function getUnsavedProfits(address account) internal view returns (uint256 total, uint256 micro) { total = ((totalProfit - lastProfit[account]) * balanceOf(account)) / ACCURACY; micro = ((microLotsProfits - lastMicroLotProfits[account]) * microBalance[account]) / ACCURACY; } /** * @notice Used for saving the amount of accumulated * staking rewards before the staking participant's share * changes higher (buying more microlots or staking lots) * or lower (selling more microlots or staking lots). **/ function saveProfits(address account) internal { (uint256 unsaved, uint256 micro) = getUnsavedProfits(account); lastProfit[account] = totalProfit; lastMicroLotProfits[account] = microLotsProfits; savedProfit[account] += unsaved; savedProfit[account] += micro; } function _beforeTokenTransfer( address from, address to, uint256 ) internal override { if (from != address(0)) saveProfits(from); if (to != address(0)) saveProfits(to); if ( lastBoughtTimestamp[from] + classicLockupPeriod > block.timestamp && lastBoughtTimestamp[from] > lastBoughtTimestamp[to] ) { require( !_revertTransfersInLockUpPeriod[to], "The recipient does not agree to accept the locked funds" ); lastBoughtTimestamp[to] = lastBoughtTimestamp[from]; } } /** * @notice Used for distributing the staking rewards * among the microlots and staking lots holders. **/ function distributeUnrealizedRewards() external override { uint256 amount = token.balanceOf(address(this)) - realisedBalance; realisedBalance += amount; uint256 _totalSupply = totalSupply(); if (microLotsTotal + _totalSupply > 0) { if (microLotsTotal == 0) { totalProfit += (amount * ACCURACY) / _totalSupply; } else if (_totalSupply == 0) { microLotsProfits += (amount * ACCURACY) / microLotsTotal; } else { uint256 microAmount = amount / 5; uint256 baseAmount = amount - microAmount; microLotsProfits += (microAmount * ACCURACY) / microLotsTotal; totalProfit += (baseAmount * ACCURACY) / _totalSupply; } emit Profit(amount); } } modifier lockupFree { require( lastBoughtTimestamp[msg.sender] + classicLockupPeriod <= block.timestamp, "The action is suspended due to the lockup" ); _; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20 { uint8 private immutable _decimals; constructor( string memory name, string memory symbol, uint8 __decimals ) ERC20(name, symbol) { _decimals = __decimals; } function decimals() public view override returns (uint8) { return _decimals; } function mintTo(address account, uint256 amount) public { _mint(account, amount); } function mint(uint256 amount) public { _mint(msg.sender, amount); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./ERC20Mock.sol"; contract WETHMock is ERC20Mock("WETH", "Wrapped Ether", 18) { function deposit() external payable { _mint(msg.sender, msg.value); } function withdraw(uint256 amount) external { _burn(msg.sender, amount); payable(msg.sender).transfer(amount); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./ERC20Mock.sol"; import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol"; contract UniswapRouterMock { ERC20Mock public immutable WBTC; ERC20Mock public immutable USDC; AggregatorV3Interface public immutable WBTCPriceProvider; AggregatorV3Interface public immutable ETHPriceProvider; constructor( ERC20Mock _wbtc, ERC20Mock _usdc, AggregatorV3Interface wpp, AggregatorV3Interface epp ) { WBTC = _wbtc; USDC = _usdc; WBTCPriceProvider = wpp; ETHPriceProvider = epp; } function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 /*deadline*/ ) external payable returns (uint256[] memory amounts) { require(path.length == 2, "UniswapMock: wrong path"); require( path[1] == address(USDC) || path[1] == address(WBTC), "UniswapMock: too small value" ); amounts = getAmountsIn(amountOut, path); require(msg.value >= amounts[0], "UniswapMock: too small value"); if (msg.value > amounts[0]) payable(msg.sender).transfer(msg.value - amounts[0]); ERC20Mock(path[1]).mintTo(to, amountOut); } function getAmountsIn(uint256 amountOut, address[] calldata path) public view returns (uint256[] memory amounts) { require(path.length == 2, "UniswapMock: wrong path"); uint256 amount; if (path[1] == address(USDC)) { (, int256 ethPrice, , , ) = ETHPriceProvider.latestRoundData(); amount = (amountOut * 1e8) / uint256(ethPrice); } else if (path[1] == address(WBTC)) { (, int256 ethPrice, , , ) = ETHPriceProvider.latestRoundData(); (, int256 wbtcPrice, , , ) = WBTCPriceProvider.latestRoundData(); amount = (amountOut * uint256(wbtcPrice)) / uint256(ethPrice); } else { revert("UniswapMock: wrong path"); } amounts = new uint256[](2); amounts[0] = (amount * 103) / 100; amounts[1] = amountOut; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/IOptionsManager.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Options Manager Contract * @notice The contract that buys the options contracts for the options holders * as well as checks whether the contract that is used for buying/exercising * options has been been granted with the permission to do it on the user's behalf. **/ contract OptionsManager is IOptionsManager, ERC721("Hegic V8888 Options (Tokenized)", "HOT8888"), AccessControl { bytes32 public constant HEGIC_POOL_ROLE = keccak256("HEGIC_POOL_ROLE"); uint256 public nextTokenId = 0; mapping(uint256 => address) public override tokenPool; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev See EIP-165: ERC-165 Standard Interface Detection * https://eips.ethereum.org/EIPS/eip-165 **/ function createOptionFor(address holder) public override onlyRole(HEGIC_POOL_ROLE) returns (uint256 id) { id = nextTokenId++; tokenPool[id] = msg.sender; _safeMint(holder, id); } /** * @dev See EIP-165: ERC-165 Standard Interface Detection * https://eips.ethereum.org/EIPS/eip-165 **/ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl, IERC165) returns (bool) { return interfaceId == type(IOptionsManager).interfaceId || AccessControl.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId); } /** * @notice Used for checking whether the user has approved * the contract to buy/exercise the options on her behalf. * @param spender The address of the contract * that is used for exercising the options * @param tokenId The ERC721 token ID that is linked to the option **/ function isApprovedOrOwner(address spender, uint256 tokenId) external view virtual override returns (bool) { address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @notice The interface for the contract * that tokenizes options as ERC721. **/ interface IOptionsManager is IERC721 { /** * @param holder The option buyer address **/ function createOptionFor(address holder) external returns (uint256); /** * @param tokenId The ERC721 token ID linked to the option **/ function tokenPool(uint256 tokenId) external returns (address pool); /** * @param spender The option buyer address or another address * with the granted permission to buy/exercise options on the user's behalf * @param tokenId The ERC721 token ID linked to the option **/ function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../Interfaces/IOptionsManager.sol"; import "../Interfaces/Interfaces.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Main Pool Contract * @notice One of the main contracts that manages the pools and the options parameters, * accumulates the funds from the liquidity providers and makes the withdrawals for them, * sells the options contracts to the options buyers and collateralizes them, * exercises the ITM (in-the-money) options with the unrealized P&L and settles them, * unlocks the expired options and distributes the premiums among the liquidity providers. **/ abstract contract HegicPool is IHegicPool, ERC721, AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; uint256 public constant INITIAL_RATE = 1e20; IOptionsManager public immutable optionsManager; AggregatorV3Interface public immutable priceProvider; IPriceCalculator public override pricer; uint256 public lockupPeriodForHedgedTranches = 60 days; uint256 public lockupPeriodForUnhedgedTranches = 30 days; uint256 public hedgeFeeRate = 80; uint256 public maxUtilizationRate = 80; uint256 public collateralizationRatio = 50; uint256 public override lockedAmount; uint256 public maxDepositAmount = type(uint256).max; uint256 public maxHedgedDepositAmount = type(uint256).max; uint256 public unhedgedShare = 0; uint256 public hedgedShare = 0; uint256 public override unhedgedBalance = 0; uint256 public override hedgedBalance = 0; ISettlementFeeRecipient public settlementFeeRecipient; address public hedgePool; Tranche[] public override tranches; mapping(uint256 => Option) public override options; IERC20 public override token; constructor( IERC20 _token, string memory name, string memory symbol, IOptionsManager manager, IPriceCalculator _pricer, ISettlementFeeRecipient _settlementFeeRecipient, AggregatorV3Interface _priceProvider ) ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); priceProvider = _priceProvider; settlementFeeRecipient = _settlementFeeRecipient; pricer = _pricer; token = _token; hedgePool = _msgSender(); optionsManager = manager; } /** * @notice Used for setting the liquidity lock-up periods during which * the liquidity providers who deposited the funds into the pools contracts * won't be able to withdraw them. Note that different lock-ups could * be set for the hedged and unhedged — classic — liquidity tranches. * @param hedgedValue Hedged liquidity tranches lock-up in seconds * @param unhedgedValue Unhedged (classic) liquidity tranches lock-up in seconds **/ function setLockupPeriod(uint256 hedgedValue, uint256 unhedgedValue) external override onlyRole(DEFAULT_ADMIN_ROLE) { require( hedgedValue <= 60 days, "The lockup period for hedged tranches is too long" ); require( unhedgedValue <= 30 days, "The lockup period for unhedged tranches is too long" ); lockupPeriodForHedgedTranches = hedgedValue; lockupPeriodForUnhedgedTranches = unhedgedValue; } /** * @notice Used for setting the total maximum amount * that could be deposited into the pools contracts. * Note that different total maximum amounts could be set * for the hedged and unhedged — classic — liquidity tranches. * @param total Maximum amount of assets in the pool * in hedged and unhedged (classic) liquidity tranches combined * @param hedged Maximum amount of assets in the pool * in hedged liquidity tranches only **/ function setMaxDepositAmount(uint256 total, uint256 hedged) external onlyRole(DEFAULT_ADMIN_ROLE) { require( total >= hedged, "Pool Error: The total amount shouldn't be lower than the hedged amount" ); maxDepositAmount = total; maxHedgedDepositAmount = hedged; } /** * @notice Used for setting the maximum share of the pool * size that could be utilized as a collateral in the options. * * Example: if `MaxUtilizationRate` = 50, then only 50% * of liquidity on the pools contracts would be used for * collateralizing options while 50% will be sitting idle * available for withdrawals by the liquidity providers. * @param value The utilization ratio in a range of 50% — 100% **/ function setMaxUtilizationRate(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { require( 50 <= value && value <= 100, "Pool error: Wrong utilization rate limitation value" ); maxUtilizationRate = value; } /** * @notice Used for setting the collateralization ratio for the option * collateral size that will be locked at the moment of buying them. * * Example: if `CollateralizationRatio` = 50, then 50% of an option's * notional size will be locked in the pools at the moment of buying it: * say, 1 ETH call option will be collateralized with 0.5 ETH (50%). * Note that if an option holder's net P&L USD value (as options * are cash-settled) will exceed the amount of the collateral locked * in the option, she will receive the required amount at the moment * of exercising the option using the pool's unutilized (unlocked) funds. * @param value The collateralization ratio in a range of 30% — 100% **/ function setCollateralizationRatio(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { require( 30 <= value && value <= 100, "Pool Error: Wrong collateralization ratio value" ); collateralizationRatio = value; } /** * @dev See EIP-165: ERC-165 Standard Interface Detection * https://eips.ethereum.org/EIPS/eip-165. **/ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl, IERC165) returns (bool) { return interfaceId == type(IHegicPool).interfaceId || AccessControl.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId); } /** * @notice Used for changing the hedging pool address * that will be accumulating the hedging premiums paid * as a share of the total premium redirected to this address. * @param value The address for receiving hedging premiums **/ function setHedgePool(address value) external override onlyRole(DEFAULT_ADMIN_ROLE) { require(value != address(0)); hedgePool = value; } /** * @notice Used for selling the options contracts * with the parameters chosen by the option buyer * such as the period of holding, option size (amount), * strike price and the premium to be paid for the option. * @param holder The option buyer address * @param period The option period * @param amount The option size * @param strike The option strike * @return id ID of ERC721 token linked to the option **/ function sellOption( address holder, uint256 period, uint256 amount, uint256 strike ) external override returns (uint256 id) { if (strike == 0) strike = _currentPrice(); uint256 balance = totalBalance(); uint256 amountToBeLocked = _calculateLockedAmount(amount); require(period >= 1 days, "Pool Error: The period is too short"); require(period <= 90 days, "Pool Error: The period is too long"); require( (lockedAmount + amountToBeLocked) * 100 <= balance * maxUtilizationRate, "Pool Error: The amount is too large" ); (uint256 settlementFee, uint256 premium) = _calculateTotalPremium(period, amount, strike); uint256 hedgedPremiumTotal = (premium * hedgedBalance) / balance; uint256 hedgeFee = (hedgedPremiumTotal * hedgeFeeRate) / 100; uint256 hedgePremium = hedgedPremiumTotal - hedgeFee; uint256 unhedgePremium = premium - hedgedPremiumTotal; lockedAmount += amountToBeLocked; id = optionsManager.createOptionFor(holder); options[id] = Option( OptionState.Active, strike, amount, amountToBeLocked, block.timestamp + period, hedgePremium, unhedgePremium ); token.safeTransferFrom( _msgSender(), address(this), premium + settlementFee ); token.safeTransfer(address(settlementFeeRecipient), settlementFee); settlementFeeRecipient.distributeUnrealizedRewards(); if (hedgeFee > 0) token.safeTransfer(hedgePool, hedgeFee); emit Acquired(id, settlementFee, premium); } /** * @notice Used for setting the price calculator * contract that will be used for pricing the options. * @param pc A new price calculator contract address **/ function setPriceCalculator(IPriceCalculator pc) public onlyRole(DEFAULT_ADMIN_ROLE) { pricer = pc; } /** * @notice Used for exercising the ITM (in-the-money) * options contracts in case of having the unrealized profits * accrued during the period of holding the option contract. * @param id ID of ERC721 token linked to the option **/ function exercise(uint256 id) external override { Option storage option = options[id]; uint256 profit = _profitOf(option); require( optionsManager.isApprovedOrOwner(_msgSender(), id), "Pool Error: msg.sender can't exercise this option" ); require( option.expired > block.timestamp, "Pool Error: The option has already expired" ); require( profit > 0, "Pool Error: There are no unrealized profits for this option" ); _unlock(option); option.state = OptionState.Exercised; _send(optionsManager.ownerOf(id), profit); emit Exercised(id, profit); } function _send(address to, uint256 transferAmount) private { require(to != address(0)); uint256 hedgeLoss = (transferAmount * hedgedBalance) / totalBalance(); uint256 unhedgeLoss = transferAmount - hedgeLoss; hedgedBalance -= hedgeLoss; unhedgedBalance -= unhedgeLoss; token.safeTransfer(to, transferAmount); } /** * @notice Used for unlocking the expired OTM (out-of-the-money) * options contracts in case if there was no unrealized P&L * accrued during the period of holding a particular option. * Note that the `unlock` function releases the liquidity that * was locked in the option when it was active and the premiums * that are distributed pro rata among the liquidity providers. * @param id ID of ERC721 token linked to the option **/ function unlock(uint256 id) external override { Option storage option = options[id]; require( option.expired < block.timestamp, "Pool Error: The option has not expired yet" ); _unlock(option); option.state = OptionState.Expired; emit Expired(id); } function _unlock(Option storage option) internal { require( option.state == OptionState.Active, "Pool Error: The option with such an ID has already been exercised or expired" ); lockedAmount -= option.lockedAmount; hedgedBalance += option.hedgePremium; unhedgedBalance += option.unhedgePremium; } function _calculateLockedAmount(uint256 amount) internal virtual returns (uint256) { return (amount * collateralizationRatio) / 100; } /** * @notice Used for depositing the funds into the pool * and minting the liquidity tranche ERC721 token * which represents the liquidity provider's share * in the pool and her unrealized P&L for this tranche. * @param account The liquidity provider's address * @param amount The size of the liquidity tranche * @param hedged The type of the liquidity tranche * @param minShare The minimum share in the pool for the user **/ function provideFrom( address account, uint256 amount, bool hedged, uint256 minShare ) external override nonReentrant returns (uint256 share) { uint256 totalShare = hedged ? hedgedShare : unhedgedShare; uint256 balance = hedged ? hedgedBalance : unhedgedBalance; share = totalShare > 0 && balance > 0 ? (amount * totalShare) / balance : amount * INITIAL_RATE; uint256 limit = hedged ? maxHedgedDepositAmount - hedgedBalance : maxDepositAmount - hedgedBalance - unhedgedBalance; require(share >= minShare, "Pool Error: The mint limit is too large"); require(share > 0, "Pool Error: The amount is too small"); require( amount <= limit, "Pool Error: Depositing into the pool is not available" ); if (hedged) { hedgedShare += share; hedgedBalance += amount; } else { unhedgedShare += share; unhedgedBalance += amount; } uint256 trancheID = tranches.length; tranches.push( Tranche(TrancheState.Open, share, amount, block.timestamp, hedged) ); _safeMint(account, trancheID); token.safeTransferFrom(_msgSender(), address(this), amount); } /** * @notice Used for withdrawing the funds from the pool * plus the net positive P&L earned or * minus the net negative P&L lost on * providing liquidity and selling options. * @param trancheID The liquidity tranche ID * @return amount The amount received after the withdrawal **/ function withdraw(uint256 trancheID) external override nonReentrant returns (uint256 amount) { address owner = ownerOf(trancheID); Tranche memory t = tranches[trancheID]; amount = _withdraw(owner, trancheID); if (t.hedged && amount < t.amount) { token.safeTransferFrom(hedgePool, owner, t.amount - amount); amount = t.amount; } emit Withdrawn(owner, trancheID, amount); } /** * @notice Used for withdrawing the funds from the pool * by the hedged liquidity tranches providers * in case of an urgent need to withdraw the liquidity * without receiving the loss compensation from * the hedging pool: the net difference between * the amount deposited and the withdrawal amount. * @param trancheID ID of liquidity tranche * @return amount The amount received after the withdrawal **/ function withdrawWithoutHedge(uint256 trancheID) external override nonReentrant returns (uint256 amount) { address owner = ownerOf(trancheID); amount = _withdraw(owner, trancheID); emit Withdrawn(owner, trancheID, amount); } function _withdraw(address owner, uint256 trancheID) internal returns (uint256 amount) { Tranche storage t = tranches[trancheID]; uint256 lockupPeriod = t.hedged ? lockupPeriodForHedgedTranches : lockupPeriodForUnhedgedTranches; require(t.state == TrancheState.Open); require(_isApprovedOrOwner(_msgSender(), trancheID)); require( block.timestamp > t.creationTimestamp + lockupPeriod, "Pool Error: The withdrawal is locked up" ); t.state = TrancheState.Closed; if (t.hedged) { amount = (t.share * hedgedBalance) / hedgedShare; hedgedShare -= t.share; hedgedBalance -= amount; } else { amount = (t.share * unhedgedBalance) / unhedgedShare; unhedgedShare -= t.share; unhedgedBalance -= amount; } token.safeTransfer(owner, amount); } /** * @return balance Returns the amount of liquidity available for withdrawing **/ function availableBalance() public view returns (uint256 balance) { return totalBalance() - lockedAmount; } /** * @return balance Returns the total balance of liquidity provided to the pool **/ function totalBalance() public view override returns (uint256 balance) { return hedgedBalance + unhedgedBalance; } function _beforeTokenTransfer( address, address, uint256 id ) internal view override { require( tranches[id].state == TrancheState.Open, "Pool Error: The closed tranches can not be transferred" ); } /** * @notice Returns the amount of unrealized P&L of the option * that could be received by the option holder in case * if she exercises it as an ITM (in-the-money) option. * @param id ID of ERC721 token linked to the option **/ function profitOf(uint256 id) external view returns (uint256) { return _profitOf(options[id]); } function _profitOf(Option memory option) internal view virtual returns (uint256 amount); /** * @notice Used for calculating the `TotalPremium` * for the particular option with regards to * the parameters chosen by the option buyer * such as the period of holding, size (amount) * and strike price. * @param period The period of holding the option * @param period The size of the option **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) external view override returns (uint256 settlementFee, uint256 premium) { return _calculateTotalPremium(period, amount, strike); } function _calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) internal view virtual returns (uint256 settlementFee, uint256 premium) { (settlementFee, premium) = pricer.calculateTotalPremium( period, amount, strike ); require( settlementFee + premium > amount / 1000, "HegicPool: The option's price is too low" ); } /** * @notice Used for changing the `settlementFeeRecipient` * contract address for distributing the settlement fees * (staking rewards) among the staking participants. * @param recipient New staking contract address **/ function setSettlementFeeRecipient(IHegicStaking recipient) external onlyRole(DEFAULT_ADMIN_ROLE) { require(address(recipient) != address(0)); settlementFeeRecipient = recipient; } function _currentPrice() internal view returns (uint256 price) { (, int256 latestPrice, , , ) = priceProvider.latestRoundData(); price = uint256(latestPrice); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./HegicPool.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Put Liquidity Pool Contract * @notice The Put Liquidity Pool Contract **/ contract HegicPUT is HegicPool { uint256 private immutable SpotDecimals; // 1e18 uint256 private constant TokenDecimals = 1e6; // 1e6 /** * @param name The pool contract name * @param symbol The pool ticker for the ERC721 options **/ constructor( IERC20 _token, string memory name, string memory symbol, IOptionsManager manager, IPriceCalculator _pricer, IHegicStaking _settlementFeeRecipient, AggregatorV3Interface _priceProvider, uint8 spotDecimals ) HegicPool( _token, name, symbol, manager, _pricer, _settlementFeeRecipient, _priceProvider ) { SpotDecimals = 10**spotDecimals; } function _profitOf(Option memory option) internal view override returns (uint256 amount) { uint256 currentPrice = _currentPrice(); if (currentPrice > option.strike) return 0; return ((option.strike - currentPrice) * option.amount * TokenDecimals) / SpotDecimals / 1e8; } function _calculateLockedAmount(uint256 amount) internal view override returns (uint256) { return (amount * collateralizationRatio * _currentPrice() * TokenDecimals) / SpotDecimals / 1e8 / 100; } function _calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) internal view override returns (uint256 settlementFee, uint256 premium) { uint256 currentPrice = _currentPrice(); (settlementFee, premium) = pricer.calculateTotalPremium( period, amount, strike ); settlementFee = (settlementFee * currentPrice * TokenDecimals) / 1e8 / SpotDecimals; premium = (premium * currentPrice * TokenDecimals) / 1e8 / SpotDecimals; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./HegicPool.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Call Liquidity Pool Contract * @notice The Call Liquidity Pool Contract **/ contract HegicCALL is HegicPool { /** * @param name The pool contract name * @param symbol The pool ticker for the ERC721 options **/ constructor( IERC20 _token, string memory name, string memory symbol, IOptionsManager manager, IPriceCalculator _pricer, IHegicStaking _settlementFeeRecipient, AggregatorV3Interface _priceProvider ) HegicPool( _token, name, symbol, manager, _pricer, _settlementFeeRecipient, _priceProvider ) {} function _profitOf(Option memory option) internal view override returns (uint256 amount) { uint256 currentPrice = _currentPrice(); if (currentPrice < option.strike) return 0; return ((currentPrice - option.strike) * option.amount) / currentPrice; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../Interfaces/IOptionsManager.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Facade Contract * @notice The contract that calculates the options prices, * conducts the process of buying options, converts the premiums * into the token that the pool is denominated in and grants * permissions to the contracts such as GSN (Gas Station Network). **/ contract Facade is Ownable { using SafeERC20 for IERC20; IWETH public immutable WETH; IUniswapV2Router01 public immutable exchange; IOptionsManager public immutable optionsManager; address public _trustedForwarder; constructor( IWETH weth, IUniswapV2Router01 router, IOptionsManager manager, address trustedForwarder ) { WETH = weth; exchange = router; _trustedForwarder = trustedForwarder; optionsManager = manager; } /** * @notice Used for calculating the option price (the premium) and using * the swap router (if needed) to convert the tokens with which the user * pays the premium into the token in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike * @param total The total premium * @param baseTotal The part of the premium that * is distributed among the liquidity providers * @param settlementFee The part of the premium that * is distributed among the HEGIC staking participants **/ function getOptionPrice( IHegicPool pool, uint256 period, uint256 amount, uint256 strike, address[] calldata swappath ) public view returns ( uint256 total, uint256 baseTotal, uint256 settlementFee, uint256 premium ) { (uint256 _baseTotal, uint256 baseSettlementFee, uint256 basePremium) = getBaseOptionCost(pool, period, amount, strike); if (swappath.length > 1) total = exchange.getAmountsIn(_baseTotal, swappath)[0]; else total = _baseTotal; baseTotal = _baseTotal; settlementFee = (total * baseSettlementFee) / baseTotal; premium = (total * basePremium) / baseTotal; } /** * @notice Used for calculating the option price (the premium) * in the token in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike **/ function getBaseOptionCost( IHegicPool pool, uint256 period, uint256 amount, uint256 strike ) public view returns ( uint256 total, uint256 settlementFee, uint256 premium ) { (settlementFee, premium) = pool.calculateTotalPremium( period, amount, strike ); total = premium + settlementFee; } /** * @notice Used for approving the pools contracts addresses. **/ function poolApprove(IHegicPool pool) external { pool.token().safeApprove(address(pool), 0); pool.token().safeApprove(address(pool), type(uint256).max); } /** * @notice Used for buying the option contract and converting * the buyer's tokens (the total premium) into the token * in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike * @param acceptablePrice The highest acceptable price **/ function createOption( IHegicPool pool, uint256 period, uint256 amount, uint256 strike, address[] calldata swappath, uint256 acceptablePrice ) external { address buyer = _msgSender(); (uint256 optionPrice, uint256 rawOptionPrice, , ) = getOptionPrice(pool, period, amount, strike, swappath); require( optionPrice <= acceptablePrice, "Facade Error: The option price is too high" ); IERC20 paymentToken = IERC20(swappath[0]); paymentToken.safeTransferFrom(buyer, address(this), optionPrice); if (swappath.length > 1) { if ( paymentToken.allowance(address(this), address(exchange)) < optionPrice ) { paymentToken.safeApprove(address(exchange), 0); paymentToken.safeApprove(address(exchange), type(uint256).max); } exchange.swapTokensForExactTokens( rawOptionPrice, optionPrice, swappath, address(this), block.timestamp ); } pool.sellOption(buyer, period, amount, strike); } /** * @notice Used for converting the liquidity provider's Ether (ETH) * into Wrapped Ether (WETH) and providing the funds into the pool. * @param hedged The liquidity tranche type: hedged or unhedged (classic) **/ function provideEthToPool( IHegicPool pool, bool hedged, uint256 minShare ) external payable returns (uint256) { WETH.deposit{value: msg.value}(); if (WETH.allowance(address(this), address(pool)) < msg.value) WETH.approve(address(pool), type(uint256).max); return pool.provideFrom(msg.sender, msg.value, hedged, minShare); } /** * @notice Unlocks the array of options. * @param optionIDs The array of options **/ function unlockAll(IHegicPool pool, uint256[] calldata optionIDs) external { uint256 arrayLength = optionIDs.length; for (uint256 i = 0; i < arrayLength; i++) { pool.unlock(optionIDs[i]); } } /** * @notice Used for granting the GSN (Gas Station Network) contract * the permission to pay the gas (transaction) fees for the users. * @param forwarder GSN (Gas Station Network) contract address **/ function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == _trustedForwarder; } function claimAllStakingProfits( IHegicStaking[] calldata stakings, address account ) external { uint256 arrayLength = stakings.length; for (uint256 i = 0; i < arrayLength; i++) { IHegicStaking s = stakings[i]; if (s.profitOf(account) > 0) s.claimProfits(account); } } function _msgSender() internal view override returns (address signer) { signer = msg.sender; if (msg.data.length >= 20 && isTrustedForwarder(signer)) { assembly { signer := shr(96, calldataload(sub(calldatasize(), 20))) } } } function exercise(uint256 optionId) external { require( optionsManager.isApprovedOrOwner(_msgSender(), optionId), "Facade Error: _msgSender is not eligible to exercise the option" ); IHegicPool(optionsManager.tokenPool(optionId)).exercise(optionId); } function versionRecipient() external pure returns (string memory) { return "2.2.2"; } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "./Interfaces/IOptionsManager.sol"; import "./Interfaces/Interfaces.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Exerciser Contract * @notice The contract that allows to automatically exercise options half an hour before expiration **/ contract Exerciser { IOptionsManager immutable optionsManager; constructor(IOptionsManager manager) { optionsManager = manager; } function exercise(uint256 optionId) external { IHegicPool pool = IHegicPool(optionsManager.tokenPool(optionId)); (, , , , uint256 expired, , ) = pool.options(optionId); require( block.timestamp > expired - 30 minutes, "Facade Error: Automatically exercise for this option is not available yet" ); pool.exercise(optionId); } } /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev A contract that allows to lock-up the rewards in * the Hegic Long-Term Pools during a certain period of time. */ contract HLTPs { using SafeERC20 for IERC20; // The beneficiary of rewards after they are released address private immutable _beneficiary; // The timestamp when the rewards release will be enabled uint256 private immutable _releaseTime; constructor(uint256 releaseTime_) { _beneficiary = msg.sender; _releaseTime = releaseTime_; } /** * @return The beneficiary address that will distribute the rewards. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return The point of time when the rewards will be released. */ function releaseTime() public view returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens locked by timelock to beneficiary. */ function release(IERC20 token) public { require( block.timestamp >= releaseTime(), "HLTPs: Current time is earlier than the release time" ); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "HLTPs: No rewards to be released"); token.safeTransfer(beneficiary(), amount); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Linear.sol"; import "./IBondingCurve.sol"; contract Erc20BondingCurve is LinearBondingCurve { using SafeERC20 for IERC20; IERC20 public immutable saleToken; IERC20 public immutable purchaseToken; uint256 public soldAmount; uint256 public comissionShare = 20; address payable public hegicDevelopmentFund; event Bought(address indexed account, uint256 amount, uint256 ethAmount); event Sold( address indexed account, uint256 amount, uint256 ethAmount, uint256 comission ); constructor( IERC20 _saleToken, IERC20 _purchaseToken, uint256 k, uint256 startPrice ) LinearBondingCurve(k, startPrice) { saleToken = _saleToken; purchaseToken = _purchaseToken; hegicDevelopmentFund = payable(msg.sender); _setupRole(LBC_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function buy(uint256 tokenAmount) external { uint256 nextSold = soldAmount + tokenAmount; uint256 purchaseAmount = s(soldAmount, nextSold); soldAmount = nextSold; purchaseToken.safeTransferFrom( msg.sender, address(this), purchaseAmount ); saleToken.safeTransfer(msg.sender, tokenAmount); emit Bought(msg.sender, tokenAmount, purchaseAmount); } function sell(uint256 tokenAmount) external { uint256 nextSold = soldAmount - tokenAmount; uint256 saleAmount = s(nextSold, soldAmount); uint256 comission = (saleAmount * comissionShare) / 100; uint256 refund = saleAmount - comission; require(comission > 0, "Amount is too small"); soldAmount = nextSold; saleToken.safeTransferFrom(msg.sender, address(this), tokenAmount); purchaseToken.safeTransfer(hegicDevelopmentFund, comission); purchaseToken.safeTransfer(msg.sender, refund); emit Sold(msg.sender, tokenAmount, refund, comission); } function setHDF(address payable value) external onlyRole(DEFAULT_ADMIN_ROLE) { hegicDevelopmentFund = value; } function setCommissionShare(uint256 value) external onlyRole(DEFAULT_ADMIN_ROLE) { comissionShare = value; } function destruct() external onlyRole(DEFAULT_ADMIN_ROLE) { selfdestruct(hegicDevelopmentFund); } function withdawERC20(IERC20 token) external onlyRole(DEFAULT_ADMIN_ROLE) { token.transfer(hegicDevelopmentFund, token.balanceOf(address(this))); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../utils/Math.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Price Calculator Contract * @notice The contract that calculates the options prices (the premiums) * that are adjusted through the `ImpliedVolRate` parameter. **/ contract PriceCalculator is IPriceCalculator, Ownable { using HegicMath for uint256; uint256 public impliedVolRate; uint256 internal constant PRICE_DECIMALS = 1e8; uint256 internal constant PRICE_MODIFIER_DECIMALS = 1e8; uint256 public settlementFeeShare = 24; uint256 public maxPeriod = 30 days; AggregatorV3Interface public priceProvider; constructor(uint256 initialRate, AggregatorV3Interface _priceProvider) { priceProvider = _priceProvider; impliedVolRate = initialRate; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New IVRate value **/ function setImpliedVolRate(uint256 value) external onlyOwner { impliedVolRate = value; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New settlementFeeShare value **/ function setSettlementFeeShare(uint256 value) external onlyOwner { require(value <= 100, "The value is too large"); settlementFeeShare = value; } function setMaxPeriod(uint256 value) external onlyOwner { maxPeriod = value; } /** * @notice Used for calculating the options prices * @param period The option period in seconds (1 days <= period <= 90 days) * @param amount The option size * @param strike The option strike * @return settlementFee The part of the premium that * is distributed among the HEGIC staking participants * @return premium The part of the premium that * is distributed among the liquidity providers **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) public view override returns (uint256 settlementFee, uint256 premium) { uint256 currentPrice = _currentPrice(); if (strike == 0) strike = currentPrice; require(period <= maxPeriod, "PriceCalculator: Period is too long"); require( strike == currentPrice, "Only ATM options are currently available" ); uint256 total = _calculatePeriodFee(amount, period); settlementFee = (total * settlementFeeShare) / 100; premium = total - settlementFee; } /** * @notice Calculates and prices in the time value of the option * @param amount Option size * @param period The option period in seconds (1 days <= period <= 90 days) * @return fee The premium size to be paid **/ function _calculatePeriodFee(uint256 amount, uint256 period) internal view returns (uint256 fee) { return (amount * impliedVolRate * period.sqrt()) / PRICE_DECIMALS / PRICE_MODIFIER_DECIMALS; } /** * @notice Used for requesting the current price of the asset * using the ChainLink data feeds contracts. * See https://feeds.chain.link/ * @return price Price **/ function _currentPrice() internal view returns (uint256 price) { (, int256 latestPrice, , , ) = priceProvider.latestRoundData(); price = uint256(latestPrice); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ library HegicMath { /** * @dev Calculates a square root of the number. * Responds with an "invalid opcode" at uint(-1). **/ function sqrt(uint256 x) internal pure returns (uint256 result) { result = x; uint256 k = (x >> 1) + 1; while (k < result) (result, k) = (k, (x / k + k) >> 1); } } pragma solidity 0.8.6; /** * SPDX-License-Identifier: GPL-3.0-or-later * Hegic * Copyright (C) 2021 Hegic Protocol * * This program 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, either version 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. **/ import "../Interfaces/Interfaces.sol"; import "../utils/Math.sol"; /** * @author 0mllwntrmt3 * @title Hegic Protocol V8888 Price Calculator Contract * @notice The contract that calculates the options prices (the premiums) * that are adjusted through the `ImpliedVolRate` parameter. **/ contract PriceCalculatorUtilization is IPriceCalculator, Ownable { using HegicMath for uint256; uint256 public impliedVolRate; uint256 internal constant PRICE_DECIMALS = 1e8; uint256 internal constant PRICE_MODIFIER_DECIMALS = 1e8; uint256 public utilizationRate = 0; uint256 public settlementFeeShare = 24; AggregatorV3Interface public priceProvider; IHegicPool pool; constructor( uint256 initialRate, AggregatorV3Interface _priceProvider, IHegicPool _pool ) { pool = _pool; priceProvider = _priceProvider; impliedVolRate = initialRate; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New IVRate value **/ function setImpliedVolRate(uint256 value) external onlyOwner { impliedVolRate = value; } /** * @notice Used for adjusting the options prices (the premiums) * while balancing the asset's implied volatility rate. * @param value New IVRate value **/ function setSettlementFeeShare(uint256 value) external onlyOwner { require(value <= 100, "The value is too large"); settlementFeeShare = value; } /** * @notice Used for updating utilizationRate value * @param value New utilizationRate value **/ function setUtilizationRate(uint256 value) external onlyOwner { utilizationRate = value; } /** * @notice Used for calculating the options prices * @param period The option period in seconds (1 days <= period <= 90 days) * @param amount The option size * @param strike The option strike * @return settlementFee The part of the premium that * is distributed among the HEGIC staking participants * @return premium The part of the premium that * is distributed among the liquidity providers **/ function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) public view override returns (uint256 settlementFee, uint256 premium) { uint256 currentPrice = _currentPrice(); if (strike == 0) strike = currentPrice; require( strike == currentPrice, "Only ATM options are currently available" ); uint256 total = _calculatePeriodFee(amount, period); settlementFee = (total * settlementFeeShare) / 100; premium = total - settlementFee; } /** * @notice Calculates and prices in the time value of the option * @param amount Option size * @param period The option period in seconds (1 days <= period <= 90 days) * @return fee The premium size to be paid **/ function _calculatePeriodFee(uint256 amount, uint256 period) internal view returns (uint256 fee) { return (amount * _priceModifier(amount, period, pool)) / PRICE_DECIMALS / PRICE_MODIFIER_DECIMALS; } /** * @notice Calculates `periodFee` of the option * @param amount The option size * @param period The option period in seconds (1 days <= period <= 90 days) **/ function _priceModifier( uint256 amount, uint256 period, IHegicPool pool ) internal view returns (uint256 iv) { uint256 poolBalance = pool.totalBalance(); require(poolBalance > 0, "Pool Error: The pool is empty"); iv = impliedVolRate * period.sqrt(); uint256 lockedAmount = pool.lockedAmount() + amount; uint256 utilization = (lockedAmount * 100e8) / poolBalance; if (utilization > 40e8) { iv += (iv * (utilization - 40e8) * utilizationRate) / 40e16; } } /** * @notice Used for requesting the current price of the asset * using the ChainLink data feeds contracts. * See https://feeds.chain.link/ * @return price Price **/ function _currentPrice() internal view returns (uint256 price) { (, int256 latestPrice, , , ) = priceProvider.latestRoundData(); price = uint256(latestPrice); } } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } pragma solidity >=0.5.0; interface IUniswapV2ERC20 { 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; } pragma solidity >=0.6.0; // 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'); } }
Used for calculating the options prices period The option period in seconds (1 days <= period <= 90 days) amount The option size strike The option strike return settlementFee The part of the premium that is distributed among the HEGIC staking participants return premium The part of the premium that is distributed among the liquidity providers/
function calculateTotalPremium( uint256 period, uint256 amount, uint256 strike ) public view override returns (uint256 settlementFee, uint256 premium) { uint256 currentPrice = _currentPrice(); if (strike == 0) strike = currentPrice; require(period <= maxPeriod, "PriceCalculator: Period is too long"); require( strike == currentPrice, "Only ATM options are currently available" ); uint256 total = _calculatePeriodFee(amount, period); settlementFee = (total * settlementFeeShare) / 100; premium = total - settlementFee; }
31,938
./partial_match/4/0xd4F79e5f4213b2403d12Be4CCd52b7575e0a88fb/sources/contracts/interfaces/IParameterRegistry.sol
2000 ETH maximum cap
function MAXIMUM_ETH_CONTRIBUTION() external pure returns (uint256);
8,656,506
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.12; /// @creator: Zoombiezoo /// @author: op3n.world import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Royalty.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./IPikoZooNFT.sol"; contract PikoZooNFT is AccessControl, IPikoZooNFT, ERC721Royalty { using ECDSA for bytes32; using Address for address; uint256 public constant UNIT_PRICE = 80000000000000000; // 0.08 ETH uint8 public constant MAX_PRESALE_PER_MINTER = 2; uint256 public constant PRESALE_START_AT = 1650942000; // Tuesday, 26 April 2022 10:00:00 GMT+07:00 uint256 public constant PUBSALE_START_AT = 1651114800; // Tuesday, 28 April 2022 10:00:00 GMT+07:00 address private _owner; address payable private _fundRecipient; bytes32 private _preSaleRoot; string private _tokenURI; uint256 private _tokenCount; uint256 private _totalSupply; uint8 private _giveawayCount; uint8 private _maxGiveaway; mapping(address => bool) private _verifiers; mapping(bytes32 => bool) public finalized; mapping(address => uint8) private _preSaleMinted; /** * @dev Initializes the contract with name is `PikoZoo`, `symbol` is `PKZ`, owner is deployer to the token collection. */ constructor() ERC721("PikoZoo", "PKZ") { _owner = _msgSender(); _grantRole(DEFAULT_ADMIN_ROLE, _owner); } /** * @dev See {IERC165-supportsInterface}, {IERC2981-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721Royalty, IERC165) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Modifier that checks that an account has an admin role. */ modifier onlyAdmin() { _checkRole(DEFAULT_ADMIN_ROLE, _msgSender()); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Returns the address of the current owner. */ function owner() public view override returns (address) { return _owner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { _owner = newOwner; } /** * @dev Returns totalSupply address. */ function totalSupply() external view override returns (uint256) { return _totalSupply; } /** * @dev Returns giveawayCount address. */ function giveawayCount() external view override returns (uint256) { return _giveawayCount; } /** * @dev Returns maxGiveaway address. */ function maxGiveaway() external view override returns (uint256) { return _maxGiveaway; } /** * @dev Check address is verifier */ function isVerifier(address verifier_) external view override returns (bool) { return _verifiers[verifier_]; } /** * @dev Set mint verifier of this contract * Can only be called by the admin. */ function setVerifier(address verifier_) external override onlyAdmin { _verifiers[verifier_] = true; } /** * @dev Revoke mint verifier of this contract * Can only be called by the admin. */ function revokeVerifier(address verifier_) external override onlyAdmin { _verifiers[verifier_] = false; } /** * @dev set tokenURI. */ function setTokenURI(string memory tokenURI_) external override onlyAdmin{ _tokenURI = tokenURI_; } /** * @dev Set preSaleRoot of this contract * Can only be called by the admin. */ function setPreSaleRoot(bytes32 root_) external override onlyAdmin { _preSaleRoot = root_; } /** * @dev Get preSaleRoot */ function preSaleRoot() external view returns(bytes32) { return _preSaleRoot; } /** * @dev Set royalty of this contract */ function setDefaultRoyalty(address receiver, uint96 feeNumerator) external override onlyAdmin { _setDefaultRoyalty(receiver, feeNumerator); } /** * @dev Set fundRecipient of this contract * Can only be called by the admin. */ function setFundRecipient(address fundRecipient_) external override onlyAdmin { _fundRecipient = payable(fundRecipient_); } /** * @dev Returns fundRecipient address. */ function fundRecipient() external view override returns (address) { return _fundRecipient; } /** * @dev Returns tokenCount address. */ function tokenCount() external view override returns (uint256) { return _tokenCount; } /** * @dev See {ERC721-_burn}, {ERC721Royalty-_burn} */ function _burn(uint256 tokenId) internal virtual override(ERC721Royalty) { super._burn(tokenId); } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual override returns (string memory) { return _tokenURI; } /** * @dev Activate this contract * Can only be called by the admin. */ function activate(uint256 totalSupply_, uint8 maxGiveaway_, address fundRecipient_, address royaltyRecipient_) external override onlyAdmin { require(_totalSupply == 0, "PKZ: Already activated"); _totalSupply = totalSupply_; _maxGiveaway = maxGiveaway_; _fundRecipient = payable(fundRecipient_); _setDefaultRoyalty(royaltyRecipient_, 750); } /** * @dev validate a mint. */ function _validateMint(bytes32[] memory proof) internal returns (bool) { if (PUBSALE_START_AT <= block.timestamp) { return true; } if (PRESALE_START_AT <= block.timestamp && MerkleProof.verify(proof, _preSaleRoot, keccak256(abi.encodePacked(_msgSender())))) { if (MAX_PRESALE_PER_MINTER <= _preSaleMinted[_msgSender()]) { return false; } _preSaleMinted[_msgSender()]++; return true; } return false; } /** * @dev validate a sig. */ function _validateSig(uint256 salt, bytes memory sig) internal returns (bool) { bytes32 _verifiedHash = keccak256(abi.encodePacked(msg.sender, salt)); if (finalized[_verifiedHash]) { return false; } if (!_verifiers[_verifiedHash.toEthSignedMessageHash().recover(sig)]) { return false; } finalized[_verifiedHash] = true; return true; } /** * @dev internal mint a NFT. */ function _mintNFT(address to, uint256 tokenId) internal { require(tokenId <= _totalSupply, "PKZ: Invalid TokenId"); _tokenCount++; _mint(to, tokenId); } /** * @dev mint a NFT. */ function mint(uint256 tokenId, uint256 salt, bytes memory sig, bytes32[] memory proof) external payable override { require(UNIT_PRICE <= msg.value, "PKZ: Invalid amount"); require(_validateMint(proof), "PKZ: Invalid mint"); require(_validateSig(salt, sig), "PKZ: Invalid signature"); Address.sendValue(_fundRecipient, msg.value); _mintNFT(msg.sender, tokenId); } /** * @dev mint NFTs. */ function mintBatch(uint256[] memory tokenIds, uint256 salt, bytes memory sig, bytes32[] memory proof) external payable override { uint256 mintCount = tokenIds.length; require(UNIT_PRICE * mintCount <= msg.value, "PKZ: Invalid amount"); require(_validateMint(proof), "PKZ: Invalid mint"); require(_validateSig(salt, sig), "PKZ: Invalid signature"); Address.sendValue(_fundRecipient, msg.value); for (uint256 index = 0; index < mintCount; index++) { _mintNFT(msg.sender, tokenIds[index]); } } /** * @dev giveaway tokenId to receiver. * Can only be called by the admin. */ function giveaway(address toAddress, uint256 tokenId) external override onlyAdmin { require(_giveawayCount < _maxGiveaway, "PKZ: Invalid giveaway"); require(tokenId <= _totalSupply, "PKZ: Invalid TokenId"); _giveawayCount++; _tokenCount++; _mint(toAddress, tokenId); emit Giveaway(toAddress, tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view 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()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../common/ERC2981.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment * information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC721Royalty is ERC2981, ERC721 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); _resetTokenRoyalty(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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: Unlicense pragma solidity ^0.8.12; import "@openzeppelin/contracts/access/IAccessControl.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol"; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; interface IPikoZooNFT is IAccessControl, IERC2981, IERC721, IERC721Metadata { event Giveaway(address toAddress, uint256 tokenId); function owner() external view returns (address); function transferOwnership(address newOwner) external; function totalSupply() external view returns (uint256); function giveawayCount() external view returns (uint256); function maxGiveaway() external view returns (uint256); function isVerifier(address verifier_) external view returns (bool); function setVerifier(address verifier_) external; function revokeVerifier(address verifier_) external; function setTokenURI(string memory tokenURI_) external; function setPreSaleRoot(bytes32 root_) external; function preSaleRoot() external view returns(bytes32); function setDefaultRoyalty(address receiver, uint96 feeNumerator) external; function setFundRecipient(address fundRecipient_) external; function fundRecipient() external view returns (address); function tokenCount() external view returns (uint256); function activate(uint256 totalSupply_, uint8 maxGiveaway_, address fundRecipient_, address royaltyRecipient_) external; function mint(uint256 tokenId, uint256 salt, bytes memory sig, bytes32[] memory proof) external payable; function mintBatch(uint256[] memory tokenIds, uint256 salt, bytes memory sig, bytes32[] memory proof) external payable; function giveaway(address toAddress, uint256 tokenId) external; } // SPDX-License-Identifier: MIT // 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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol) pragma solidity ^0.8.0; import "../../interfaces/IERC2981.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC2981 is IERC2981, ERC165 { struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Removes default royalty information. */ function _deleteDefaultRoyalty() internal virtual { delete _defaultRoyaltyInfo; } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../token/ERC721/extensions/IERC721Metadata.sol";
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); }
119,390
./full_match/1/0x4599E4F3Eea04BADD41501bF79183e67f6Cf569d/sources/contracts/HighTableVaultETH.sol
@inheritdoc IHighTableVaultETH
function closePositionAndClaimETH(address payable _receiver) external override returns (uint256 assets) { claimOwedShares(msg.sender); uint256 shares = balanceOf(msg.sender); closePosition(shares, msg.sender); assets = claimOwedAssetsETH(_receiver); }
17,149,121
./full_match/1/0x73b3B399c0067cDE7D04BB2F9087Faed8edD64ab/sources/contracts/EtherMonkeyLPPool.sol
ensure funds staked by users can't be transferred out
function withdrawReward() external onlyOwner { uint256 rewardSupply = rewardToken.balanceOf(address(this)); if (rewardToken == stakedToken) rewardSupply -= totalSupply; require(rewardToken.transfer(msg.sender, rewardSupply)); rewardRate = 0; periodFinish = uint64(block.timestamp); }
3,007,932
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./Uniswap.sol"; import "./interfaces/IUniMexFactory.sol"; import "./interfaces/IUniMexPool.sol"; import "./interfaces/ISwapPathCreator.sol"; import "./interfaces/IPositionAmountChecker.sol"; import "./interfaces/IUniMexStaking.sol"; contract UniMexMargin is Ownable, AccessControl, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint32; using SafeERC20 for IERC20; bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE"); address private immutable USDC_ADDRESS; IERC20 public immutable USDC; address public immutable WETH_ADDRESS; uint256 public constant MAG = 1e18; uint256 public constant LIQUIDATION_MARGIN = 1.1e18; //11% uint256 public thresholdGasPrice = 3e8; //gas price in wei used to calculate bonuses for liquidation, sl, tp uint32 public borrowInterestPercentScaled = 100; //10% uint256 public constant YEAR = 31536000; uint256 public positionNonce = 0; bool public paused = false; IPositionAmountChecker public positionAmountChecker; uint256 public amountThresholds; struct Position { uint256 owed; uint256 input; uint256 commitment; address token; bool isShort; uint32 startTimestamp; uint32 borrowInterest; address owner; uint32 stopLossPercent; uint32 takeProfitPercent; } struct Limit { uint256 amount; uint256 minimalSwapAmount; address token; bool isShort; uint32 validBefore; uint32 leverageScaled; address owner; uint32 takeProfitPercent; uint32 stopLossPercent; uint256 escrowAmount; } mapping(bytes32 => Position) public positionInfo; mapping(bytes32 => Limit) public limitOrders; mapping(address => uint256) public balanceOf; mapping(address => uint256) public escrow; IUniMexStaking public staking; IUniMexFactory public immutable unimex_factory; IUniswapV2Factory public immutable uniswap_factory; IUniswapV2Router02 public immutable uniswap_router; ISwapPathCreator public swapPathCreator; event OnClosePosition( bytes32 indexed positionId, address token, address indexed owner, uint256 owed, uint256 input, uint256 commitment, uint32 startTimestamp, bool isShort, uint256 borrowInterest, uint256 liquidationBonus, //amount that went to liquidator when position was liquidated. 0 if position was closed uint256 scaledCloseRate // busd/token multiplied by 1e18 ); event OnOpenPosition( address indexed sender, bytes32 positionId, bool isShort, address indexed token, uint256 scaledLeverage ); event OnAddCommitment( bytes32 indexed positionId, uint256 amount ); event OnLimitOrder( bytes32 indexed limitOrderId, address indexed owner, address token, uint256 amount, uint256 minimalSwapAmount, uint256 leverageScaled, uint32 validBefore, uint256 escrowAmount, uint32 takeProfitPercent, uint32 stopLossPercent, bool isShort ); event OnLimitOrderCancelled( bytes32 indexed limitOrderId ); event OnLimitOrderCompleted( bytes32 indexed limitOrderId, bytes32 positionId ); event OnTakeProfit( bytes32 indexed positionId, uint256 positionInput, uint256 swapAmount, address token, bool isShort ); event OnStopLoss( bytes32 indexed positionId, uint256 positionInput, uint256 swapAmount, address token, bool isShort ); //to prevent flashloans modifier isHuman() { require(msg.sender == tx.origin); _; } constructor( address _staking, address _factory, address _busd, address _weth, address _uniswap_factory, address _uniswap_router, address _swapPathCreator ) public { staking = IUniMexStaking(_staking); unimex_factory = IUniMexFactory(_factory); USDC_ADDRESS = _busd; USDC = IERC20(_busd); uniswap_factory = IUniswapV2Factory(_uniswap_factory); uniswap_router = IUniswapV2Router02(_uniswap_router); swapPathCreator = ISwapPathCreator(_swapPathCreator); WETH_ADDRESS = _weth; // Grant the contract deployer the default admin role: it will be able // to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); amountThresholds = 275; } function deposit(uint256 _amount) public { USDC.safeTransferFrom(msg.sender, address(this), _amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(_amount); } function withdraw(uint256 _amount) public { require(balanceOf[msg.sender] >= _amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount); USDC.safeTransfer(msg.sender, _amount); } function calculateBorrowInterest(bytes32 positionId) public view returns (uint256) { Position storage position = positionInfo[positionId]; uint256 loanTime = block.timestamp.sub(position.startTimestamp); return position.owed.mul(loanTime).mul(position.borrowInterest).div(1000).div(YEAR); } function openShortPosition(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, 0, 0]; _openPosition(msg.sender, token, true, values); } function openLongPosition(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, 0, 0]; _openPosition(msg.sender, token, false, values); } function openShortPositionWithSlTp(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount, uint256 takeProfitPercent, uint256 stopLossPercent) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, takeProfitPercent, stopLossPercent]; _openPosition(msg.sender, token, true, values); } function openLongPositionWithSlTp(address token, uint256 amount, uint256 scaledLeverage, uint256 minimalSwapAmount, uint256 takeProfitPercent, uint256 stopLossPercent) public isHuman { uint256[5] memory values = [amount, scaledLeverage, minimalSwapAmount, takeProfitPercent, stopLossPercent]; _openPosition(msg.sender, token, false, values); } /** * values[0] amount * values[1] scaledLeverage * values[2] minimalSwapAmount * values[3] takeProfitPercent * values[4] stopLossPercent */ function _openPosition(address owner, address token, bool isShort, uint256[5] memory values) private nonReentrant returns (bytes32) { require(!paused, "PAUSED"); require(values[0] > 0, "AMOUNT_ZERO"); require(values[4] < 1e6, "STOPLOSS EXCEEDS MAX"); address pool = unimex_factory.getPool(address(isShort ? IERC20(token) : USDC)); require(pool != address(0), "POOL_DOES_NOT_EXIST"); require(values[1] <= unimex_factory.getMaxLeverage(token).mul(MAG), "LEVERAGE_EXCEEDS_MAX"); if(address(positionAmountChecker) != address(0)) { (address baseToken, address quoteToken) = isShort ? (token, USDC_ADDRESS) : (USDC_ADDRESS, token); require(positionAmountChecker.checkPositionAmount(baseToken, quoteToken, values[0], values[1]), "NOT_ENOUGH_UNISWAP_LIQUIDITY"); } uint256 amountInBusd = isShort ? swapPathCreator.calculateConvertedValue(token, USDC_ADDRESS, values[0]) : values[0]; uint256 commitment = getCommitment(amountInBusd, values[1]); uint256 commitmentWithLb = commitment.add(calculateAutoCloseBonus()); require(balanceOf[owner] >= commitmentWithLb, "NO_BALANCE"); IUniMexPool(pool).borrow(values[0]); uint256 swap; { (address baseToken, address quoteToken) = isShort ? (token, USDC_ADDRESS) : (USDC_ADDRESS, token); swap = swapTokens(baseToken, quoteToken, values[0]); require(swap >= values[2], "INSUFFICIENT_SWAP"); } uint256 fees = (swap.mul(4)).div(1000); swap = swap.sub(fees); if(!isShort) { fees = swapTokens(token, USDC_ADDRESS, fees); // convert fees to ETH } transferFees(fees, pool); transferUserToEscrow(owner, owner, commitmentWithLb); positionNonce = positionNonce + 1; //possible overflow is ok bytes32 positionId = getPositionId( owner, token, values[0], values[1], positionNonce ); Position memory position = Position({ owed: values[0], input: swap, commitment: commitmentWithLb, token: token, isShort: isShort, startTimestamp: uint32(block.timestamp), owner: owner, borrowInterest: borrowInterestPercentScaled, takeProfitPercent: uint32(values[3]), stopLossPercent: uint32(values[4]) }); positionInfo[positionId] = position; emit OnOpenPosition(owner, positionId, isShort, token, values[1]); if(position.takeProfitPercent > 0) { emit OnTakeProfit(positionId, swap, position.takeProfitPercent, token, isShort); } if(position.stopLossPercent > 0) { emit OnStopLoss(positionId, swap, position.stopLossPercent, token, isShort); } return positionId; } /** * @dev add additional commitment to an opened position. The amount * must be initially approved * @param positionId id of the position to add commitment * @param amount the amount to add to commitment */ function addCommitmentToPosition(bytes32 positionId, uint256 amount) public { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); position.commitment = position.commitment.add(amount); USDC.safeTransferFrom(msg.sender, address(this), amount); escrow[position.owner] = escrow[position.owner].add(amount); emit OnAddCommitment(positionId, amount); } /** * @dev allows anyone to close position if it's loss exceeds threshold */ function setStopLoss(bytes32 positionId, uint32 percentAmount) public { require(percentAmount < 1e6, "STOPLOSS EXCEEDS MAX"); Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); require(msg.sender == position.owner, "NOT_OWNER"); position.stopLossPercent = percentAmount; emit OnStopLoss(positionId, position.input, percentAmount, position.token, position.isShort); } /** * @dev allows anyone to close position if it's profit exceeds threshold */ function setTakeProfit(bytes32 positionId, uint32 percentAmount) public { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); require(msg.sender == position.owner, "NOT_OWNER"); position.takeProfitPercent = percentAmount; emit OnTakeProfit(positionId, position.input, percentAmount, position.token, position.isShort); } function autoClose(bytes32 positionId) public isHuman { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); //check constraints (address baseToken, address quoteToken) = position.isShort ? (USDC_ADDRESS, position.token) : (position.token, USDC_ADDRESS); uint256 swapAmount = swapPathCreator.calculateConvertedValue(baseToken, quoteToken, position.input); uint256 hundredPercent = 1e6; require((position.takeProfitPercent != 0 && position.owed.mul(hundredPercent.add(position.takeProfitPercent)).div(hundredPercent) <= swapAmount) || (position.stopLossPercent != 0 && position.owed.mul(hundredPercent.sub(position.stopLossPercent)).div(hundredPercent) >= swapAmount), "SL_OR_TP_UNAVAILABLE"); //withdraw bonus from position commitment uint256 closeBonus = calculateAutoCloseBonus(); position.commitment = position.commitment.sub(closeBonus); USDC.safeTransfer(msg.sender, closeBonus); transferEscrowToUser(position.owner, address(0), closeBonus); _closePosition(positionId, position, 0); } function calculateAutoOpenBonus() public view returns(uint256) { return thresholdGasPrice.mul(510000); } function calculateAutoCloseBonus() public view returns(uint256) { return thresholdGasPrice.mul(270000); } /** * @dev opens position that can be opened at a specific price */ function openLimitOrder(address token, bool isShort, uint256 amount, uint256 minimalSwapAmount, uint256 leverageScaled, uint32 validBefore, uint32 takeProfitPercent, uint32 stopLossPercent) public { require(!paused, "PAUSED"); require(stopLossPercent < 1e6, "STOPLOSS EXCEEDS MAX"); require(validBefore > block.timestamp, "INCORRECT_EXP_DATE"); uint256[3] memory values256 = [amount, minimalSwapAmount, leverageScaled]; uint32[3] memory values32 = [validBefore, takeProfitPercent, stopLossPercent]; _openLimitOrder(token, isShort, values256, values32); } /** * @dev values256[0] - amount * values256[1] - minimal swap amount * values256[2] - scaled leverage * values32[0] - valid before * values32[1] - take profit percent * values32[2] - stop loss percent */ function _openLimitOrder(address token, bool isShort, uint256[3] memory values256, uint32[3] memory values) private { uint256 escrowAmount; //stack depth optimization { uint256 commitment = isShort ? getCommitment(values256[1], values256[2]) : getCommitment(values256[0], values256[2]); escrowAmount = commitment.add(calculateAutoOpenBonus()).add(calculateAutoCloseBonus()); require(balanceOf[msg.sender] >= escrowAmount, "INSUFFICIENT_BALANCE"); transferUserToEscrow(msg.sender, msg.sender, escrowAmount); } bytes32 limitOrderId = _getLimitOrderId(token, values256[0], values256[1], values256[2], values[0], msg.sender, isShort); Limit memory limitOrder = Limit({ token: token, amount: values256[0], minimalSwapAmount: values256[1], leverageScaled: uint32(values256[2].div(1e14)), validBefore: values[0], owner: msg.sender, escrowAmount: escrowAmount, isShort: isShort, takeProfitPercent: values[1], stopLossPercent: values[2] }); limitOrders[limitOrderId] = limitOrder; emitLimitOrderEvent(limitOrderId, token, values256, values, escrowAmount, isShort); } function emitLimitOrderEvent(bytes32 limitOrderId, address token, uint256[3] memory values256, uint32[3] memory values, uint256 escrowAmount, bool isShort) private { emit OnLimitOrder(limitOrderId, msg.sender, token, values256[0], values256[1], values256[2], values[0], escrowAmount, values[1], values[2], isShort); } function cancelLimitOrder(bytes32 limitOrderId) public { Limit storage limitOrder = limitOrders[limitOrderId]; require(limitOrder.owner == msg.sender, "NOT_OWNER"); transferEscrowToUser(limitOrder.owner, limitOrder.owner, limitOrder.escrowAmount); delete limitOrders[limitOrderId]; emit OnLimitOrderCancelled(limitOrderId); } function autoOpen(bytes32 limitOrderId) public isHuman { //get limit order Limit storage limitOrder = limitOrders[limitOrderId]; require(limitOrder.owner != address(0), "NO_ORDER"); require(limitOrder.validBefore >= uint32(block.timestamp), "EXPIRED"); //check open rate (address baseToken, address quoteToken) = limitOrder.isShort ? (limitOrder.token, USDC_ADDRESS) : (USDC_ADDRESS, limitOrder.token); uint256 swapAmount = swapPathCreator.calculateConvertedValue(baseToken, quoteToken, limitOrder.amount); require(swapAmount >= limitOrder.minimalSwapAmount, "LIMIT_NOT_SATISFIED"); uint256 openBonus = calculateAutoOpenBonus(); //transfer bonus from escrow to caller USDC.transfer(msg.sender, openBonus); transferEscrowToUser(limitOrder.owner, limitOrder.owner, limitOrder.escrowAmount.sub(openBonus)); transferEscrowToUser(limitOrder.owner, address(0), openBonus); //open position for user uint256[5] memory values = [limitOrder.amount, uint256(limitOrder.leverageScaled.mul(1e14)), limitOrder.minimalSwapAmount, uint256(limitOrder.takeProfitPercent), uint256(limitOrder.stopLossPercent)]; bytes32 positionId = _openPosition(limitOrder.owner, limitOrder.token, limitOrder.isShort, values); //delete order id delete limitOrders[limitOrderId]; emit OnLimitOrderCompleted(limitOrderId, positionId); } function _getLimitOrderId(address token, uint256 amount, uint256 minSwapAmount, uint256 scaledLeverage, uint256 validBefore, address owner, bool isShort) private pure returns (bytes32) { return keccak256(abi.encodePacked(token, amount, minSwapAmount, scaledLeverage, validBefore, owner, isShort)); } function _checkPositionIsOpen(Position storage position) private view { require(position.owner != address(0), "NO_OPEN_POSITION"); } function closePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); require(msg.sender == position.owner, "BORROWER_ONLY"); _closePosition(positionId, position, minimalSwapAmount); } function _closePosition(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private nonReentrant{ uint256 scaledRate; if(position.isShort) { scaledRate = _closeShort(positionId, position, minimalSwapAmount); }else{ scaledRate = _closeLong(positionId, position, minimalSwapAmount); } deletePosition(positionId, position, 0, scaledRate); } function _closeShort(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private returns (uint256){ uint256 input = position.input; uint256 owed = position.owed; uint256 commitment = position.commitment; address pool = unimex_factory.getPool(position.token); uint256 poolInterestInTokens = calculateBorrowInterest(positionId); uint256 swap = swapTokens(USDC_ADDRESS, position.token, input); require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP"); uint256 scaledRate = calculateScaledRate(input, swap); require(swap >= owed.add(poolInterestInTokens).mul(input).div(input.add(commitment)), "LIQUIDATE_ONLY"); bool isProfit = owed < swap; uint256 amount; uint256 fees = poolInterestInTokens > 0 ? swapPathCreator.calculateConvertedValue(position.token, address(USDC), poolInterestInTokens) : 0; if(isProfit) { uint256 profitInTokens = swap.sub(owed); amount = swapTokens(position.token, USDC_ADDRESS, profitInTokens); //profit in eth } else { uint256 commitmentInTokens = swapTokens(USDC_ADDRESS, position.token, commitment); uint256 remainder = owed.sub(swap); require(commitmentInTokens >= remainder, "LIQUIDATE_ONLY"); amount = swapTokens(position.token, USDC_ADDRESS, commitmentInTokens.sub(remainder)); //return to user's balance } if(isProfit) { if(amount >= fees) { transferEscrowToUser(position.owner, position.owner, commitment); transferToUser(position.owner, amount.sub(fees)); } else { uint256 remainder = fees.sub(amount); transferEscrowToUser(position.owner, position.owner, commitment.sub(remainder)); transferEscrowToUser(position.owner, address(0), remainder); } } else { require(amount >= fees, "LIQUIDATE_ONLY"); //safety check transferEscrowToUser(position.owner, address(0x0), commitment); transferToUser(position.owner, amount.sub(fees)); } transferFees(fees, pool); transferToPool(pool, position.token, owed); return scaledRate; } function _closeLong(bytes32 positionId, Position storage position, uint256 minimalSwapAmount) private returns (uint256){ uint256 input = position.input; uint256 owed = position.owed; address pool = unimex_factory.getPool(USDC_ADDRESS); uint256 fees = calculateBorrowInterest(positionId); uint256 swap = swapTokens(position.token, USDC_ADDRESS, input); require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP"); uint256 scaledRate = calculateScaledRate(swap, input); require(swap.add(position.commitment) >= owed.add(fees), "LIQUIDATE_ONLY"); uint256 commitment = position.commitment; bool isProfit = swap >= owed; uint256 amount = isProfit ? swap.sub(owed) : commitment.sub(owed.sub(swap)); transferToPool(pool, USDC_ADDRESS, owed); transferFees(fees, pool); transferEscrowToUser(position.owner, isProfit ? position.owner : address(0x0), commitment); transferToUser(position.owner, amount.sub(fees)); return scaledRate; } /** * @dev helper function, indicates when a position can be liquidated. * Liquidation threshold is when position input plus commitment can be converted to 110% of owed tokens */ function canLiquidate(bytes32 positionId) public view returns(bool) { Position storage position = positionInfo[positionId]; uint256 liquidationBonus = calculateAutoCloseBonus(); uint256 canReturn; if(position.isShort) { uint256 positionBalance = position.input.add(position.commitment); uint256 valueToConvert = positionBalance < liquidationBonus ? 0 : positionBalance.sub(liquidationBonus); canReturn = swapPathCreator.calculateConvertedValue(USDC_ADDRESS, position.token, valueToConvert); } else { uint256 canReturnOverall = swapPathCreator.calculateConvertedValue(position.token, USDC_ADDRESS, position.input) .add(position.commitment); canReturn = canReturnOverall < liquidationBonus ? 0 : canReturnOverall.sub(liquidationBonus); } uint256 poolInterest = calculateBorrowInterest(positionId); return canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG); } /** * @dev Liquidates position and sends a liquidation bonus from user's commitment to a caller. * can only be called from account that has the LIQUIDATOR role */ function liquidatePosition(bytes32 positionId, uint256 minimalSwapAmount) external isHuman nonReentrant { Position storage position = positionInfo[positionId]; _checkPositionIsOpen(position); uint256 canReturn; uint256 poolInterest = calculateBorrowInterest(positionId); uint256 liquidationBonus = calculateAutoCloseBonus(); uint256 liquidatorBonus; uint256 scaledRate; if(position.isShort) { uint256 positionBalance = position.input.add(position.commitment); uint256 valueToConvert; (valueToConvert, liquidatorBonus) = _safeSubtract(positionBalance, liquidationBonus); canReturn = swapTokens(USDC_ADDRESS, position.token, valueToConvert); require(canReturn >= minimalSwapAmount, "INSUFFICIENT_SWAP"); scaledRate = calculateScaledRate(valueToConvert, canReturn); } else { uint256 swap = swapTokens(position.token, USDC_ADDRESS, position.input); require(swap >= minimalSwapAmount, "INSUFFICIENT_SWAP"); scaledRate = calculateScaledRate(swap, position.input); uint256 canReturnOverall = swap.add(position.commitment); (canReturn, liquidatorBonus) = _safeSubtract(canReturnOverall, liquidationBonus); } require(canReturn < position.owed.add(poolInterest).mul(LIQUIDATION_MARGIN).div(MAG), "CANNOT_LIQUIDATE"); _liquidate(position, canReturn, poolInterest); transferEscrowToUser(position.owner, address(0x0), position.commitment); USDC.safeTransfer(msg.sender, liquidatorBonus); deletePosition(positionId, position, liquidatorBonus, scaledRate); } function _liquidate(Position memory position, uint256 canReturn, uint256 fees) private { address baseToken = position.isShort ? position.token : USDC_ADDRESS; address pool = unimex_factory.getPool(baseToken); if(canReturn > position.owed) { transferToPool(pool, baseToken, position.owed); uint256 remainder = canReturn.sub(position.owed); if(remainder > fees) { //can pay fees completely if(position.isShort) { remainder = swapTokens(position.token, USDC_ADDRESS, remainder); if(fees > 0) { //with fees == 0 calculation is reverted with "UV2: insufficient input amount" fees = swapPathCreator.calculateConvertedValue(position.token, USDC_ADDRESS, fees); if(fees > remainder) { //safety check fees = remainder; } } } transferFees(fees, pool); transferToUser(position.owner, remainder.sub(fees)); } else { //all is left is for fees if(position.isShort) { //convert remainder to busd remainder = swapTokens(position.token, USDC_ADDRESS, canReturn.sub(position.owed)); } transferFees(remainder, pool); } } else { //return to pool all that's left uint256 correction = position.owed.sub(canReturn); IUniMexPool(pool).distributeCorrection(correction); transferToPool(pool, baseToken, canReturn); } } function setStaking(address _staking) external onlyOwner { require(_staking != address(0)); staking = IUniMexStaking(_staking); } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { paused = true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { paused = false; } function setThresholdGasPrice(uint256 gasPrice) public { require(hasRole(LIQUIDATOR_ROLE, msg.sender), "NOT_LIQUIDATOR"); thresholdGasPrice = gasPrice; } /** * @dev set interest rate for tokens owed from pools. Scaled to 10 (e.g. 150 is 15%) */ function setBorrowPercent(uint32 _newPercentScaled) external onlyOwner { borrowInterestPercentScaled = _newPercentScaled; } function calculateScaledRate(uint256 busdAmount, uint256 tokenAmount) private pure returns (uint256 scaledRate) { if(tokenAmount == 0) { return 0; } return busdAmount.mul(MAG).div(tokenAmount); } function transferUserToEscrow(address from, address to, uint256 amount) private { require(balanceOf[from] >= amount); balanceOf[from] = balanceOf[from].sub(amount); escrow[to] = escrow[to].add(amount); } function transferEscrowToUser(address from, address to, uint256 amount) private { require(escrow[from] >= amount); escrow[from] = escrow[from].sub(amount); balanceOf[to] = balanceOf[to].add(amount); } function transferToUser(address to, uint256 amount) private { balanceOf[to] = balanceOf[to].add(amount); } function getPositionId( address maker, address token, uint256 amount, uint256 leverage, uint256 nonce ) private pure returns (bytes32 positionId) { //date acts as a nonce positionId = keccak256( abi.encodePacked(maker, token, amount, leverage, nonce) ); } function swapTokens(address baseToken, address quoteToken, uint256 input) private returns (uint256 swap) { if(input == 0) { return 0; } IERC20(baseToken).approve(address(uniswap_router), input); address[] memory path = swapPathCreator.getPath(baseToken, quoteToken); uint256 balanceBefore = IERC20(quoteToken).balanceOf(address(this)); IUniswapV2Router02(uniswap_router).swapExactTokensForTokensSupportingFeeOnTransferTokens( input, 0, //checks are done after swap in caller functions path, address(this), block.timestamp ); uint256 balanceAfter = IERC20(quoteToken).balanceOf(address(this)); swap = balanceAfter.sub(balanceBefore); } function getCommitment(uint256 _amount, uint256 scaledLeverage) private pure returns (uint256 commitment) { commitment = (_amount.mul(MAG)).div(scaledLeverage); } function transferFees(uint256 busdFees, address pool) private { uint256 fees = swapTokens(USDC_ADDRESS, WETH_ADDRESS, busdFees); // convert fees to ETH uint256 halfFees = fees.div(2); // Pool fees IERC20(WETH_ADDRESS).approve(pool, halfFees); IUniMexPool(pool).distribute(halfFees); // Staking Fees IERC20(WETH_ADDRESS).approve(address(staking), fees.sub(halfFees)); staking.distribute(fees.sub(halfFees)); } function transferToPool(address pool, address token, uint256 amount) private { IERC20(token).approve(pool, amount); IUniMexPool(pool).repay(amount); } function _safeSubtract(uint256 from, uint256 amount) private pure returns (uint256 remainder, uint256 subtractedAmount) { if(from < amount) { remainder = 0; subtractedAmount = from; } else { remainder = from.sub(amount); subtractedAmount = amount; } } function setAmountThresholds(uint32 leverage5) public onlyOwner { amountThresholds = leverage5; } function deletePosition(bytes32 positionId, Position storage position, uint256 liquidatedAmount, uint256 scaledRate) private { emit OnClosePosition( positionId, position.token, position.owner, position.owed, position.input, position.commitment, position.startTimestamp, position.isShort, position.borrowInterest, liquidatedAmount, scaledRate ); delete positionInfo[positionId]; } function setSwapPathCreator(address newAddress) external onlyOwner { require(newAddress != address(0), "ZERO ADDRESS"); swapPathCreator = ISwapPathCreator(newAddress); } function setPositionAmountChecker(address checker) external onlyOwner { positionAmountChecker = IPositionAmountChecker(checker); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, 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()); } } } // 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.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; interface IUniswapV2Pair { function getReserves() external view returns (uint112 r0, uint112 r1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } interface IUniswapV2Factory { function getPair(address a, address b) external view returns (address p); } interface IUniswapV2Router02 { function WETH() external returns (address); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } library UniswapV2Library { 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, 'UV2: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UV2: ZERO_ADDRESS'); } // 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, 'UV2: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UV2: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); // pair = address(uint(keccak256(abi.encodePacked( // hex'ff', // factory, // keccak256(abi.encodePacked(token0, token1)), // hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash // )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // 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); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface IUniMexFactory { function getPool(address) external returns(address); function getMaxLeverage(address) external returns(uint256); function allowedMargins(address) external returns (bool); function utilizationScaled(address token) external pure returns(uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface IUniMexPool { function borrow(uint256 _amount) external; function distribute(uint256 _amount) external; function distributeCorrections(uint256 _amount) external; function repay(uint256 _amount) external returns (bool); function distributeCorrection(uint256 _amount) external returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface ISwapPathCreator { function getPath(address baseToken, address quoteToken) external view returns (address[] memory); function calculateConvertedValue(address baseToken, address quoteToken, uint256 amount) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface IPositionAmountChecker { function checkPositionAmount(address baseToken, address quoteToken, uint256 amount, uint256 leverageScaled) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface IUniMexStaking { function distribute(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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 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; } }
called by the owner to unpause, returns to normal state/
function unpause() onlyOwner public { paused = false; }
1,373,297
pragma solidity 0.4.24; pragma experimental ABIEncoderV2; //Truffle Imports import "@chainlink/contracts/src/v0.4/ChainlinkClient.sol"; import "@chainlink/contracts/src/v0.4/vendor/Ownable.sol"; import "@chainlink/contracts/src/v0.4/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.4/interfaces/AggregatorV3Interface.sol"; import "./strings.sol"; //Remix Imports //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/ChainlinkClient.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/vendor/Ownable.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/LinkTokenInterface.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.4/interfaces/AggregatorV3Interface.sol"; //import "github.com/Arachnid/solidity-stringutils/strings.sol"; contract RentalAgreementFactory { using SafeMath_Chainlink for uint; address private dappWallet = msg.sender; enum RentalAgreementStatus {PROPOSED, APPROVED, REJECTED, ACTIVE, COMPLETED, ENDED_ERROR} bytes32 JOB_ID = "534ea675a9524e8e834585b00368b178"; address private constant LINK_KOVAN = 0xa36085F69e2889c224210F603D836748e7dC0088; address private constant ORACLE_CONTRACT = 0x05c8fadf1798437c143683e665800d58a42b6e19; address private constant NODE_ADDRESS = 0xDC92b2B1C731d07dC9bd8D30D0B1A69F266f2A8A; uint256 constant private ORACLE_PAYMENT = 0.1 * 1 ether; address private constant ETH_USD_CONTRACT = 0x9326BFA02ADD2366b30bacB125260Af641031331; address private constant AUD_USD_CONTRACT = 0x5813A90f826e16dB392abd2aF7966313fc1fd5B8; address private constant GBP_USD_CONTRACT = 0x28b0061f44E6A9780224AA61BEc8C3Fcb0d37de9; enum VehicleModels { Model_S, Model_3, Model_X, Model_Y, Cybertruck, Roadster} enum VehicleStatus {PENDING, APPROVED} enum Currency { ETH, USD, GBP, AUD } struct Vehicle { uint vehicleId; address ownerAddress; uint baseHireFee; uint bondRequired; Currency ownerCurrency; VehicleModels vehicleModel; string vehiclePlate; int vehicleLongitude; int vehicleLatitude; VehicleStatus status; } address[] internal keyList; AggregatorV3Interface internal ethUsdPriceFeed; AggregatorV3Interface internal audUsdPriceFeed; AggregatorV3Interface internal gbpUsdPriceFeed; mapping (address => Vehicle) vehicles; RentalAgreement[] rentalAgreements; constructor() public payable { //newVehicle(0x54a47c5e6a6CEc35eEB23E24C6b3659eE205eE35,123, 0.001 ether,0.01 ether,Currency.ETH,VehicleModels.Model_S,'REVOLT',-35008518,138575206); //newVehicle(0x20442A67128F4a2d9eb123e353893c8f05429AcB,567, 0.01 * 0.01 ether,0.01 ether,Currency.ETH,VehicleModels.Model_X,'LINKCAR',-35028518,138525206); //approveVehicle(0x54a47c5e6a6CEc35eEB23E24C6b3659eE205eE35); ethUsdPriceFeed = AggregatorV3Interface(ETH_USD_CONTRACT); audUsdPriceFeed = AggregatorV3Interface(AUD_USD_CONTRACT); gbpUsdPriceFeed = AggregatorV3Interface(GBP_USD_CONTRACT); } modifier onlyOwner() { require(dappWallet == msg.sender,'Only Insurance provider can do this'); _; } modifier onlyNode() { require(NODE_ADDRESS == msg.sender,'Only Node can call this function'); _; } event rentalAgreementCreated(address _newAgreement, uint _totalFundsHeld); event vehicleAdded( uint _vehicleId, address _vehicleOwner, uint _baseHireFee, uint _bondRequired, Currency _ownerCurrency, VehicleModels _vehicleModel, string _vehiclePlate, int _vehicleLongitude, int _vehicleLatitude); function getLatestEthUsdPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = ethUsdPriceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } function getLatestAudUsdPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = audUsdPriceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } function getLatestGbpUsdPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = gbpUsdPriceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } function convertEthToFiat(uint _value, Currency _toCurrency) public view returns (uint) { if (_toCurrency == Currency.ETH) { return _value; } int ethUsdPrice = getLatestEthUsdPrice(); uint inUsd = (_value * uint(ethUsdPrice)) / 1 ether; if (_toCurrency == Currency.USD) { return inUsd; } else if (_toCurrency == Currency.GBP) { int gbpUsdPrice = getLatestGbpUsdPrice(); return inUsd * (10 ** 8) / uint(gbpUsdPrice); } else if (_toCurrency == Currency.AUD) { int audUsdPrice = getLatestAudUsdPrice(); return inUsd * (10 ** 8) / uint(audUsdPrice); } return _value; } function convertFiatToEth(uint _value, Currency _fromCurrency) public view returns (uint) { if (_fromCurrency == Currency.ETH) { return _value; } int ethUsdPrice = getLatestEthUsdPrice(); uint fromUsd = (_value * 1 ether / uint(ethUsdPrice)); if (_fromCurrency == Currency.USD) { return fromUsd; } else if (_fromCurrency == Currency.GBP) { int gbpUsdPrice = getLatestGbpUsdPrice(); return fromUsd * uint(gbpUsdPrice) / (10 ** 8); } else if (_fromCurrency == Currency.AUD) { int audUsdPrice = getLatestAudUsdPrice(); return fromUsd * uint(audUsdPrice) / (10 ** 8); } return _value; } /** * @dev Create a new Rental Agreement. Once it's created, all logic & flow is handled from within the RentalAgreement Contract */ function newRentalAgreement(address _vehicleOwner, address _renter, uint _startDateTime, uint _endDateTime) public payable returns(address) { //vehicle owner must be different to renter require (_vehicleOwner != _renter,'Owner & Renter must be different'); //start date must be < end date and must be at least 1 hour (3600 seconds) require (_endDateTime >= _startDateTime.add(3600),'Vehicle Agreement must be for a minimum of 1 hour'); //specify agreement must be for a discrete number of hours to keep it simple require((_endDateTime - _startDateTime) % 3600 == 0,'Vehicle Agreement must be for a discrete number of hours'); //vehicle to be rented must be in APPROVED status require (vehicles[_vehicleOwner].status == VehicleStatus.APPROVED,'Vehicle is not approved'); //ensure start date is now or in the future //require (_startDateTime >= now,'Vehicle Agreement cannot be in the past'); // Ensure correct amount of ETH has been sent for total rent cost & bond uint convertedMsgValue = convertEthToFiat(msg.value, vehicles[_vehicleOwner].ownerCurrency); uint totalRentCost = vehicles[_vehicleOwner].baseHireFee * ((_endDateTime - _startDateTime) / 3600); uint bondRequired = vehicles[_vehicleOwner].bondRequired; //add 1% tolerance to account for rounding & fluctuations in case a round just ended in price feed require (convertedMsgValue.add(convertedMsgValue.div(100)) >= totalRentCost.add(bondRequired),'Insufficient rent & bond paid'); // Now that we've determined the ETH passed in is correct, we need to calculate bond + fee values in ETH to send to contract uint bondRequiredETH = convertFiatToEth(bondRequired, vehicles[_vehicleOwner].ownerCurrency); // Fee value is total value minus bond. We've already validated enough ETH has been sent uint totalRentCostETH = msg.value - bondRequiredETH; //create new Rental Agreement RentalAgreement a = (new RentalAgreement).value(totalRentCostETH.add(bondRequiredETH))(_vehicleOwner, _renter, _startDateTime, _endDateTime, totalRentCostETH, bondRequiredETH,LINK_KOVAN, ORACLE_CONTRACT, ORACLE_PAYMENT, JOB_ID); //store new agreement in array of agreements rentalAgreements.push(a); emit rentalAgreementCreated(address(a), msg.value); //now that contract has been created, we need to fund it with enough LINK tokens to fulfil 1 Oracle request per day LinkTokenInterface link = LinkTokenInterface(a.getChainlinkToken()); link.transfer(address(a), 1 ether); return address(a); } /** * @dev Create a new Vehicle. */ function newVehicle(address _vehicleOwner, uint _vehicleId, uint _baseHireFee, uint _bondRequired, Currency _ownerCurrency, VehicleModels _vehicleModel, string _vehiclePlate, int _vehicleLongitude, int _vehicleLatitude) public { //adds a vehicle and stores it in the vehicles mapping. Each vehicle is represented by 1 Ethereum address var v = vehicles[_vehicleOwner]; v.vehicleId = _vehicleId; v.ownerAddress = _vehicleOwner; v.baseHireFee = _baseHireFee; v.bondRequired = _bondRequired; v.ownerCurrency = _ownerCurrency; v.vehicleModel = _vehicleModel; v.vehiclePlate = _vehiclePlate; v.vehicleLongitude = _vehicleLongitude; v.vehicleLatitude = _vehicleLatitude; v.status = VehicleStatus.PENDING; emit vehicleAdded(_vehicleId, _vehicleOwner, _baseHireFee, _bondRequired, _ownerCurrency, _vehicleModel, _vehiclePlate, _vehicleLongitude, _vehicleLatitude); } /** * @dev Approves a vehicle for use in the app. Only a Chainlink node can call this, as it knows if the test to the tesla servers was * successful or not */ function approveVehicle(address _walletOwner) public onlyNode() { vehicles[_walletOwner].status = VehicleStatus.APPROVED; //store the key in an array where we can loop through. At this point the vehicle will be returned in searched keyList.push(_walletOwner); } /** * @dev Return a particular Vehicle struct based on a wallet address */ function getVehicle(address _walletOwner) external view returns (Vehicle) { return vehicles[_walletOwner]; } /** * @dev Return all rental contract addresses */ function getRentalContracts() external view returns (RentalAgreement[] ) { return rentalAgreements; } /** * @dev Return a particular Rental Contract based on a rental contract address */ function getRentalContract(address _rentalContract) external view returns (address,address,uint,uint,uint,uint,RentalAgreementStatus ) { //loop through list of contracts, and find any belonging to the address for (uint i = 0; i < rentalAgreements.length; i++) { if (address(rentalAgreements[i]) == _rentalContract) { return rentalAgreements[i].getAgreementDetails(); } } } /** * @dev Return a list of rental contract addresses belonging to a particular vehicle owner or renter * ownerRenter = 0 means vehicle owner, 1 = vehicle renter */ function getRentalContracts(uint _owner, address _address) external view returns (address[] ) { //loop through list of contracts, and find any belonging to the address & type (renter or vehicle owner) //_owner variable determines if were searching for agreements for the owner or renter //0 = renter & 1 = owner uint finalResultCount = 0; //because we need to know exact size of final memory array, first we need to iterate and count how many will be in the final result for (uint i = 0; i < rentalAgreements.length; i++) { if (_owner == 1) { //owner scenario if (rentalAgreements[i].getVehicleOwner() == _address) { finalResultCount = finalResultCount + 1; } } else { //renter scenario if (rentalAgreements[i].getVehicleRenter() == _address) { finalResultCount = finalResultCount + 1; } } } //now we have the total count, we can create a memory array with the right size and then populate it address[] memory addresses = new address[](finalResultCount); uint addrCountInserted = 0; for (uint j = 0; j < rentalAgreements.length; j++) { if (_owner == 1) { //owner scenario if (rentalAgreements[j].getVehicleOwner() == _address) { addresses[addrCountInserted] = address(rentalAgreements[j]); addrCountInserted = addrCountInserted + 1; } } else { //renter scenario if (rentalAgreements[j].getVehicleRenter() == _address) { addresses[addrCountInserted] = address(rentalAgreements[j]); addrCountInserted = addrCountInserted + 1; } } } return addresses; } /** * @dev Function that takes a vehicle ID/address, start & end epochs and then searches through to see if * vehicle is available during those dates or not */ function checkVehicleAvailable(address _vehicleAddress, uint _start, uint _end) public view returns (uint) { //algorithm works as follows: //vehicle needs to be in approved status otherwise return false //loop through all rental agreemets //for each agreement, check if its our vehicle //if its our vehicle, check if agreement is approved or active (proposed & completed/error not included) //and if its approved or active, check if overlap: overlap = param.start < contract.end && contract.start < param.end; //if overlap, return 0 //else return 1 if (vehicles[_vehicleAddress].status == VehicleStatus.APPROVED) { for (uint i = 0; i < rentalAgreements.length; i++) { if (rentalAgreements[i].getVehicleOwner() == _vehicleAddress){ if (rentalAgreements[i].getAgreementStatus() == RentalAgreementFactory.RentalAgreementStatus.APPROVED || rentalAgreements[i].getAgreementStatus() == RentalAgreementFactory.RentalAgreementStatus.ACTIVE) { //check for overlap if ( _start < rentalAgreements[i].getAgreementEndTime() && rentalAgreements[i].getAgreementStartTime() < _end) { //overlap found, return 0 return 0; } } } } } else { //vehicle not approved, return false return 0; } //no clashes found, we can return success return 1; } /** * @dev Function that takes a start & end epochs and then returns all vehicle addresses that are available */ function returnAvailableVehicles(uint _start, uint _end) public view returns (address[]) { //algorithm works as follows: loop through all rental agreemets //for each agreement, check if its our vehicle //if its our vehicle, check if agreement is approved or active (proposed & completed/error not included) //and if its approved or active, check if overlap: overlap = param.start < contract.end && contract.start < param.end; //if overlap, return 0 //else return 1 uint finalResultCount = 0; //because we need to know exact size of final memory array, first we need to iterate and count how many will be in the final result for (uint i = 0; i < keyList.length; i++) { //call function above for each key found if (checkVehicleAvailable(keyList[i], _start, _end) > 0){ //vehicle is available, add to final result count finalResultCount = finalResultCount+ 1; } } //now we have the total count, we can create a memory array with the right size and then populate it address[] memory addresses = new address[](finalResultCount); uint addrCountInserted = 0; for (uint j = 0; j < keyList.length; j++) { //call function above for each key found if (checkVehicleAvailable(keyList[j], _start, _end) > 0){ //vehicle is available, add to list addresses[addrCountInserted] = keyList[j]; } addrCountInserted = addrCountInserted + 1; } return addresses; } /** * @dev Return a list of all vehicle addresses */ function getVehicleAddresses() public view returns (address[]) { return keyList; } /** * @dev Return a vehicle ID for a given vehicle address */ function getVehicleId(address _vehicleAddress) public view returns (uint) { return vehicles[_vehicleAddress].vehicleId; } /** * @dev Function to end provider contract, in case of bugs or needing to update logic etc, funds are returned to dapp owner, including any remaining LINK tokens */ function endContractProvider() external payable onlyOwner() { LinkTokenInterface link = LinkTokenInterface(LINK_KOVAN); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); selfdestruct(dappWallet); } /** * @dev fallback function, to receive ether */ function() external payable { } } contract RentalAgreement is ChainlinkClient, Ownable { using SafeMath_Chainlink for uint; using SafeMath_Chainlink for int; using strings for *; enum RentalAgreementStatus {PROPOSED, APPROVED, REJECTED, ACTIVE, COMPLETED, ENDED_ERROR} int constant private LOCATION_BUFFER = 10000; //Buffer for how far from start position end position can be without incurring fine. 10000 = 1m uint256 constant private ODOMETER_BUFFER = 5; //Buffer for how many miles past agreed total miles allowed without incurring fine uint256 constant private CHARGE_BUFFER = 0; //Buffer for how much % of TOTAL CHARGE allowed without incurring fine. 0 means vehicle must be fully charged uint256 constant private TIME_BUFFER = 10800; //Buffer for how many seconds past agreed end time can the renter end the contrat without incurring a penalty uint256 constant private LOCATION_FINE = 1; //What percentage of bond goes to vehicle owner if vehicle isn't returned at the correct location + buffer, per km uint256 constant private ODOMETER_FINE = 1; //What percentage of bond goes to vehicle owner if vehicle incurs more than allowed miles + buffer, per mile uint256 constant private CHARGE_FINE = 1; //What percentage of bond goes to vehicle owner if vehicle isn't charged at the expected level + buffer uint256 constant private TIME_FINE = 1; //What percentage of bond goes to vehicle owner if contract ends past the agreed end date/time + buffer, per hour uint256 constant private PLATFORM_FEE = 1; //What percentage of the base fee goes to the Platform. To be used to fund data requests etc uint256 private oraclePaymentAmount; bytes32 private jobId; address private dappWallet = msg.sender; address private vehicleOwner; address private renter; uint private startDateTime; uint private endDateTime; uint private totalRentCost; uint private totalBond; RentalAgreementFactory.RentalAgreementStatus private agreementStatus; uint private startOdometer = 0; uint private startChargeState = 0; int private startVehicleLongitude = 0; int private startVehicleLatitude = 0; uint private endOdometer = 0; int private endVehicleLongitude = 0; int private endVehicleLatitude = 0; uint private rentalAgreementEndDateTime = 0; uint private endChargeState = 0; //variables for calulating final fee payable uint private totalMiles = 0; uint private secsPastEndDate = 0; int private longitudeDifference = 0; int private latitudeDifference = 0; uint private totalLocationPenalty = 0; uint private totalOdometerPenalty = 0; uint private totalChargePenalty = 0; uint private totalTimePenalty = 0; uint private totalPlatformFee = 0; uint private totalRentPayable = 0; uint private totalBondReturned = 0; uint private bondForfeited = 0; //List of events event rentalAgreementCreated(address vehicleOwner, address renter,uint startDateTime,uint endDateTime,uint totalRentCost, uint totalBond); event contractActive(uint _startOdometer, uint _startChargeState, int _startVehicleLongitude, int _startVehicleLatitude); event contractCompleted(uint _endOdometer, uint _endChargeState, int _endVehicleLongitude, int _endVehicleLatitide); event contractCompletedError(uint _endOdometer, uint _endChargeState, int _endVehicleLongitude, int _endVehicleLatitide); event agreementPayments(uint _platformFee, uint _totalRent, uint _totalBondKept, uint _totalBondForfeitted, uint _timePenality, uint _chargePenalty, uint _locationPenalty, uint _milesPenalty); /** * @dev Modifier to check if the dapp wallet is calling the transaction */ modifier onlyDapp() { require(dappWallet == msg.sender,'Only Link-My-Ride Web App can perform this step'); _; } /** * @dev Modifier to check if the vehicle owner is calling the transaction */ modifier onlyVehicleOwner() { require(vehicleOwner == msg.sender,'Only Vehicle Owner can perform this step'); _; } /** * @dev Modifier to check if the vehicle renter is calling the transaction */ modifier onlyRenter() { require(renter == msg.sender,'Only Vehicle Renter can perform this step'); _; } /** * @dev Prevents a function being run unless contract is still active */ modifier onlyContractProposed() { require(agreementStatus == RentalAgreementFactory.RentalAgreementStatus.PROPOSED ,'Contract must be in PROPOSED status'); _; } /** * @dev Prevents a function being run unless contract is still active */ modifier onlyContractApproved() { require(agreementStatus == RentalAgreementFactory.RentalAgreementStatus.APPROVED ,'Contract must be in APPROVED status'); _; } /** * @dev Prevents a function being run unless contract is still active */ modifier onlyContractActive() { require(agreementStatus == RentalAgreementFactory.RentalAgreementStatus.ACTIVE ,'Contract must be in ACTIVE status'); _; } /** * @dev Step 01: Generate a contract in PROPOSED status */ constructor(address _vehicleOwner, address _renter, uint _startDateTime, uint _endDateTime, uint _totalRentCost, uint _totalBond, address _link, address _oracle, uint256 _oraclePaymentAmount, bytes32 _jobId) payable Ownable() public { //initialize variables required for Chainlink Node interaction setChainlinkToken(_link); setChainlinkOracle(_oracle); jobId = _jobId; oraclePaymentAmount = _oraclePaymentAmount; //first ensure insurer has fully funded the contract - check here. money should be transferred on creation of agreement. //require(msg.value > _totalCover, "Not enough funds sent to contract"); //now initialize values for the contract vehicleOwner = _vehicleOwner; renter = _renter; startDateTime = _startDateTime; endDateTime = _endDateTime; totalRentCost = _totalRentCost; totalBond = _totalBond; agreementStatus = RentalAgreementFactory.RentalAgreementStatus.PROPOSED; emit rentalAgreementCreated(vehicleOwner,renter,startDateTime,endDateTime,totalRentCost,totalBond); } /** * @dev Step 02a: Owner ACCEPTS proposal, contract becomes APPROVED */ function approveContract() external onlyVehicleOwner() onlyContractProposed() { //Vehicle Owner simply looks at proposed agreement & either approves or denies it. //Only vehicle owner can run this, contract must be in PROPOSED status //In this case, we approve. Contract becomes Approved and sits waiting until start time reaches agreementStatus = RentalAgreementFactory.RentalAgreementStatus.APPROVED; } /** * @dev Step 02b: Owner REJECTS proposal, contract becomes REJECTED. This is the end of the line for the Contract */ function rejectContract() external onlyVehicleOwner() onlyContractProposed() { //Vehicle Owner simply looks at proposed agreement & either approves or denies it. //Only vehicle owner can call this function //In this case, we approve. Contract becomes Rejected. No more actions should be possible on the contract in this status //return money to renter renter.transfer(address(this).balance); //return any LINK tokens in here back to the DAPP wallet LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(dappWallet, link.balanceOf(address(this))), "Unable to transfer"); //Set status to rejected. This is the end of the line for this agreement agreementStatus = RentalAgreementFactory.RentalAgreementStatus.REJECTED; } /** * @dev Step 03a: Renter starts contract, contract becomes ACTIVE * Conditions for starting contract: Must be APPROVED, & Start Date/Time must be <= current Date/Time */ function activateRentalContract() external onlyRenter() onlyContractApproved() { //First we need to wake up the vehicle & obtain some values needed in the contract before the vehicle can be unlocked & started //do external adapter call to wake up vehicle & get vehicle data //Need to check start time has reached //require(startDateTime <= now ,'Start Date/Time has not been reached'); //get vehicle ID of the vehicle, needed for the request uint vid = RentalAgreementFactory(dappWallet).getVehicleId(vehicleOwner); //call to chainlink node job to wake up the car, get starting vehicle data, then unlock the car Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.activeteRentalContractFallback.selector); req.add("apiToken", ""); req.add("vehicleId", uint2str(vid)); req.add("action", "unlock"); sendChainlinkRequestTo(chainlinkOracleAddress(), req, oraclePaymentAmount); } /** * @dev Step 03b: Callback function for obtaining vehicle data as part of rental agreement beginning * If we get to this stage, it means the vehicle successfully returned the required data to start the agreement, & the vehicle has been unlocked * Only the contract should be able to call this function */ function activeteRentalContractFallback(bytes32 _requestId, bytes32 _vehicleData) public recordChainlinkFulfillment(_requestId) { //Set contract variables to start the agreement //temp variables required for converting to signed integer uint tmpStartLongitude; uint tmpStartLatitude; bytes memory longitudeBytes; bytes memory latitudeBytes; //first split the results into individual strings based on the delimiter var s = bytes32ToString(_vehicleData).toSlice(); var delim = ",".toSlice(); //store each string in an array string[] memory splitResults = new string[](s.count(delim)+ 1); for (uint i = 0; i < splitResults.length; i++) { splitResults[i] = s.split(delim).toString(); } //Now for each one, convert to uint startOdometer = stringToUint(splitResults[0]); startChargeState = stringToUint(splitResults[1]); tmpStartLongitude = stringToUint(splitResults[2]); tmpStartLatitude = stringToUint(splitResults[3]); //Now store location coordinates in signed variables. Will always be positive, but will check in the next step if need to make negative startVehicleLongitude = int(tmpStartLongitude); startVehicleLatitude = int(tmpStartLatitude); //Finally, check first bye in the string for the location variables. If it was a '-', then multiply location coordinate by -1 //first get the first byte of each location coordinate string longitudeBytes = bytes(splitResults[2]); latitudeBytes = bytes(splitResults[3]); //First check longitude if (uint(longitudeBytes[0]) == 0x2d) { //first byte was a '-', multiply result by -1 startVehicleLongitude = startVehicleLongitude * -1; } //Now check latitude if (uint(latitudeBytes[0]) == 0x2d) { //first byte was a '-', multiply result by -1 startVehicleLatitude = startVehicleLatitude * -1; } //Values have been set, now set the contract to ACTIVE agreementStatus = RentalAgreementFactory.RentalAgreementStatus.ACTIVE; //Emit an event now that contract is now active emit contractActive(startOdometer,startChargeState,startVehicleLongitude,startVehicleLatitude); } /** * @dev Step 04a: Renter ends an active contract, contract becomes COMPLETED or ENDED_ERROR * Conditions for ending contract: Must be ACTIVE */ function endRentalContract() external onlyRenter() onlyContractActive() { //First we need to check if vehicle can be accessed, if so then do a call to get vehicle data //get vehicle ID of the vehicle, needed for the request uint vid = RentalAgreementFactory(dappWallet).getVehicleId(vehicleOwner); //call to chainlink node job to wake up the car, get ending vehicle data, then lock the car Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.endRentalContractFallback.selector); req.add("apiToken", ""); req.add("vehicleId", uint2str(vid)); req.add("action", "lock"); sendChainlinkRequestTo(chainlinkOracleAddress(), req, oraclePaymentAmount); } /** * @dev Step 04b: Callback for getting vehicle data on ending a rental agreement. Based on results Contract becomes COMPELTED or ENDED_ERROR * Conditions for ending contract: Must be ACTIVE. Only this contract should be able to call this function */ function endRentalContractFallback(bytes32 _requestId, bytes32 _vehicleData) public recordChainlinkFulfillment(_requestId) { //Set contract variables to end the agreement //temp variables required for converting to signed integer uint tmpEndLongitude; uint tmpEndLatitude; bytes memory longitudeBytes; bytes memory latitudeBytes; //first split the results into individual strings based on the delimiter var s = bytes32ToString(_vehicleData).toSlice(); var delim = ",".toSlice(); //store each string in an array string[] memory splitResults = new string[](s.count(delim)+ 1); for (uint i = 0; i < splitResults.length; i++) { splitResults[i] = s.split(delim).toString(); } //Now for each one, convert to uint endOdometer = stringToUint(splitResults[0]); endChargeState = stringToUint(splitResults[1]); tmpEndLongitude = stringToUint(splitResults[2]); tmpEndLatitude = stringToUint(splitResults[3]); //Now store location coordinates in signed variables. Will always be positive, but will check in the next step if need to make negative endVehicleLongitude = int(tmpEndLongitude); endVehicleLatitude = int(tmpEndLatitude); //Finally, check first bye in the string for the location variables. If it was a '-', then multiply location coordinate by -1 //first get the first byte of each location coordinate string longitudeBytes = bytes(splitResults[2]); latitudeBytes = bytes(splitResults[3]); //First check longitude if (uint(longitudeBytes[0]) == 0x2d) { //first byte was a '-', multiply result by -1 endVehicleLongitude = endVehicleLongitude * -1; } //Now check latitude if (uint(latitudeBytes[0]) == 0x2d) { //first byte was a '-', multiply result by -1 endVehicleLatitude = endVehicleLatitude * -1; } //Set the end time of the contract rentalAgreementEndDateTime = now; //Now that we have all values in contract, we can calculate final fees & penalties payable //First calculate and send platform fee //Total to go to platform = base fee / platform fee % totalPlatformFee = totalRentCost.div(uint(100).div(PLATFORM_FEE)); //now total rent payable is original amount minus calculated platform fee above totalRentPayable = totalRentCost - totalPlatformFee; //Total to go to car owner = (base fee - platform fee from above) + time penalty + location penalty + charge penalty //Now calculate penalties to be used for amount to go to car owner //Odometer penalty. Number of miles over agreed total miles * odometer penalty per mile. //Eg if only 10 miles allowed but agreement logged 20 miles, with a penalty of 1% per extra mile //then penalty is 20-10 = 10 * 1% = 10% of Bond totalMiles = endOdometer.sub(startOdometer); if (totalMiles > ODOMETER_BUFFER) { totalOdometerPenalty = totalMiles.mul(ODOMETER_FINE).mul(totalBond); totalOdometerPenalty = (totalMiles.sub(ODOMETER_BUFFER)).mul(totalBond.div(uint(100).div(ODOMETER_FINE))); } //Time penalty. Number of hours past agreed end date/time + buffer * time penalty per hour //eg TIME_FINE buffer set to 1 = 1% of bond for each hour past the end date + buffer (buffer currently set to 3 hours) if (rentalAgreementEndDateTime > endDateTime) { secsPastEndDate = rentalAgreementEndDateTime.sub(endDateTime); //if retuned later than the the grace period, incur penalty if (secsPastEndDate > TIME_BUFFER) { //penalty incurred //penalty TIME_FINE is a % per hour over. So if over by less than an hour, round up to an hour if (secsPastEndDate.sub(TIME_BUFFER) < 3600) { totalTimePenalty = uint(1).mul(totalBond.div(uint(100).div(TIME_FINE))); } else { //do normal penlaty calculation in hours totalTimePenalty = secsPastEndDate.sub(TIME_BUFFER).div(3600).mul(totalBond.div(uint(100).div(TIME_FINE))); } } } //Charge penalty. Simple comparison of charge at start & end. If it isn't at least what it was at agreement start, then a static fee is paid of //CHARGE_FINE, which is a % of bond. Currently set to 1% if (startChargeState > endChargeState) { totalChargePenalty = totalBond.div(uint(100).div(CHARGE_FINE)); } //Location penalty. If the vehicle is not returned to around the same spot, then a penalty is incurred. //Allowed distance from original spot is stored in the LOCATION_BUFFER param, currently set to 100m //Penalty incurred is stored in LOCATION_FINE, and applies per km off from the original location //Penalty applies to either location coordinates //eg if LOCATION_BUFFER set to 100m, fee set to 1% per 1km, and renter returns vehicle 2km from original place //fee payable is 2 * 1 = 2% of bond longitudeDifference = abs(abs(startVehicleLongitude) - abs(endVehicleLongitude)); latitudeDifference = abs(abs(startVehicleLatitude) - abs(endVehicleLatitude)); if (longitudeDifference > LOCATION_BUFFER) { //If difference in longitude is > 100m totalLocationPenalty = uint(longitudeDifference).div(10000).mul(totalBond.div(uint(100).div(LOCATION_FINE))); } else if (latitudeDifference > LOCATION_BUFFER) { //If difference in latitude is > 100m totalLocationPenalty = uint(latitudeDifference).div(10000).mul(totalBond.div(uint(100).div(LOCATION_FINE))); } //Final amount of bond to go to owner = sum of all penalties above. Then renter gets rest bondForfeited = totalOdometerPenalty.add(totalTimePenalty).add(totalChargePenalty).add(totalLocationPenalty); uint bondKept = totalBond.sub(bondForfeited); //Now that we have all fees & charges calculated, perform necessary transfers & then end contract //first pay platform fee dappWallet.transfer(totalPlatformFee); //then pay vehicle owner rent amount vehicleOwner.transfer(totalRentPayable); //pay Owner any bond penalties. Only if > 0 if (bondForfeited > 0) { owner.transfer(bondForfeited); } //finally, pay renter back any remaining bond totalBondReturned = address(this).balance; renter.transfer(totalBondReturned); //Transfers all completed, now we just need to set contract status to successfully completed agreementStatus = RentalAgreementFactory.RentalAgreementStatus.COMPLETED; //Emit an event with all the payments emit agreementPayments(totalPlatformFee, totalRentPayable, bondKept, bondForfeited, totalTimePenalty, totalChargePenalty, totalLocationPenalty, totalOdometerPenalty); //Emit an event now that contract is now ended emit contractCompleted(endOdometer,endChargeState,endVehicleLongitude,endVehicleLatitude); } /** * @dev Step 04c: Car Owner ends an active contract due to the Renter not ending it, contract becomes ENDED_ERROR * Conditions for ending contract: Must be ACTIVE, & End Date must be in the past more than the current defined TIME_BUFFER value */ function forceEndRentalContract() external onlyOwner() onlyContractActive() { //don't allow unless contract still active & current time is > contract end date + TIME_BUFFER require(now > endDateTime + TIME_BUFFER, "Agreement not eligible for forced cancellation yet"); //get vehicle ID of the vehicle, needed for the request uint vid = RentalAgreementFactory(dappWallet).getVehicleId(vehicleOwner); //call to chainlink node job to wake up the car, get ending vehicle data Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.forceEndRentalContractFallback.selector); req.add("apiToken", ""); req.add("vehicleId", uint2str(vid)); req.add("action", "vehicle_data"); sendChainlinkRequestTo(chainlinkOracleAddress(), req, oraclePaymentAmount); } /** * @dev Step 04d: Callback for force ending a vehicle agreement. Based on results Contract becomes ENDED_ERROR */ function forceEndRentalContractFallback(bytes32 _requestId, bytes32 _vehicleData) public recordChainlinkFulfillment(_requestId) { totalPlatformFee = totalRentCost.div(uint(100).div(PLATFORM_FEE)); //now total rent payable is original amount minus calculated platform fee above totalRentPayable = totalRentCost - totalPlatformFee; bondForfeited = totalBondReturned; totalBondReturned = 0; //Now that we have all fees & charges calculated, perform necessary transfers & then end contract //first pay platform fee dappWallet.transfer(totalPlatformFee); //then pay vehicle owner rent payable vehicleOwner.transfer(totalRentPayable); //pay owner the bond owed vehicleOwner.transfer(bondForfeited); //Transfers all completed, now we just need to set contract status to successfully completed agreementStatus = RentalAgreementFactory.RentalAgreementStatus.ENDED_ERROR; //Emit an event now that contract is now ended emit contractCompletedError(endOdometer,endChargeState,endVehicleLongitude,endVehicleLatitude); } /** * @dev Get address of the chainlink token */ function getChainlinkToken() public view returns (address) { return chainlinkTokenAddress(); } /** * @dev Get address of vehicle owner */ function getVehicleOwner() public view returns (address) { return vehicleOwner; } /** * @dev Get address of vehicle renter */ function getVehicleRenter() public view returns (address) { return renter; } /** * @dev Get status of the agreement */ function getAgreementStatus() public view returns (RentalAgreementFactory.RentalAgreementStatus) { return agreementStatus; } /** * @dev Get start date/time */ function getAgreementStartTime() public view returns (uint) { return startDateTime; } /** * @dev Get end date/time */ function getAgreementEndTime() public view returns (uint) { return endDateTime; } /** * @dev Return All Details about a Vehicle Rental Agreement */ function getAgreementDetails() public view returns (address,address,uint,uint,uint,uint,RentalAgreementFactory.RentalAgreementStatus) { return (vehicleOwner,renter,startDateTime,endDateTime,totalRentCost,totalBond,agreementStatus); } /** * @dev Return All Vehicle Data from a Vehicle Rental Agreement */ function getAgreementData() public view returns (uint, uint, int, int, uint, uint, int, int) { return (startOdometer,startChargeState,startVehicleLongitude, startVehicleLatitude,endOdometer,endChargeState, endVehicleLongitude,endVehicleLatitude); } /** * @dev Return All Payment & fee Details about a Vehicle Rental Agreement */ function getPaymentDetails() public view returns (uint, uint, uint, uint, uint, uint, uint, uint) { return (rentalAgreementEndDateTime,totalLocationPenalty,totalOdometerPenalty,totalChargePenalty,totalTimePenalty,totalPlatformFee,totalRentPayable,totalBondReturned); } /** * @dev Helper function to get absolute value of an int */ function abs(int x) private pure returns (int) { return x >= 0 ? x : -x; } /** * @dev Helper function for converting uint to a string */ function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function bytes32ToString(bytes32 x) constant returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function stringToUint(string s) constant returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } }
Return a particular Rental Contract based on a rental contract address/loop through list of contracts, and find any belonging to the address
function getRentalContract(address _rentalContract) external view returns (address,address,uint,uint,uint,uint,RentalAgreementStatus ) { for (uint i = 0; i < rentalAgreements.length; i++) { if (address(rentalAgreements[i]) == _rentalContract) { return rentalAgreements[i].getAgreementDetails(); } } }
2,511,984
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./libraries/ABDKMath64x64.sol"; import "./libraries/Utils.sol"; import "./libraries/UniswapLibrary.sol"; import "./BlockLock.sol"; import "./interfaces/IxTokenManager.sol"; contract xU3LPStable is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, BlockLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant LIQUIDATION_TIME_PERIOD = 4 weeks; uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 1; uint256 private constant BUFFER_TARGET = 20; // 5% target uint256 private constant SWAP_SLIPPAGE = 100; // 1% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% uint24 private constant POOL_FEE = 500; // Used to give an identical token representation uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; int24 tickLower; int24 tickUpper; // Prices calculated using above ticks from TickMath.getSqrtRatioAtTick() uint160 priceLower; uint160 priceUpper; int128 lastTwap; // Last stored oracle twap // Max current twap vs last twap deviation percentage divisor (100 = 1%) uint256 maxTwapDeviationDivisor; IERC20 token0; IERC20 token1; address public poolAddress; address public routerAddress; address public positionManagerAddress; uint256 public adminActiveTimestamp; uint256 public withdrawableToken0Fees; uint256 public withdrawableToken1Fees; uint256 public tokenId; // token id representing this uniswap position uint256 public token0DecimalMultiplier; // 10 ** (18 - token0 decimals) uint256 public token1DecimalMultiplier; // 10 ** (18 - token1 decimals) uint256 public tokenDiffDecimalMultiplier; // 10 ** (token0 decimals - token1 decimals) uint8 public token0Decimals; uint8 public token1Decimals; address private manager; address private manager2; struct FeeDivisors { uint256 mintFee; uint256 burnFee; uint256 claimFee; } FeeDivisors public feeDivisors; uint32 twapPeriod; IxTokenManager xTokenManager; // xToken manager contract event Rebalance(); event FeeDivisorsSet(uint256 mintFee, uint256 burnFee, uint256 claimFee); event FeeWithdraw(uint256 token0Fee, uint256 token1Fee); event FeeCollected(uint256 token0Fee, uint256 token1Fee); function initialize( string memory _symbol, int24 _tickLower, int24 _tickUpper, IERC20 _token0, IERC20 _token1, address _pool, address _router, address _positionManager, FeeDivisors memory _feeDivisors, uint256 _maxTwapDeviationDivisor, uint8 _token0Decimals, uint8 _token1Decimals ) external initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xU3LP", _symbol); tickLower = _tickLower; tickUpper = _tickUpper; priceLower = UniswapLibrary.getSqrtRatio(_tickLower); priceUpper = UniswapLibrary.getSqrtRatio(_tickUpper); if (_token0 > _token1) { token0 = _token1; token1 = _token0; token0Decimals = _token1Decimals; token1Decimals = _token0Decimals; } else { token0 = _token0; token1 = _token1; token0Decimals = _token0Decimals; token1Decimals = _token1Decimals; } token0DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token0Decimals); token1DecimalMultiplier = 10**(TOKEN_DECIMAL_REPRESENTATION - token1Decimals); tokenDiffDecimalMultiplier = 10**((Utils.subAbs(token0Decimals, token1Decimals))); maxTwapDeviationDivisor = _maxTwapDeviationDivisor; poolAddress = _pool; routerAddress = _router; positionManagerAddress = _positionManager; token0.safeIncreaseAllowance(_router, type(uint256).max); token1.safeIncreaseAllowance(_router, type(uint256).max); token0.safeIncreaseAllowance(_positionManager, type(uint256).max); token1.safeIncreaseAllowance(_positionManager, type(uint256).max); lastTwap = getAsset0Price(); _setFeeDivisors(_feeDivisors); } /* ========================================================================================= */ /* User-facing */ /* ========================================================================================= */ /** * @dev Mint xU3LP tokens by sending *amount* of *inputAsset* tokens */ function mintWithToken(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); if (inputAsset == 0) { token0.safeTransferFrom(msg.sender, address(this), amount); amount = getAmountInAsset1Terms(amount); uint256 fee = Utils.calculateFee(amount, feeDivisors.mintFee); _incrementWithdrawableToken0Fees(fee); _mintInternal(getToken0AmountInWei(amount.sub(fee))); } else { token1.safeTransferFrom(msg.sender, address(this), amount); uint256 fee = Utils.calculateFee(amount, feeDivisors.mintFee); _incrementWithdrawableToken1Fees(fee); _mintInternal(getToken1AmountInWei(amount.sub(fee))); } } /** * @dev Burn *amount* of xU3LP tokens to receive proportional * amount of *outputAsset* tokens */ function burn(uint8 outputAsset, uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); (uint256 bufferToken0Balance, uint256 bufferToken1Balance) = getBufferTokenBalance(); uint256 nav = getNav(); uint256 proRataBalance; if (outputAsset == 0) { proRataBalance = (nav.mul(getAmountInAsset0Terms(amount))).div( totalSupply() ); require( proRataBalance <= bufferToken0Balance, "Insufficient exit liquidity" ); } else { proRataBalance = (nav.mul(amount).div(totalSupply())); require( proRataBalance <= bufferToken1Balance, "Insufficient exit liquidity" ); } super._burn(msg.sender, amount); // Fee is in wei (18 decimals, so doesn't need to be normalized) uint256 fee = Utils.calculateFee(proRataBalance, feeDivisors.burnFee); if (outputAsset == 0) { withdrawableToken0Fees = withdrawableToken0Fees.add(fee); uint256 transferAmount = getToken0AmountInNativeDecimals(proRataBalance.sub(fee)); token0.safeTransfer(msg.sender, transferAmount); } else { withdrawableToken1Fees = withdrawableToken1Fees.add(fee); uint256 transferAmount = getToken1AmountInNativeDecimals(proRataBalance.sub(fee)); token1.safeTransfer(msg.sender, transferAmount); } } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price() public view returns (int128) { return UniswapLibrary.getAsset0Price( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price() public view returns (int128) { return UniswapLibrary.getAsset1Price( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset0Terms( amount, poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms(uint256 amount) public view returns (uint256) { return UniswapLibrary.getAmountInAsset1Terms( amount, poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); } // Get net asset value function getNav() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } // Get total balance in the position function getStakedBalance() public view returns (uint256) { (uint256 amount0, uint256 amount1) = getStakedTokenBalance(); return getAmountInAsset1Terms(amount0).add(amount1); } // Get balance in xU3LP contract function getBufferBalance() public view returns (uint256) { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); return getAmountInAsset1Terms(balance0).add(balance1); } // Get token balances in xU3LP contract function getBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { return (getBufferToken0Balance(), getBufferToken1Balance()); } function getBufferToken0Balance() public view returns (uint256 amount0) { uint256 balance0 = getToken0AmountInWei(token0.balanceOf(address(this))); return Utils.sub0(balance0, withdrawableToken0Fees); } function getBufferToken1Balance() public view returns (uint256 amount1) { uint256 balance1 = getToken1AmountInWei(token1.balanceOf(address(this))); return Utils.sub0(balance1, withdrawableToken1Fees); } // Get token balances in the position function getStakedTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity(getPositionLiquidity()); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); } // Get wanted xU3LP contract token balance - 5% of NAV function getTargetBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (uint256 bufferAmount0, uint256 bufferAmount1) = getBufferTokenBalance(); (uint256 poolAmount0, uint256 poolAmount1) = getStakedTokenBalance(); amount0 = bufferAmount0.add(poolAmount0).div(BUFFER_TARGET); amount1 = bufferAmount1.add(poolAmount1).div(BUFFER_TARGET); // Keep 50:50 ratio amount0 = amount0.add(amount1).div(2); amount1 = amount0; } // Check how much xU3LP tokens will be minted function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount.mul(INITIAL_SUPPLY_MULTIPLIER); uint256 previousNav = getNav().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousNav); return mintAmount; } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ function rebalance() external onlyOwnerOrManager { collect(); _rebalance(); _certifyAdmin(); } function _rebalance() private { _provideOrRemoveLiquidity(); emit Rebalance(); } function _provideOrRemoveLiquidity() private { checkTwap(); (uint256 bufferToken0Balance, uint256 bufferToken1Balance) = getBufferTokenBalance(); (uint256 targetToken0Balance, uint256 targetToken1Balance) = getTargetBufferTokenBalance(); uint256 bufferBalance = bufferToken0Balance.add(bufferToken1Balance); uint256 targetBalance = targetToken0Balance.add(targetToken1Balance); uint256 _amount0 = Utils.subAbs(bufferToken0Balance, targetToken0Balance); uint256 _amount1 = Utils.subAbs(bufferToken1Balance, targetToken1Balance); _amount0 = getToken0AmountInNativeDecimals(_amount0); _amount1 = getToken1AmountInNativeDecimals(_amount1); (uint256 amount0, uint256 amount1) = checkIfAmountsMatchAndSwap(_amount0, _amount1); if (amount0 == 0 || amount1 == 0) { return; } if (bufferBalance > targetBalance) { _stake(amount0, amount1); } else if (bufferBalance < targetBalance) { _unstake(amount0, amount1); } } /** * @dev Stake liquidity in position */ function _stake(uint256 amount0, uint256 amount1) private returns (uint256 stakedAmount0, uint256 stakedAmount1) { return UniswapLibrary.stake( amount0, amount1, positionManagerAddress, tokenId ); } /** * @dev Unstake liquidity from position */ function _unstake(uint256 amount0, uint256 amount1) private returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount); return collectPosition(uint128(_amount0), uint128(_amount1)); } // Collect fees function collect() public onlyOwnerOrManager { (uint256 collected0, uint256 collected1) = collectPosition(type(uint128).max, type(uint128).max); uint256 fee0 = Utils.calculateFee(collected0, feeDivisors.claimFee); uint256 fee1 = Utils.calculateFee(collected1, feeDivisors.claimFee); _incrementWithdrawableToken0Fees(fee0); _incrementWithdrawableToken1Fees(fee1); emit FeeCollected(collected0, collected1); } /** * @dev Check if token amounts match before attempting rebalance * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible */ function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint ) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: POOL_FEE, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }); return UniswapLibrary.checkIfAmountsMatchAndSwap( true, amount0ToMint, amount1ToMint, positionDetails, tokenDetails ); } // Migrate the current position to a new position with different ticks function migratePosition(int24 newTickLower, int24 newTickUpper) external onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT UniswapLibrary.burn(positionManagerAddress, tokenId); tokenId = 0; // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = UniswapLibrary.getSqrtRatio(newTickLower); priceUpper = UniswapLibrary.getSqrtRatio(newTickUpper); // if amounts don't add up when minting, swap tokens (uint256 amount0, uint256 amount1) = checkIfAmountsMatchAndSwap(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); } // Withdraws all current liquidity from the position function withdrawAll() private returns (uint256 _amount0, uint256 _amount1) { // Collect fees collect(); (_amount0, _amount1) = unstakePosition(getPositionLiquidity()); collectPosition(uint128(_amount0), uint128(_amount1)); } /** * Mint function which initializes the pool position * Must be called before any liquidity can be deposited */ function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); if (amount0 > 0) { token0.safeTransferFrom(msg.sender, address(this), amount0); } if (amount1 > 0) { token1.safeTransferFrom(msg.sender, address(this), amount1); } tokenId = createPosition(amount0, amount1); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); _mintInternal(getAmountInAsset1Terms(amount0).add(amount1)); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { UniswapLibrary.TokenDetails memory tokenDetails = UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }); UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: POOL_FEE, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }); return UniswapLibrary.createPosition( amount0, amount1, positionManagerAddress, tokenDetails, positionDetails ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { UniswapLibrary.PositionDetails memory positionDetails = UniswapLibrary.PositionDetails({ poolFee: POOL_FEE, priceLower: priceLower, priceUpper: priceUpper, tokenId: tokenId, positionManager: positionManagerAddress, router: routerAddress, pool: poolAddress }); return UniswapLibrary.unstakePosition(liquidity, positionDetails); } /* * @notice Registers that admin is present and active * @notice If admin isn't certified within liquidation time period, * emergencyUnstake function becomes callable */ function _certifyAdmin() private { adminActiveTimestamp = block.timestamp; } /* * @dev Public callable function for unstaking in event of admin failure/incapacitation */ function emergencyUnstake(uint256 _amount0, uint256 _amount1) external { require( adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp ); _unstake(_amount0, _amount1); } function _mintInternal(uint256 _amount) private { uint256 mintAmount = calculateMintAmount(_amount, totalSupply()); return super._mint(msg.sender, mintAmount); } function _incrementWithdrawableToken0Fees(uint256 _feeAmount) private { withdrawableToken0Fees = withdrawableToken0Fees.add( getToken0AmountInWei(_feeAmount) ); } function _incrementWithdrawableToken1Fees(uint256 _feeAmount) private { withdrawableToken1Fees = withdrawableToken1Fees.add( getToken1AmountInWei(_feeAmount) ); } /* * @notice Inverse of fee i.e., a fee divisor of 100 == 1% * @notice Three fee types * @dev Mint fee 0 or <= 1% * @dev Burn fee 0 or <= 1% * @dev Claim fee 0 <= 4% */ function setFeeDivisors(FeeDivisors memory _feeDivisors) external onlyOwnerOrManager { _setFeeDivisors(_feeDivisors); } function _setFeeDivisors(FeeDivisors memory _feeDivisors) private { require(_feeDivisors.mintFee == 0 || _feeDivisors.mintFee >= 100); require(_feeDivisors.burnFee == 0 || _feeDivisors.burnFee >= 100); require(_feeDivisors.claimFee == 0 || _feeDivisors.claimFee >= 25); feeDivisors.mintFee = _feeDivisors.mintFee; feeDivisors.burnFee = _feeDivisors.burnFee; feeDivisors.claimFee = _feeDivisors.claimFee; emit FeeDivisorsSet( feeDivisors.mintFee, feeDivisors.burnFee, feeDivisors.claimFee ); } /* * Emergency function in case of errant transfer * of any token directly to contract */ function withdrawToken(address token, address receiver) external onlyOwnerOrManager { require(token != address(token0) && token != address(token1)); uint256 tokenBal = IERC20(address(token)).balanceOf(address(this)); if (tokenBal > 0) { IERC20(address(token)).safeTransfer(receiver, tokenBal); } } /* * Withdraw function for token0 and token1 fees */ function withdrawFees() external { require( xTokenManager.isRevenueController(msg.sender), "Callable only by Revenue Controller" ); uint256 token0Fees = getToken0AmountInNativeDecimals(withdrawableToken0Fees); uint256 token1Fees = getToken1AmountInNativeDecimals(withdrawableToken1Fees); if (token0Fees > 0) { token0.safeTransfer(msg.sender, token0Fees); withdrawableToken0Fees = 0; } if (token1Fees > 0) { token1.safeTransfer(msg.sender, token1Fees); withdrawableToken1Fees = 0; } emit FeeWithdraw(token0Fees, token1Fees); } /* * Admin function for staking beyond the scope of a rebalance */ function adminStake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _stake(amount0, amount1); } /* * Admin function for unstaking beyond the scope of a rebalance */ function adminUnstake(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { _unstake(amount0, amount1); } /* * Admin function for swapping LP tokens in xU3LP * @param amount - how much to swap * @param _0for1 - swap token 0 for 1 if true, token 1 for 0 if false */ function adminSwap(uint256 amount, bool _0for1) external onlyOwnerOrManager { if (_0for1) { swapToken0ForToken1(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } else { swapToken1ForToken0(amount.add(amount.div(SWAP_SLIPPAGE)), amount); } } /** * @dev Admin function for swapping LP tokens in xU3LP using 1inch v3 exchange * @param minReturn - how much output tokens to receive on swap, in 18 decimals * @param _0for1 - swap token 0 for token 1 if true, token 1 for token 0 if false * @param _oneInchData - 1inch calldata, generated off-chain using their v3 api */ function adminSwapOneInch( uint256 minReturn, bool _0for1, bytes memory _oneInchData ) external onlyOwnerOrManager { UniswapLibrary.oneInchSwap( true, minReturn, _0for1, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }), _oneInchData ); } function pauseContract() external onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() external onlyOwnerOrManager returns (bool) { _unpause(); return true; } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Function may be called only by owner or manager" ); _; } /* ========================================================================================= */ /* Uniswap helpers */ /* ========================================================================================= */ function swapToken0ForToken1(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken0ForToken1( amountIn, amountOut, POOL_FEE, routerAddress, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } function swapToken1ForToken0(uint256 amountIn, uint256 amountOut) private { UniswapLibrary.swapToken1ForToken0( amountIn, amountOut, POOL_FEE, routerAddress, UniswapLibrary.TokenDetails({ token0: address(token0), token1: address(token1), token0DecimalMultiplier: token0DecimalMultiplier, token1DecimalMultiplier: token1DecimalMultiplier, token0Decimals: token0Decimals, token1Decimals: token1Decimals }) ); } // Returns the current liquidity in the position function getPositionLiquidity() public view returns (uint128 liquidity) { return UniswapLibrary.getPositionLiquidity( positionManagerAddress, tokenId ); } // Returns the current pool price function getPoolPrice() private view returns (uint160) { return UniswapLibrary.getPoolPrice(poolAddress); } // Returns the current pool liquidity function getPoolLiquidity() private view returns (uint128) { return UniswapLibrary.getPoolLiquidity(poolAddress); } /** * @dev Checks if twap deviates too much from the previous twap */ function checkTwap() private { lastTwap = UniswapLibrary.checkTwap( poolAddress, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier, lastTwap, maxTwapDeviationDivisor ); } /** * Reset last twap if oracle price is consistently above the max deviation * Requires twap to be above max deviation to execute */ function resetTwap() external onlyOwnerOrManager { lastTwap = getAsset0Price(); } /** * Set the max twap deviation divisor */ function setMaxTwapDeviationDivisor(uint256 newDeviationDivisor) external onlyOwnerOrManager { maxTwapDeviationDivisor = newDeviationDivisor; } /** * Set the oracle reading twap period */ function setTwapPeriod(uint32 newPeriod) external onlyOwnerOrManager { require(newPeriod >= 360); twapPeriod = newPeriod; } /** * @dev Collect token amounts from pool position */ function collectPosition(uint128 amount0, uint128 amount1) private returns (uint256 collected0, uint256 collected1) { return UniswapLibrary.collectPosition( amount0, amount1, tokenId, positionManagerAddress ); } /** * Calculates the amounts deposited/withdrawn from the pool * amount0, amount1 - amounts to deposit/withdraw * amount0Minted, amount1Minted - actual amounts which can be deposited */ function calculatePoolMintedAmounts(uint256 amount0, uint256 amount1) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts(amount0, amount1); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount ); } function getAmountsForLiquidity(uint128 liquidity) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = UniswapLibrary.getAmountsForLiquidity( liquidity, priceLower, priceUpper, poolAddress ); } function getLiquidityForAmounts(uint256 amount0, uint256 amount1) public view returns (uint128 liquidity) { liquidity = UniswapLibrary.getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, poolAddress ); } /** * Get lower and upper ticks of the pool position */ function getTicks() external view returns (int24 tick0, int24 tick1) { return (tickLower, tickUpper); } /** * Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInWei( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInWei( amount, token1Decimals, token1DecimalMultiplier ); } /** * Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken0AmountInNativeDecimals( amount, token0Decimals, token0DecimalMultiplier ); } /** * Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals(uint256 amount) private view returns (uint256) { return UniswapLibrary.getToken1AmountInNativeDecimals( amount, token1Decimals, token1DecimalMultiplier ); } /** * Set xTokenManager contract */ function setxTokenManager(IxTokenManager _manager) external onlyOwner { require(address(xTokenManager) == address(0)); xTokenManager = _manager; } /** * Approve 1inch v3 exchange for swaps */ function approveOneInch() external onlyOwnerOrManager { UniswapLibrary.approveOneInch(token0, token1); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^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, 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.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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.7.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return uint64(x >> 64); } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(uint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) internal pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) internal pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; /** * Library with utility functions for xU3LP */ library Utils { using SafeMath for uint256; /** Get asset 1 twap price for the period of [now - secondsAgo, now] */ function getTWAP(int56[] memory prices, uint32 secondsAgo) internal pure returns (int128) { // Formula is // 1.0001 ^ (currentPrice - pastPrice) / secondsAgo if (secondsAgo == 0) { return ABDKMath64x64.fromInt(1); } int256 diff = int256(prices[1]) - int256(prices[0]); uint256 priceDiff = diff < 0 ? uint256(-diff) : uint256(diff); int128 fraction = ABDKMath64x64.divu(priceDiff, uint256(secondsAgo)); int128 twap = ABDKMath64x64.pow( ABDKMath64x64.divu(10001, 10000), uint256(ABDKMath64x64.toUInt(fraction)) ); // This is necessary because we cannot call .pow on unsigned integers // And thus when asset0Price > asset1Price we need to reverse the value twap = diff < 0 ? ABDKMath64x64.inv(twap) : twap; return twap; } /** * Helper function to calculate how much to swap to deposit / withdraw * In Uni Pool to satisfy the required buffer balance in xU3LP of 5% */ function calculateSwapAmount( uint256 amount0ToMint, uint256 amount1ToMint, uint256 amount0Minted, uint256 amount1Minted, int128 liquidityRatio ) internal pure returns (uint256 swapAmount) { // formula: swapAmount = // (amount0ToMint * amount1Minted - // amount1ToMint * amount0Minted) / // ((amount0Minted + amount1Minted) + // liquidityRatio * (amount0ToMint + amount1ToMint)) uint256 mul1 = amount0ToMint.mul(amount1Minted); uint256 mul2 = amount1ToMint.mul(amount0Minted); uint256 sub = subAbs(mul1, mul2); uint256 add1 = amount0Minted.add(amount1Minted); uint256 add2 = ABDKMath64x64.mulu( liquidityRatio, amount0ToMint.add(amount1ToMint) ); uint256 add = add1.add(add2); // Some numbers are too big to fit in ABDK's div 128-bit representation // So calculate the root of the equation and then raise to the 2nd power int128 nRatio = ABDKMath64x64.divu( ABDKMath64x64.sqrtu(sub), ABDKMath64x64.sqrtu(add) ); int64 n = ABDKMath64x64.toInt(nRatio); swapAmount = uint256(n)**2; } // comparator for 32-bit timestamps // @return bool Whether a <= b function lte( uint32 time, uint32 a, uint32 b ) internal pure returns (bool) { if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2**32; uint256 bAdjusted = b > time ? b : b + 2**32; return aAdjusted <= bAdjusted; } // Subtract two numbers and return absolute value function subAbs(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } // Subtract two numbers and return 0 if result is < 0 function sub0(uint256 amount0, uint256 amount1) internal pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : 0; } function calculateFee(uint256 _value, uint256 _feeDivisor) internal pure returns (uint256 fee) { if (_feeDivisor > 0) { fee = _value.div(_feeDivisor); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./ABDKMath64x64.sol"; import "./Utils.sol"; /** * Helper library for Uniswap functions * Used in xU3LP and xAssetCLR */ library UniswapLibrary { using SafeMath for uint256; using SafeERC20 for IERC20; uint8 private constant TOKEN_DECIMAL_REPRESENTATION = 18; uint256 private constant SWAP_SLIPPAGE = 100; // 1% uint256 private constant MINT_BURN_SLIPPAGE = 100; // 1% uint256 private constant BUFFER_TARGET = 20; // 5% target // 1inch v3 exchange address address private constant oneInchExchange = 0x11111112542D85B3EF69AE05771c2dCCff4fAa26; struct TokenDetails { address token0; address token1; uint256 token0DecimalMultiplier; uint256 token1DecimalMultiplier; uint8 token0Decimals; uint8 token1Decimals; } struct PositionDetails { uint24 poolFee; uint160 priceLower; uint160 priceUpper; uint256 tokenId; address positionManager; address router; address pool; } struct AmountsMinted { uint256 amount0ToMint; uint256 amount1ToMint; uint256 amount0Minted; uint256 amount1Minted; } /* ========================================================================================= */ /* Uni V3 Pool Helper functions */ /* ========================================================================================= */ /** * @dev Returns the current pool price */ function getPoolPrice(address _pool) public view returns (uint160) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return sqrtRatioX96; } /** * @dev Returns the current pool liquidity */ function getPoolLiquidity(address _pool) public view returns (uint128) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); return pool.liquidity(); } /** * @dev Calculate pool liquidity for given token amounts */ function getLiquidityForAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint128 liquidity) { liquidity = LiquidityAmounts.getLiquidityForAmounts( getPoolPrice(pool), priceLower, priceUpper, amount0, amount1 ); } /** * @dev Calculate token amounts for given pool liquidity */ function getAmountsForLiquidity( uint128 liquidity, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( getPoolPrice(pool), priceLower, priceUpper, liquidity ); } /** * @dev Calculates the amounts deposited/withdrawn from the pool * @param amount0 - token0 amount to deposit/withdraw * @param amount1 - token1 amount to deposit/withdraw */ function calculatePoolMintedAmounts( uint256 amount0, uint256 amount1, uint160 priceLower, uint160 priceUpper, address pool ) public view returns (uint256 amount0Minted, uint256 amount1Minted) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, priceLower, priceUpper, pool ); (amount0Minted, amount1Minted) = getAmountsForLiquidity( liquidityAmount, priceLower, priceUpper, pool ); } /** * @dev Get asset 0 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset0Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time IUniswapV3Pool poolImpl = IUniswapV3Pool(pool); uint32 observationTime = getObservationTime(poolImpl); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = poolImpl.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; } /** * @dev Get asset 1 twap * @dev Uses Uni V3 oracle, reading the TWAP from twap period * @dev or the earliest oracle observation time if twap period is not set */ function getAsset1Price( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (int128) { return ABDKMath64x64.inv( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ) ); } /** * @dev Returns amount in terms of asset 0 * @dev amount * asset 1 price */ function getAmountInAsset0Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset1Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns amount in terms of asset 1 * @dev amount * asset 0 price */ function getAmountInAsset1Terms( uint256 amount, address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier ) public view returns (uint256) { return ABDKMath64x64.mulu( getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ), amount ); } /** * @dev Returns the earliest oracle observation time */ function getObservationTime(IUniswapV3Pool _pool) public view returns (uint32) { IUniswapV3Pool pool = _pool; (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; } /** * @dev Checks if twap deviates too much from the previous twap * @return current twap */ function checkTwap( address pool, uint32 twapPeriod, uint8 token0Decimals, uint8 token1Decimals, uint256 tokenDiffDecimalMultiplier, int128 lastTwap, uint256 maxTwapDeviationDivisor ) public view returns (int128) { int128 twap = getAsset0Price( pool, twapPeriod, token0Decimals, token1Decimals, tokenDiffDecimalMultiplier ); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); return twap; } /** * @dev get tick spacing corresponding to pool fee amount */ function getTickSpacingForFee(uint24 fee) public pure returns (int24) { if (fee == 500) { return 10; } else if (fee == 3000) { return 60; } else if (fee == 10000) { return 200; } else { return 0; } } /* ========================================================================================= */ /* Uni V3 Swap Router Helper functions */ /* ========================================================================================= */ /** * @dev Swap token 0 for token 1 in xU3LP / xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always */ function swapToken0ForToken1( uint256 amountIn, uint256 amountOut, uint24 poolFee, address routerAddress, TokenDetails memory tokenDetails ) public { ISwapRouter router = ISwapRouter(routerAddress); amountIn = getToken0AmountInNativeDecimals( amountIn, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOut = getToken1AmountInNativeDecimals( amountOut, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); router.exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token0, tokenOut: tokenDetails.token1, fee: poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MIN_SQRT_RATIO + 1 }) ); } /** * @dev Swap token 1 for token 0 in xU3LP / xAssetCLR contract * @dev amountIn and amountOut should be in 18 decimals always */ function swapToken1ForToken0( uint256 amountIn, uint256 amountOut, uint24 poolFee, address routerAddress, TokenDetails memory tokenDetails ) public { ISwapRouter router = ISwapRouter(routerAddress); amountIn = getToken1AmountInNativeDecimals( amountIn, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOut = getToken0AmountInNativeDecimals( amountOut, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); router.exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: tokenDetails.token1, tokenOut: tokenDetails.token0, fee: poolFee, recipient: address(this), deadline: block.timestamp, amountOut: amountOut, amountInMaximum: amountIn, sqrtPriceLimitX96: TickMath.MAX_SQRT_RATIO - 1 }) ); } /* ========================================================================================= */ /* 1inch Swap Helper functions */ /* ========================================================================================= */ /** * @dev Swap tokens in xU3LP / xAssetCLR using 1inch v3 exchange * @param xU3LP - swap for xU3LP if true, xAssetCLR if false * @param minReturn - required min amount out from swap, in 18 decimals * @param _0for1 - swap token0 for token1 if true, token1 for token0 if false * @param tokenDetails - xU3LP / xAssetCLR token 0 and token 1 details * @param _oneInchData - One inch calldata, generated off-chain from their v3 api for the swap */ function oneInchSwap( bool xU3LP, uint256 minReturn, bool _0for1, TokenDetails memory tokenDetails, bytes memory _oneInchData ) public { uint256 token0AmtSwapped; uint256 token1AmtSwapped; bool success; // inline code to prevent stack too deep errors { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); uint256 balanceBeforeToken0 = token0.balanceOf(address(this)); uint256 balanceBeforeToken1 = token1.balanceOf(address(this)); (success, ) = oneInchExchange.call(_oneInchData); require(success, "One inch swap call failed"); uint256 balanceAfterToken0 = token0.balanceOf(address(this)); uint256 balanceAfterToken1 = token1.balanceOf(address(this)); token0AmtSwapped = subAbs(balanceAfterToken0, balanceBeforeToken0); token1AmtSwapped = subAbs(balanceAfterToken1, balanceBeforeToken1); } uint256 amountInSwapped; uint256 amountOutReceived; if (_0for1) { amountInSwapped = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amountOutReceived = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } else { amountInSwapped = getToken1AmountInWei( token1AmtSwapped, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); amountOutReceived = getToken0AmountInWei( token0AmtSwapped, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); } // require minimum amount received is > min return require( amountOutReceived > minReturn, "One inch swap not enough output token amount" ); // require amount out > amount in * 98% // only for xU3LP require( xU3LP && amountOutReceived > amountInSwapped.sub(amountInSwapped.div(SWAP_SLIPPAGE * 2)), "One inch swap slippage > 2 %" ); } /** * Approve 1inch v3 for swaps */ function approveOneInch(IERC20 token0, IERC20 token1) public { token0.safeApprove(oneInchExchange, type(uint256).max); token1.safeApprove(oneInchExchange, type(uint256).max); } /* ========================================================================================= */ /* NFT Position Manager Helpers */ /* ========================================================================================= */ /** * @dev Returns the current liquidity in a position represented by tokenId NFT */ function getPositionLiquidity(address positionManager, uint256 tokenId) public view returns (uint128 liquidity) { (, , , , , , , liquidity, , , , ) = INonfungiblePositionManager( positionManager ) .positions(tokenId); } /** * @dev Stake liquidity in position represented by tokenId NFT */ function stake( uint256 amount0, uint256 amount1, address positionManager, uint256 tokenId ) public returns (uint256 stakedAmount0, uint256 stakedAmount1) { (, stakedAmount0, stakedAmount1) = INonfungiblePositionManager( positionManager ) .increaseLiquidity( INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Unstake liquidity from position represented by tokenId NFT * @dev using amount0 and amount1 instead of liquidity */ function unstake( uint256 amount0, uint256 amount1, PositionDetails memory positionDetails ) public returns (uint256 collected0, uint256 collected1) { uint128 liquidityAmount = getLiquidityForAmounts( amount0, amount1, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (uint256 _amount0, uint256 _amount1) = unstakePosition(liquidityAmount, positionDetails); return collectPosition( uint128(_amount0), uint128(_amount1), positionDetails.tokenId, positionDetails.positionManager ); } /** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */ function unstakePosition( uint128 liquidity, PositionDetails memory positionDetails ) public returns (uint256 amount0, uint256 amount1) { INonfungiblePositionManager positionManager = INonfungiblePositionManager(positionDetails.positionManager); (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity( liquidity, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: positionDetails.tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); } /** * @dev Collect token amounts from pool position */ function collectPosition( uint128 amount0, uint128 amount1, uint256 tokenId, address positionManager ) public returns (uint256 collected0, uint256 collected1) { (collected0, collected1) = INonfungiblePositionManager(positionManager) .collect( INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: amount0, amount1Max: amount1 }) ); } /** * @dev Creates the NFT token representing the pool position * @dev Mint initial liquidity */ function createPosition( uint256 amount0, uint256 amount1, address positionManager, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public returns (uint256 _tokenId) { (_tokenId, , , ) = INonfungiblePositionManager(positionManager).mint( INonfungiblePositionManager.MintParams({ token0: tokenDetails.token0, token1: tokenDetails.token1, fee: positionDetails.poolFee, tickLower: getTickFromPrice(positionDetails.priceLower), tickUpper: getTickFromPrice(positionDetails.priceUpper), amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); } /** * @dev burn NFT representing a pool position with tokenId * @dev uses NFT Position Manager */ function burn(address positionManager, uint256 tokenId) public { INonfungiblePositionManager(positionManager).burn(tokenId); } /* ========================================================================================= */ /* xU3LP / xAssetCLR Helpers */ /* ========================================================================================= */ function provideOrRemoveLiquidity( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private { (uint256 bufferToken0Balance, uint256 bufferToken1Balance) = getBufferTokenBalance(tokenDetails); (uint256 targetToken0Balance, uint256 targetToken1Balance) = getTargetBufferTokenBalance(tokenDetails, positionDetails); uint256 bufferBalance = bufferToken0Balance.add(bufferToken1Balance); uint256 targetBalance = targetToken0Balance.add(targetToken1Balance); uint256 amount0 = subAbs(bufferToken0Balance, targetToken0Balance); uint256 amount1 = subAbs(bufferToken1Balance, targetToken1Balance); amount0 = getToken0AmountInNativeDecimals( amount0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amount1 = getToken1AmountInNativeDecimals( amount1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); (amount0, amount1) = checkIfAmountsMatchAndSwap( true, amount0, amount1, positionDetails, tokenDetails ); if (amount0 == 0 || amount1 == 0) { return; } if (bufferBalance > targetBalance) { stake( amount0, amount1, positionDetails.positionManager, positionDetails.tokenId ); } else if (bufferBalance < targetBalance) { unstake(amount0, amount1, positionDetails); } } /** * @dev Admin function to stake tokens * @dev used in case there's leftover tokens in the contract */ function adminRebalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private { (uint256 token0Balance, uint256 token1Balance) = getBufferTokenBalance(tokenDetails); (uint256 stakeAmount0, uint256 stakeAmount1) = checkIfAmountsMatchAndSwap( false, token0Balance, token1Balance, positionDetails, tokenDetails ); require( stakeAmount0 != 0 && stakeAmount1 != 0, "Rebalance amounts are 0" ); stake( stakeAmount0, stakeAmount1, positionDetails.positionManager, positionDetails.tokenId ); } /** * @dev Check if token amounts match before attempting rebalance in xAssetCLR * @dev Uniswap contract requires deposits at a precise token ratio * @dev If they don't match, swap the tokens so as to deposit as much as possible * @param xU3LP true if called from xU3LP, false if from xAssetCLR * @param amount0ToMint how much token0 amount we want to deposit/withdraw * @param amount1ToMint how much token1 amount we want to deposit/withdraw */ function checkIfAmountsMatchAndSwap( bool xU3LP, uint256 amount0ToMint, uint256 amount1ToMint, PositionDetails memory positionDetails, TokenDetails memory tokenDetails ) public returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio = // minted liquidity / total pool liquidity // used to calculate swap impact in pool uint256 mintLiquidity = getLiquidityForAmounts( amount0ToMint, amount1ToMint, positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); uint256 poolLiquidity = getPoolLiquidity(positionDetails.pool); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( xU3LP, liquidityRatio, AmountsMinted({ amount0ToMint: amount0ToMint, amount1ToMint: amount1ToMint, amount0Minted: amount0Minted, amount1Minted: amount1Minted }), tokenDetails, positionDetails ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } } /** * @dev Swap tokens in xAssetCLR so as to keep a ratio which is required for * @dev depositing/withdrawing liquidity to/from Uniswap pool * @param xU3LP true if called from xU3LP, false if from xAssetCLR */ function restoreTokenRatios( bool xU3LP, int128 liquidityRatio, AmountsMinted memory amountsMinted, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private returns (uint256 amount0, uint256 amount1) { // after normalization, returned swap amount will be in wei representation uint256 swapAmount = Utils.calculateSwapAmount( getToken0AmountInWei( amountsMinted.amount0ToMint, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getToken1AmountInWei( amountsMinted.amount1ToMint, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), getToken0AmountInWei( amountsMinted.amount0Minted, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getToken1AmountInWei( amountsMinted.amount1Minted, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), liquidityRatio ); if (swapAmount == 0) { return (amountsMinted.amount0ToMint, amountsMinted.amount1ToMint); } uint256 swapAmountWithSlippage = swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)); uint256 mul1 = amountsMinted.amount0ToMint.mul(amountsMinted.amount1Minted); uint256 mul2 = amountsMinted.amount1ToMint.mul(amountsMinted.amount0Minted); (uint256 balance0, uint256 balance1) = getBufferTokenBalance(tokenDetails); if (mul1 > mul2) { if (balance0 < swapAmountWithSlippage) { // withdraw enough balance to swap withdrawSingleToken( true, swapAmountWithSlippage, tokenDetails, positionDetails ); xU3LP ? provideOrRemoveLiquidity(tokenDetails, positionDetails) : adminRebalance(tokenDetails, positionDetails); return (0, 0); } // Swap tokens swapToken0ForToken1( swapAmountWithSlippage, swapAmount, positionDetails.poolFee, positionDetails.router, tokenDetails ); amount0 = amountsMinted.amount0ToMint.sub( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); amount1 = amountsMinted.amount1ToMint.add( getToken1AmountInNativeDecimals( swapAmount, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } else if (mul1 < mul2) { if (balance1 < swapAmountWithSlippage) { // withdraw enough balance to swap withdrawSingleToken( false, swapAmountWithSlippage, tokenDetails, positionDetails ); provideOrRemoveLiquidity(tokenDetails, positionDetails); return (0, 0); } // Swap tokens swapToken1ForToken0( swapAmountWithSlippage, swapAmount, positionDetails.poolFee, positionDetails.router, tokenDetails ); amount0 = amountsMinted.amount0ToMint.add( getToken0AmountInNativeDecimals( swapAmount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) ); amount1 = amountsMinted.amount1ToMint.sub( getToken1AmountInNativeDecimals( swapAmount, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } } /** * @dev Withdraw until token0 or token1 balance reaches amount * @param forToken0 withdraw balance for token0 (true) or token1 (false) * @param amount minimum amount we want to have in token0 or token1 */ function withdrawSingleToken( bool forToken0, uint256 amount, TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) private { uint256 balance; uint256 unstakeAmount0; uint256 unstakeAmount1; uint256 swapAmount; IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); do { // calculate how much we can withdraw (unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts( getToken0AmountInNativeDecimals( amount, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getToken1AmountInNativeDecimals( amount, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ), positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); // withdraw both tokens unstake(unstakeAmount0, unstakeAmount1, positionDetails); // swap the excess amount of token0 for token1 or vice-versa swapAmount = forToken0 ? getToken1AmountInWei( unstakeAmount1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) : getToken0AmountInWei( unstakeAmount0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); forToken0 ? swapToken1ForToken0( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount, positionDetails.poolFee, positionDetails.router, tokenDetails ) : swapToken0ForToken1( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount, positionDetails.poolFee, positionDetails.router, tokenDetails ); balance = forToken0 ? getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ) : getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } while (balance < amount); } /** * @dev Get token balances in xU3LP/xAssetCLR contract * @dev returned balances are in wei representation */ function getBufferTokenBalance(TokenDetails memory tokenDetails) public view returns (uint256 amount0, uint256 amount1) { IERC20 token0 = IERC20(tokenDetails.token0); IERC20 token1 = IERC20(tokenDetails.token1); return ( getBufferToken0Balance( token0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ), getBufferToken1Balance( token1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ) ); } // Get token balances in the position function getStakedTokenBalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = getAmountsForLiquidity( getPositionLiquidity( positionDetails.positionManager, positionDetails.tokenId ), positionDetails.priceLower, positionDetails.priceUpper, positionDetails.pool ); amount0 = getToken0AmountInWei( amount0, tokenDetails.token0Decimals, tokenDetails.token0DecimalMultiplier ); amount1 = getToken1AmountInWei( amount1, tokenDetails.token1Decimals, tokenDetails.token1DecimalMultiplier ); } // Get wanted xU3LP contract token balance - 5% of NAV function getTargetBufferTokenBalance( TokenDetails memory tokenDetails, PositionDetails memory positionDetails ) public view returns (uint256 amount0, uint256 amount1) { (uint256 bufferAmount0, uint256 bufferAmount1) = getBufferTokenBalance(tokenDetails); (uint256 poolAmount0, uint256 poolAmount1) = getStakedTokenBalance(tokenDetails, positionDetails); amount0 = bufferAmount0.add(poolAmount0).div(BUFFER_TARGET); amount1 = bufferAmount1.add(poolAmount1).div(BUFFER_TARGET); // Keep 50:50 ratio amount0 = amount0.add(amount1).div(2); amount1 = amount0; } /** * @dev Get token0 balance in xAssetCLR */ function getBufferToken0Balance( IERC20 token0, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public view returns (uint256 amount0) { return getToken0AmountInWei( token0.balanceOf(address(this)), token0Decimals, token0DecimalMultiplier ); } /** * @dev Get token1 balance in xAssetCLR */ function getBufferToken1Balance( IERC20 token1, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public view returns (uint256 amount1) { return getToken1AmountInWei( token1.balanceOf(address(this)), token1Decimals, token1DecimalMultiplier ); } /* ========================================================================================= */ /* Miscellaneous */ /* ========================================================================================= */ /** * @dev Returns token0 amount in token0Decimals */ function getToken0AmountInNativeDecimals( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in token1Decimals */ function getToken1AmountInNativeDecimals( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.div(token1DecimalMultiplier); } return amount; } /** * @dev Returns token0 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken0AmountInWei( uint256 amount, uint8 token0Decimals, uint256 token0DecimalMultiplier ) public pure returns (uint256) { if (token0Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token0DecimalMultiplier); } return amount; } /** * @dev Returns token1 amount in TOKEN_DECIMAL_REPRESENTATION */ function getToken1AmountInWei( uint256 amount, uint8 token1Decimals, uint256 token1DecimalMultiplier ) public pure returns (uint256) { if (token1Decimals < TOKEN_DECIMAL_REPRESENTATION) { amount = amount.mul(token1DecimalMultiplier); } return amount; } /** * @dev get price from tick */ function getSqrtRatio(int24 tick) public pure returns (uint160) { return TickMath.getSqrtRatioAtTick(tick); } /** * @dev get tick from price */ function getTickFromPrice(uint160 price) public pure returns (int24) { return TickMath.getTickAtSqrtRatio(price); } /** * @dev Subtract two numbers and return absolute value */ function subAbs(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : amount1.sub(amount0); } // Subtract two numbers and return 0 if result is < 0 function sub0(uint256 amount0, uint256 amount1) public pure returns (uint256) { return amount0 >= amount1 ? amount0.sub(amount1) : 0; } function calculateFee(uint256 _value, uint256 _feeDivisor) public pure returns (uint256 fee) { if (_feeDivisor > 0) { fee = _value.div(_feeDivisor); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; function lock(address _address) internal { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } modifier notLocked(address lockedAddress) { require(lastLockedBlock[lockedAddress] <= block.number); _; } } //SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.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) { // 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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @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 { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xc02f72e8ae5e68802e6d893d58ddfb0df89a2f4c9c2f04927db1186a29373660; /// @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 ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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 ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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 ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @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 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, 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); }
Check how much xU3LP tokens will be minted
function calculateMintAmount(uint256 _amount, uint256 totalSupply) public view returns (uint256 mintAmount) { if (totalSupply == 0) return _amount.mul(INITIAL_SUPPLY_MULTIPLIER); uint256 previousNav = getNav().sub(_amount); mintAmount = (_amount).mul(totalSupply).div(previousNav); return mintAmount; }
11,924,286
./full_match/1/0x4AaADe11879f991ACD485E10d2D52a3587B304B7/sources/contracts/Global/AuthorityModel.sol
____________________________________________________________________________________________________________________ -->ACCESS CONTROL (function) grantReviewAdmin Allows the super user Default Admin to add an address to the review admin group. --------------------------------------------------------------------------------------------------------------------- newReviewAdmin_ The address of the new review admin --------------------------------------------------------------------------------------------------------------------- _____________________________________________________________________________________________________________________/
function grantReviewAdmin(address newReviewAdmin_) public onlySuperAdmin { if (newReviewAdmin_ == address(0)) { _revert(ReviewAdminCannotBeAddressZero.selector); } emit ReviewAdminAdded(newReviewAdmin_); }
8,477,093
./full_match/5/0x96923a67F0CB42Fb25F879c9aa9b1eDf1c704cB0/sources/contracts/thirdweb-wallet/Account.sol
/// Approves a signer to be able to call `_selector` function on `_target` smart contract.
Approve non-admin signers for function calls. function approveSignerForTarget( address _signer, bytes4 _selector, address _target ) external onlySelf { bytes32 targetHash = keccak256(abi.encode(_selector, _target)); bool currentApproval = isApprovedFor[_signer][targetHash]; require(!currentApproval, "Account: already approved."); isApprovedFor[_signer][targetHash] = true; callTargets[_signer].push(CallTarget(_selector, _target)); emit TargetApprovedForSigner(_signer, _selector, _target, true); }
11,621,587
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.8.7; interface IERC20Like { function approve(address spender_, uint256 amount_) external returns (bool success_); function balanceOf(address account_) external view returns (uint256 balance_); function transfer(address recipient_, uint256 amount_) external returns (bool success_); function transferFrom(address owner_, address recipient_, uint256 amount_) external returns (bool success_); } interface ILenderLike { function poolDelegate() external view returns (address poolDelegate_); } interface IMapleGlobalsLike { function investorFee() external view returns (uint256 investorFee_); function mapleTreasury() external view returns (address mapleTreasury_); function protocolPaused() external view returns (bool paused_); function treasuryFee() external view returns (uint256 treasuryFee_); } interface IMapleProxyFactoryLike { function mapleGlobals() external view returns (address mapleGlobals_); function upgradeInstance(uint256 toVersion_, bytes calldata arguments_) external; } /// @title Small Library to standardize erc20 token interactions. library ERC20Helper { /**************************/ /*** Internal Functions ***/ /**************************/ function transfer(address token_, address to_, uint256 amount_) internal returns (bool success_) { return _call(token_, abi.encodeWithSelector(IERC20Like.transfer.selector, to_, amount_)); } function transferFrom(address token_, address from_, address to_, uint256 amount_) internal returns (bool success_) { return _call(token_, abi.encodeWithSelector(IERC20Like.transferFrom.selector, from_, to_, amount_)); } function approve(address token_, address spender_, uint256 amount_) internal returns (bool success_) { // If setting approval to zero fails, return false. if (!_call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, uint256(0)))) return false; // If `amount_` is zero, return true as the previous step already did this. if (amount_ == uint256(0)) return true; // Return the result of setting the approval to `amount_`. return _call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, amount_)); } function _call(address token_, bytes memory data_) private returns (bool success_) { if (token_.code.length == uint256(0)) return false; bytes memory returnData; ( success_, returnData ) = token_.call(data_); return success_ && (returnData.length == uint256(0) || abi.decode(returnData, (bool))); } } /// @title An implementation that is to be proxied, must implement IProxied. interface IProxied { /** * @dev The address of the proxy factory. */ function factory() external view returns (address factory_); /** * @dev The address of the implementation contract being proxied. */ function implementation() external view returns (address implementation_); /** * @dev Modifies the proxy's implementation address. * @param newImplementation_ The address of an implementation contract. */ function setImplementation(address newImplementation_) external; /** * @dev Modifies the proxy's storage by delegate-calling a migrator contract with some arguments. * Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled. * @param migrator_ The address of a migrator contract. * @param arguments_ Some encoded arguments to use for the migration. */ function migrate(address migrator_, bytes calldata arguments_) external; } /// @title A Maple implementation that is to be proxied, must implement IMapleProxied. interface IMapleProxied is IProxied { /** * @dev The instance was upgraded. * @param toVersion_ The new version of the loan. * @param arguments_ The upgrade arguments, if any. */ event Upgraded(uint256 toVersion_, bytes arguments_); /** * @dev Upgrades a contract implementation to a specific version. * Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled. * @param toVersion_ The version to upgrade to. * @param arguments_ Some encoded arguments to use for the upgrade. */ function upgrade(uint256 toVersion_, bytes calldata arguments_) external; } /// @title IMapleLoanEvents defines the events for a MapleLoan. interface IMapleLoanEvents { /** * @dev Borrower was accepted, and set to a new account. * @param borrower_ The address of the new borrower. */ event BorrowerAccepted(address indexed borrower_); /** * @dev Collateral was posted. * @param amount_ The amount of collateral posted. */ event CollateralPosted(uint256 amount_); /** * @dev Collateral was removed. * @param amount_ The amount of collateral removed. * @param destination_ The recipient of the collateral removed. */ event CollateralRemoved(uint256 amount_, address indexed destination_); /** * @dev The loan was funded. * @param lender_ The address of the lender. * @param amount_ The amount funded. * @param nextPaymentDueDate_ The due date of the next payment. */ event Funded(address indexed lender_, uint256 amount_, uint256 nextPaymentDueDate_); /** * @dev Funds were claimed. * @param amount_ The amount of funds claimed. * @param destination_ The recipient of the funds claimed. */ event FundsClaimed(uint256 amount_, address indexed destination_); /** * @dev Funds were drawn. * @param amount_ The amount of funds drawn. * @param destination_ The recipient of the funds drawn down. */ event FundsDrawnDown(uint256 amount_, address indexed destination_); /** * @dev Funds were redirected on an additional `fundLoan` call. * @param amount_ The amount of funds redirected. * @param destination_ The recipient of the redirected funds. */ event FundsRedirected(uint256 amount_, address indexed destination_); /** * @dev Funds were returned. * @param amount_ The amount of funds returned. */ event FundsReturned(uint256 amount_); /** * @dev The loan was initialized. * @param borrower_ The address of the borrower. * @param assets_ Array of asset addresses. * [0]: collateralAsset, * [1]: fundsAsset. * @param termDetails_ Array of loan parameters: * [0]: gracePeriod, * [1]: paymentInterval, * [2]: payments, * @param amounts_ Requested amounts: * [0]: collateralRequired, * [1]: principalRequested, * [2]: endingPrincipal. * @param rates_ Fee parameters: * [0]: interestRate, * [1]: earlyFeeRate, * [2]: lateFeeRate, * [3]: lateInterestPremium. */ event Initialized(address indexed borrower_, address[2] assets_, uint256[3] termDetails_, uint256[3] amounts_, uint256[4] rates_); /** * @dev Lender was accepted, and set to a new account. * @param lender_ The address of the new lender. */ event LenderAccepted(address indexed lender_); /** * @dev Loan was repaid early and closed. * @param principalPaid_ The portion of the total amount that went towards principal. * @param interestPaid_ The portion of the total amount that went towards interest fees. */ event LoanClosed(uint256 principalPaid_, uint256 interestPaid_); /** * @dev A refinance was proposed. * @param refinanceCommitment_ The hash of the refinancer and calls proposed. * @param refinancer_ The address that will execute the refinance. * @param calls_ The individual calls for the refinancer contract. */ event NewTermsAccepted(bytes32 refinanceCommitment_, address refinancer_, bytes[] calls_); /** * @dev A refinance was proposed. * @param refinanceCommitment_ The hash of the refinancer and calls proposed. * @param refinancer_ The address that will execute the refinance. * @param calls_ The individual calls for the refinancer contract. */ event NewTermsProposed(bytes32 refinanceCommitment_, address refinancer_, bytes[] calls_); /** * @dev Payments were made. * @param principalPaid_ The portion of the total amount that went towards principal. * @param interestPaid_ The portion of the total amount that went towards interest fees. */ event PaymentMade(uint256 principalPaid_, uint256 interestPaid_); /** * @dev Pending borrower was set. * @param pendingBorrower_ Address that can accept the borrower role. */ event PendingBorrowerSet(address pendingBorrower_); /** * @dev Pending lender was set. * @param pendingLender_ Address that can accept the lender role. */ event PendingLenderSet(address pendingLender_); /** * @dev The loan was in default and funds and collateral was repossessed by the lender. * @param collateralRepossessed_ The amount of collateral asset repossessed. * @param fundsRepossessed_ The amount of funds asset repossessed. * @param destination_ The recipient of the collateral and funds, if any. */ event Repossessed(uint256 collateralRepossessed_, uint256 fundsRepossessed_, address indexed destination_); /** * @dev Some token (neither fundsAsset nor collateralAsset) was removed from the loan. * @param token_ The address of the token contract. * @param amount_ The amount of token remove from the loan. * @param destination_ The recipient of the token. */ event Skimmed(address indexed token_, uint256 amount_, address indexed destination_); } /// @title MapleLoan implements a primitive loan with additional functionality, and is intended to be proxied. interface IMapleLoan is IMapleProxied, IMapleLoanEvents { /***********************/ /*** State Variables ***/ /***********************/ /** * @dev The borrower of the loan, responsible for repayments. */ function borrower() external view returns (address borrower_); /** * @dev The amount of funds that have yet to be claimed by the lender. */ function claimableFunds() external view returns (uint256 claimableFunds_); /** * @dev The amount of collateral posted against outstanding (drawn down) principal. */ function collateral() external view returns (uint256 collateral_); /** * @dev The address of the asset deposited by the borrower as collateral, if needed. */ function collateralAsset() external view returns (address collateralAsset_); /** * @dev The amount of collateral required if all of the principal required is drawn down. */ function collateralRequired() external view returns (uint256 collateralRequired_); /** * @dev The amount of funds that have yet to be drawn down by the borrower. */ function drawableFunds() external view returns (uint256 drawableFunds_); /** * @dev The rate charged at early payments. * This value should be configured so that it is less expensive to close a loan with more than one payment remaining, but * more expensive to close it if on the last payment. */ function earlyFeeRate() external view returns (uint256 earlyFeeRate_); /** * @dev The portion of principal to not be paid down as part of payment installments, which would need to be paid back upon final payment. * If endingPrincipal = principal, loan is interest-only. */ function endingPrincipal() external view returns (uint256 endingPrincipal_); /** * @dev The asset deposited by the lender to fund the loan. */ function fundsAsset() external view returns (address fundsAsset_); /** * @dev The amount of time the borrower has, after a payment is due, to make a payment before being in default. */ function gracePeriod() external view returns (uint256 gracePeriod_); /** * @dev The annualized interest rate (APR), in units of 1e18, (i.e. 1% is 0.01e18). */ function interestRate() external view returns (uint256 interestRate_); /** * @dev The rate charged at late payments. */ function lateFeeRate() external view returns (uint256 lateFeeRate_); /** * @dev The premium over the regular interest rate applied when paying late. */ function lateInterestPremium() external view returns (uint256 lateInterestPremium_); /** * @dev The lender of the Loan. */ function lender() external view returns (address lender_); /** * @dev The timestamp due date of the next payment. */ function nextPaymentDueDate() external view returns (uint256 nextPaymentDueDate_); /** * @dev The specified time between loan payments. */ function paymentInterval() external view returns (uint256 paymentInterval_); /** * @dev The number of payment installments remaining for the loan. */ function paymentsRemaining() external view returns (uint256 paymentsRemaining_); /** * @dev The address of the pending borrower. */ function pendingBorrower() external view returns (address pendingBorrower_); /** * @dev The address of the pending lender. */ function pendingLender() external view returns (address pendingLender_); /** * @dev The amount of principal owed (initially, the requested amount), which needs to be paid back. */ function principal() external view returns (uint256 principal_); /** * @dev The initial principal amount requested by the borrower. */ function principalRequested() external view returns (uint256 principalRequested_); /** * @dev The factory address that deployed this contract (necessary for PoolV1 integration). */ function superFactory() external view returns (address superFactory_); /********************************/ /*** State Changing Functions ***/ /********************************/ /** * @dev Accept the borrower role, must be called by pendingBorrower. */ function acceptBorrower() external; /** * @dev Accept the lender role, must be called by pendingLender. */ function acceptLender() external; /** * @dev Accept the proposed terms ans trigger refinance execution * @param refinancer_ The address of the refinancer contract. * @param calls_ The encoded arguments to be passed to refinancer. * @param amount_ An amount to pull from the caller, if any. */ function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external; /** * @dev Claim funds that have been paid (principal, interest, and late fees). * @param amount_ The amount to be claimed. * @param destination_ The address to send the funds. */ function claimFunds(uint256 amount_, address destination_) external; /** * @dev Repay all principal and fees and close a loan. * @param amount_ An amount to pull from the caller, if any. * @return principal_ The portion of the amount paid paying back principal. * @return interest_ The portion of the amount paid paying interest fees. */ function closeLoan(uint256 amount_) external returns (uint256 principal_, uint256 interest_); /** * @dev Draw down funds from the loan. * @param amount_ The amount to draw down. * @param destination_ The address to send the funds. * @return collateralPosted_ The amount of additional collateral posted, if any. */ function drawdownFunds(uint256 amount_, address destination_) external returns (uint256 collateralPosted_); /** * @dev Lend funds to the loan/borrower. * @param lender_ The address to be registered as the lender. * @param amount_ An amount to pull from the caller, if any. * @return fundsLent_ The amount funded. */ function fundLoan(address lender_, uint256 amount_) external returns (uint256 fundsLent_); /** * @dev Make a payment to the loan. * @param amount_ An amount to pull from the caller, if any. * @return principal_ The portion of the amount paid paying back principal. * @return interest_ The portion of the amount paid paying interest fees. */ function makePayment(uint256 amount_) external returns (uint256 principal_, uint256 interest_); /** * @dev Post collateral to the loan. * @param amount_ An amount to pull from the caller, if any. * @return collateralPosted_ The amount posted. */ function postCollateral(uint256 amount_) external returns (uint256 collateralPosted_); /** * @dev Propose new terms for refinance * @param refinancer_ The address of the refinancer contract. * @param calls_ The encoded arguments to be passed to refinancer. */ function proposeNewTerms(address refinancer_, bytes[] calldata calls_) external; /** * @dev Remove collateral from the loan (opposite of posting collateral). * @param amount_ The amount removed. * @param destination_ The destination to send the removed collateral. */ function removeCollateral(uint256 amount_, address destination_) external; /** * @dev Return funds to the loan (opposite of drawing down). * @param amount_ An amount to pull from the caller, if any. * @return fundsReturned_ The amount returned. */ function returnFunds(uint256 amount_) external returns (uint256 fundsReturned_); /** * @dev Repossess collateral, and any funds, for a loan in default. * @param destination_ The address where the collateral and funds asset is to be sent, if any. * @return collateralRepossessed_ The amount of collateral asset repossessed. * @return fundsRepossessed_ The amount of funds asset repossessed. */ function repossess(address destination_) external returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_); /** * @dev Set the pendingBorrower to a new account. * @param pendingBorrower_ The address of the new pendingBorrower. */ function setPendingBorrower(address pendingBorrower_) external; /** * @dev Set the pendingLender to a new account. * @param pendingLender_ The address of the new pendingLender. */ function setPendingLender(address pendingLender_) external; /** * @dev Remove some token (neither fundsAsset nor collateralAsset) from the loan. * @param token_ The address of the token contract. * @param destination_ The recipient of the token. * @return skimmed_ The amount of token removed from the loan. */ function skim(address token_, address destination_) external returns (uint256 skimmed_); /**********************/ /*** View Functions ***/ /**********************/ /** * @dev Returns the excess collateral that can be removed. * @return excessCollateral_ The excess collateral that can be removed, if any. */ function excessCollateral() external view returns (uint256 excessCollateral_); /** * @dev Get the additional collateral to be posted to drawdown some amount. * @param drawdown_ The amount desired to be drawn down. * @return additionalCollateral_ The additional collateral that must be posted, if any. */ function getAdditionalCollateralRequiredFor(uint256 drawdown_) external view returns (uint256 additionalCollateral_); /** * @dev Get the breakdown of the total payment needed to satisfy an early repayment. * @return totalPrincipalAmount_ The portion of the total amount that will go towards principal. * @return totalInterestFees_ The portion of the total amount that will go towards interest fees. */ function getEarlyPaymentBreakdown() external view returns ( uint256 totalPrincipalAmount_, uint256 totalInterestFees_ ); /** * @dev Get the breakdown of the total payment needed to satisfy `numberOfPayments` payment installments. * @return totalPrincipalAmount_ The portion of the total amount that will go towards principal. * @return totalInterestFees_ The portion of the total amount that will go towards interest fees. */ function getNextPaymentBreakdown() external view returns ( uint256 totalPrincipalAmount_, uint256 totalInterestFees_ ); /** * @dev Returns whether the protocol is paused. * @return paused_ A boolean indicating if protocol is paused. */ function isProtocolPaused() external view returns (bool paused_); } abstract contract SlotManipulatable { function _getReferenceTypeSlot(bytes32 slot_, bytes32 key_) internal pure returns (bytes32 value_) { return keccak256(abi.encodePacked(key_, slot_)); } function _getSlotValue(bytes32 slot_) internal view returns (bytes32 value_) { assembly { value_ := sload(slot_) } } function _setSlotValue(bytes32 slot_, bytes32 value_) internal { assembly { sstore(slot_, value_) } } } /// @title An implementation that is to be proxied, will need ProxiedInternals. abstract contract ProxiedInternals is SlotManipulatable { /// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.factory') - 1`. bytes32 private constant FACTORY_SLOT = bytes32(0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1); /// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.implementation') - 1`. bytes32 private constant IMPLEMENTATION_SLOT = bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc); /// @dev Delegatecalls to a migrator contract to manipulate storage during an initialization or migration. function _migrate(address migrator_, bytes calldata arguments_) internal virtual returns (bool success_) { uint256 size; assembly { size := extcodesize(migrator_) } if (size == uint256(0)) return false; ( success_, ) = migrator_.delegatecall(arguments_); } /// @dev Sets the factory address in storage. function _setFactory(address factory_) internal virtual returns (bool success_) { _setSlotValue(FACTORY_SLOT, bytes32(uint256(uint160(factory_)))); return true; } /// @dev Sets the implementation address in storage. function _setImplementation(address implementation_) internal virtual returns (bool success_) { _setSlotValue(IMPLEMENTATION_SLOT, bytes32(uint256(uint160(implementation_)))); return true; } /// @dev Returns the factory address. function _factory() internal view virtual returns (address factory_) { return address(uint160(uint256(_getSlotValue(FACTORY_SLOT)))); } /// @dev Returns the implementation address. function _implementation() internal view virtual returns (address implementation_) { return address(uint160(uint256(_getSlotValue(IMPLEMENTATION_SLOT)))); } } /// @title A Maple implementation that is to be proxied, will need MapleProxiedInternals. abstract contract MapleProxiedInternals is ProxiedInternals {} /// @title MapleLoanInternals defines the storage layout and internal logic of MapleLoan. abstract contract MapleLoanInternals is MapleProxiedInternals { uint256 private constant SCALED_ONE = uint256(10 ** 18); // Roles address internal _borrower; // The address of the borrower. address internal _lender; // The address of the lender. address internal _pendingBorrower; // The address of the pendingBorrower, the only address that can accept the borrower role. address internal _pendingLender; // The address of the pendingLender, the only address that can accept the lender role. // Assets address internal _collateralAsset; // The address of the asset used as collateral. address internal _fundsAsset; // The address of the asset used as funds. // Loan Term Parameters uint256 internal _gracePeriod; // The number of seconds a payment can be late. uint256 internal _paymentInterval; // The number of seconds between payments. // Rates uint256 internal _interestRate; // The annualized interest rate of the loan. uint256 internal _earlyFeeRate; // The fee rate for prematurely closing loans. uint256 internal _lateFeeRate; // The fee rate for late payments. uint256 internal _lateInterestPremium; // The amount to increase the interest rate by for late payments. // Requested Amounts uint256 internal _collateralRequired; // The collateral the borrower is expected to put up to draw down all _principalRequested. uint256 internal _principalRequested; // The funds the borrowers wants to borrow. uint256 internal _endingPrincipal; // The principal to remain at end of loan. // State uint256 internal _drawableFunds; // The amount of funds that can be drawn down. uint256 internal _claimableFunds; // The amount of funds that the lender can claim (principal repayments, interest, etc). uint256 internal _collateral; // The amount of collateral, in collateral asset, that is currently posted. uint256 internal _nextPaymentDueDate; // The timestamp of due date of next payment. uint256 internal _paymentsRemaining; // The number of payments remaining. uint256 internal _principal; // The amount of principal yet to be paid down. // Refinance bytes32 internal _refinanceCommitment; /**********************************/ /*** Internal General Functions ***/ /**********************************/ /// @dev Clears all state variables to end a loan, but keep borrower and lender withdrawal functionality intact. function _clearLoanAccounting() internal { _gracePeriod = uint256(0); _paymentInterval = uint256(0); _interestRate = uint256(0); _earlyFeeRate = uint256(0); _lateFeeRate = uint256(0); _lateInterestPremium = uint256(0); _endingPrincipal = uint256(0); _nextPaymentDueDate = uint256(0); _paymentsRemaining = uint256(0); _principal = uint256(0); } /** * @dev Initializes the loan. * @param borrower_ The address of the borrower. * @param assets_ Array of asset addresses. * [0]: collateralAsset, * [1]: fundsAsset. * @param termDetails_ Array of loan parameters: * [0]: gracePeriod, * [1]: paymentInterval, * [2]: payments, * @param amounts_ Requested amounts: * [0]: collateralRequired, * [1]: principalRequested, * [2]: endingPrincipal. * @param rates_ Fee parameters: * [0]: interestRate, * [1]: earlyFeeRate, * [2]: lateFeeRate, * [3]: lateInterestPremium. */ function _initialize( address borrower_, address[2] memory assets_, uint256[3] memory termDetails_, uint256[3] memory amounts_, uint256[4] memory rates_ ) internal { // Principal requested needs to be non-zero (see `_getCollateralRequiredFor` math). require(amounts_[1] > uint256(0), "MLI:I:INVALID_PRINCIPAL"); // Ending principal needs to be less than or equal to principal requested. require(amounts_[2] <= amounts_[1], "MLI:I:INVALID_ENDING_PRINCIPAL"); require((_borrower = borrower_) != address(0), "MLI:I:INVALID_BORROWER"); _collateralAsset = assets_[0]; _fundsAsset = assets_[1]; _gracePeriod = termDetails_[0]; _paymentInterval = termDetails_[1]; _paymentsRemaining = termDetails_[2]; _collateralRequired = amounts_[0]; _principalRequested = amounts_[1]; _endingPrincipal = amounts_[2]; _interestRate = rates_[0]; _earlyFeeRate = rates_[1]; _lateFeeRate = rates_[2]; _lateInterestPremium = rates_[3]; } /**************************************/ /*** Internal Borrow-side Functions ***/ /**************************************/ /// @dev Prematurely ends a loan by making all remaining payments. function _closeLoan() internal returns (uint256 principal_, uint256 interest_) { require(block.timestamp <= _nextPaymentDueDate, "MLI:CL:PAYMENT_IS_LATE"); ( principal_, interest_ ) = _getEarlyPaymentBreakdown(); uint256 totalPaid = principal_ + interest_; // The drawable funds are increased by the extra funds in the contract, minus the total needed for payment. _drawableFunds = _drawableFunds + _getUnaccountedAmount(_fundsAsset) - totalPaid; _claimableFunds += totalPaid; _clearLoanAccounting(); } /// @dev Sends `amount_` of `_drawableFunds` to `destination_`. function _drawdownFunds(uint256 amount_, address destination_) internal { _drawableFunds -= amount_; require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:DF:TRANSFER_FAILED"); require(_isCollateralMaintained(), "MLI:DF:INSUFFICIENT_COLLATERAL"); } /// @dev Makes a payment to progress the loan closer to maturity. function _makePayment() internal returns (uint256 principal_, uint256 interest_) { ( principal_, interest_ ) = _getNextPaymentBreakdown(); uint256 totalPaid = principal_ + interest_; // The drawable funds are increased by the extra funds in the contract, minus the total needed for payment. // NOTE: This line will revert if not enough funds were added for the full payment amount. _drawableFunds = (_drawableFunds + _getUnaccountedAmount(_fundsAsset)) - totalPaid; _claimableFunds += totalPaid; uint256 paymentsRemaining = _paymentsRemaining; if (paymentsRemaining == uint256(1)) { _clearLoanAccounting(); // Assumes `_getNextPaymentBreakdown` returns a `principal_` that is `_principal`. } else { _nextPaymentDueDate += _paymentInterval; _principal -= principal_; _paymentsRemaining = paymentsRemaining - uint256(1); } } /// @dev Registers the delivery of an amount of collateral to be posted. function _postCollateral() internal returns (uint256 collateralPosted_) { _collateral += (collateralPosted_ = _getUnaccountedAmount(_collateralAsset)); } /// @dev Sets refinance commitment given refinance operations. function _proposeNewTerms(address refinancer_, bytes[] calldata calls_) internal returns (bytes32 proposedRefinanceCommitment_) { // NOTE: There is no way to invalidate the `refinanceCommitment` (i.e. bytes32(0)) without explicitly setting it if `calls_.length` is 0. return _refinanceCommitment = calls_.length > uint256(0) ? _getRefinanceCommitment(refinancer_, calls_) : bytes32(0); } /// @dev Sends `amount_` of `_collateral` to `destination_`. function _removeCollateral(uint256 amount_, address destination_) internal { _collateral -= amount_; require(ERC20Helper.transfer(_collateralAsset, destination_, amount_), "MLI:RC:TRANSFER_FAILED"); require(_isCollateralMaintained(), "MLI:RC:INSUFFICIENT_COLLATERAL"); } /// @dev Registers the delivery of an amount of funds to be returned as `_drawableFunds`. function _returnFunds() internal returns (uint256 fundsReturned_) { _drawableFunds += (fundsReturned_ = _getUnaccountedAmount(_fundsAsset)); } /************************************/ /*** Internal Lend-side Functions ***/ /************************************/ /// @dev Processes refinance operations. function _acceptNewTerms(address refinancer_, bytes[] calldata calls_) internal returns (bytes32 acceptedRefinanceCommitment_) { // NOTE: A zero refinancer address and/or empty calls array will never (probabilistically) match a refinance commitment in storage. require(_refinanceCommitment == (acceptedRefinanceCommitment_ = _getRefinanceCommitment(refinancer_, calls_)), "MLI:ANT:COMMITMENT_MISMATCH"); require(refinancer_.code.length != uint256(0), "MLI:ANT:INVALID_REFINANCER"); // Clear refinance commitment to prevent implications of re-acceptance of another call to `_acceptNewTerms`. _refinanceCommitment = bytes32(0); uint256 callCount = calls_.length; for (uint256 i; i < callCount; ++i) { ( bool success, ) = refinancer_.delegatecall(calls_[i]); require(success, "MLI:ANT:FAILED"); } // Ensure that collateral is maintained after changes made. require(_isCollateralMaintained(), "MLI:ANT:INSUFFICIENT_COLLATERAL"); } /// @dev Sends `amount_` of `_claimableFunds` to `destination_`. /// If `amount_` is higher than `_claimableFunds` the transaction will underflow and revert. function _claimFunds(uint256 amount_, address destination_) internal { _claimableFunds -= amount_; require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:CF:TRANSFER_FAILED"); } /// @dev Fund the loan and kick off the repayment requirements. function _fundLoan(address lender_) internal returns (uint256 fundsLent_) { uint256 paymentsRemaining = _paymentsRemaining; // Can only fund loan if there are payments remaining (as defined by the initialization) and no payment is due yet (as set by a funding). require((_nextPaymentDueDate == uint256(0)) && (paymentsRemaining != uint256(0)), "MLI:FL:LOAN_ACTIVE"); uint256 paymentInterval = _paymentInterval; // NOTE: Don't need to check if lender_ is nonzero or valid, since it is done implicitly in calls to `lender_` below. _lender = lender_; _nextPaymentDueDate = block.timestamp + paymentInterval; // Amount funded and principal are as requested. fundsLent_ = _principal = _principalRequested; address fundsAsset = _fundsAsset; // Cannot under-fund loan, but over-funding results in additional funds left unaccounted for. require(_getUnaccountedAmount(fundsAsset) >= fundsLent_, "MLI:FL:WRONG_FUND_AMOUNT"); IMapleGlobalsLike globals = IMapleGlobalsLike(IMapleProxyFactoryLike(_factory()).mapleGlobals()); // Transfer the annualized treasury fee, if any, to the Maple treasury, and decrement drawable funds. uint256 treasuryFee = (fundsLent_ * globals.treasuryFee() * paymentInterval * paymentsRemaining) / uint256(365 days * 10_000); // Transfer delegate fee, if any, to the pool delegate, and decrement drawable funds. uint256 delegateFee = (fundsLent_ * globals.investorFee() * paymentInterval * paymentsRemaining) / uint256(365 days * 10_000); // Drawable funds is the amount funded, minus any fees. _drawableFunds = fundsLent_ - treasuryFee - delegateFee; require( treasuryFee == uint256(0) || ERC20Helper.transfer(fundsAsset, globals.mapleTreasury(), treasuryFee), "MLI:FL:T_TRANSFER_FAILED" ); require( delegateFee == uint256(0) || ERC20Helper.transfer(fundsAsset, ILenderLike(lender_).poolDelegate(), delegateFee), "MLI:FL:PD_TRANSFER_FAILED" ); } /// @dev Reset all state variables in order to release funds and collateral of a loan in default. function _repossess(address destination_) internal returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_) { uint256 nextPaymentDueDate = _nextPaymentDueDate; require( nextPaymentDueDate != uint256(0) && (block.timestamp > nextPaymentDueDate + _gracePeriod), "MLI:R:NOT_IN_DEFAULT" ); _clearLoanAccounting(); // Uniquely in `_repossess`, stop accounting for all funds so that they can be swept. _collateral = uint256(0); _claimableFunds = uint256(0); _drawableFunds = uint256(0); address collateralAsset = _collateralAsset; // Either there is no collateral to repossess, or the transfer of the collateral succeeds. require( (collateralRepossessed_ = _getUnaccountedAmount(collateralAsset)) == uint256(0) || ERC20Helper.transfer(collateralAsset, destination_, collateralRepossessed_), "MLI:R:C_TRANSFER_FAILED" ); address fundsAsset = _fundsAsset; // Either there are no funds to repossess, or the transfer of the funds succeeds. require( (fundsRepossessed_ = _getUnaccountedAmount(fundsAsset)) == uint256(0) || ERC20Helper.transfer(fundsAsset, destination_, fundsRepossessed_), "MLI:R:F_TRANSFER_FAILED" ); } /*******************************/ /*** Internal View Functions ***/ /*******************************/ /// @dev Returns whether the amount of collateral posted is commensurate with the amount of drawn down (outstanding) principal. function _isCollateralMaintained() internal view returns (bool isMaintained_) { return _collateral >= _getCollateralRequiredFor(_principal, _drawableFunds, _principalRequested, _collateralRequired); } /// @dev Get principal and interest breakdown for paying off the entire loan early. function _getEarlyPaymentBreakdown() internal view returns (uint256 principal_, uint256 interest_) { interest_ = ((principal_ = _principal) * _earlyFeeRate) / SCALED_ONE; } /// @dev Get principal and interest breakdown for next standard payment. function _getNextPaymentBreakdown() internal view returns (uint256 principal_, uint256 interest_) { ( principal_, interest_ ) = _getPaymentBreakdown( block.timestamp, _nextPaymentDueDate, _paymentInterval, _principal, _endingPrincipal, _paymentsRemaining, _interestRate, _lateFeeRate, _lateInterestPremium ); } /// @dev Returns the amount of an `asset_` that this contract owns, which is not currently accounted for by its state variables. function _getUnaccountedAmount(address asset_) internal view virtual returns (uint256 unaccountedAmount_) { return IERC20Like(asset_).balanceOf(address(this)) - (asset_ == _collateralAsset ? _collateral : uint256(0)) // `_collateral` is `_collateralAsset` accounted for. - (asset_ == _fundsAsset ? _claimableFunds + _drawableFunds : uint256(0)); // `_claimableFunds` and `_drawableFunds` are `_fundsAsset` accounted for. } /*******************************/ /*** Internal Pure Functions ***/ /*******************************/ /// @dev Returns the total collateral to be posted for some drawn down (outstanding) principal and overall collateral ratio requirement. function _getCollateralRequiredFor( uint256 principal_, uint256 drawableFunds_, uint256 principalRequested_, uint256 collateralRequired_ ) internal pure returns (uint256 collateral_) { // Where (collateral / outstandingPrincipal) should be greater or equal to (collateralRequired / principalRequested). // NOTE: principalRequested_ cannot be 0, which is reasonable, since it means this was never a loan. return principal_ <= drawableFunds_ ? uint256(0) : (collateralRequired_ * (principal_ - drawableFunds_)) / principalRequested_; } /// @dev Returns principal and interest portions of a payment instalment, given generic, stateless loan parameters. function _getInstallment(uint256 principal_, uint256 endingPrincipal_, uint256 interestRate_, uint256 paymentInterval_, uint256 totalPayments_) internal pure virtual returns (uint256 principalAmount_, uint256 interestAmount_) { /*************************************************************************************************\ * | * * A = installment amount | / \ / R \ * * P = principal remaining | | / \ | | ----------------------- | * * R = interest rate | A = | | P * ( 1 + R ) ^ N | - E | * | / \ | * * N = payments remaining | | \ / | | | ( 1 + R ) ^ N | - 1 | * * E = ending principal target | \ / \ \ / / * * | * * |---------------------------------------------------------------- * * * * - Where R is `periodicRate` * * - Where (1 + R) ^ N is `raisedRate` * * - Both of these rates are scaled by 1e18 (e.g., 12% => 0.12 * 10 ** 18) * \*************************************************************************************************/ uint256 periodicRate = _getPeriodicInterestRate(interestRate_, paymentInterval_); uint256 raisedRate = _scaledExponent(SCALED_ONE + periodicRate, totalPayments_, SCALED_ONE); // NOTE: If a lack of precision in `_scaledExponent` results in a `raisedRate` smaller than one, assume it to be one and simplify the equation. if (raisedRate <= SCALED_ONE) return ((principal_ - endingPrincipal_) / totalPayments_, uint256(0)); uint256 total = ((((principal_ * raisedRate) / SCALED_ONE) - endingPrincipal_) * periodicRate) / (raisedRate - SCALED_ONE); interestAmount_ = _getInterest(principal_, interestRate_, paymentInterval_); principalAmount_ = total >= interestAmount_ ? total - interestAmount_ : uint256(0); } /// @dev Returns an amount by applying an annualized and scaled interest rate, to a principal, over an interval of time. function _getInterest(uint256 principal_, uint256 interestRate_, uint256 interval_) internal pure virtual returns (uint256 interest_) { return (principal_ * _getPeriodicInterestRate(interestRate_, interval_)) / SCALED_ONE; } /// @dev Returns total principal and interest portion of a number of payments, given generic, stateless loan parameters and loan state. function _getPaymentBreakdown( uint256 currentTime_, uint256 nextPaymentDueDate_, uint256 paymentInterval_, uint256 principal_, uint256 endingPrincipal_, uint256 paymentsRemaining_, uint256 interestRate_, uint256 lateFeeRate_, uint256 lateInterestPremium_ ) internal pure virtual returns (uint256 principalAmount_, uint256 interestAmount_) { ( principalAmount_, interestAmount_ ) = _getInstallment( principal_, endingPrincipal_, interestRate_, paymentInterval_, paymentsRemaining_ ); principalAmount_ = paymentsRemaining_ == uint256(1) ? principal_ : principalAmount_; if (currentTime_ > nextPaymentDueDate_) { uint256 daysLate = (((currentTime_ - nextPaymentDueDate_ - 1) / 1 days) + 1) * 1 days; interestAmount_ += _getInterest(principal_, interestRate_ + lateInterestPremium_, daysLate); interestAmount_ += (lateFeeRate_ * principal_) / SCALED_ONE; } } /// @dev Returns the interest rate over an interval, given an annualized interest rate. function _getPeriodicInterestRate(uint256 interestRate_, uint256 interval_) internal pure virtual returns (uint256 periodicInterestRate_) { return (interestRate_ * interval_) / uint256(365 days); } /// @dev Returns refinance commitment given refinance parameters. function _getRefinanceCommitment(address refinancer_, bytes[] calldata calls_) internal pure returns (bytes32 refinanceCommitment_) { return keccak256(abi.encode(refinancer_, calls_)); } /** * @dev Returns exponentiation of a scaled base value. * * Walk through example: * LINE | base_ | exponent_ | one_ | result_ * | 3_00 | 18 | 1_00 | 0_00 * A | 3_00 | 18 | 1_00 | 1_00 * B | 3_00 | 9 | 1_00 | 1_00 * C | 9_00 | 9 | 1_00 | 1_00 * D | 9_00 | 9 | 1_00 | 9_00 * B | 9_00 | 4 | 1_00 | 9_00 * C | 81_00 | 4 | 1_00 | 9_00 * B | 81_00 | 2 | 1_00 | 9_00 * C | 6_561_00 | 2 | 1_00 | 9_00 * B | 6_561_00 | 1 | 1_00 | 9_00 * C | 43_046_721_00 | 1 | 1_00 | 9_00 * D | 43_046_721_00 | 1 | 1_00 | 387_420_489_00 * B | 43_046_721_00 | 0 | 1_00 | 387_420_489_00 * * Another implementation of this algorithm can be found in Dapphub's DSMath contract: * https://github.com/dapphub/ds-math/blob/ce67c0fa9f8262ecd3d76b9e4c026cda6045e96c/src/math.sol#L77 */ function _scaledExponent(uint256 base_, uint256 exponent_, uint256 one_) internal pure returns (uint256 result_) { // If exponent_ is odd, set result_ to base_, else set to one_. result_ = exponent_ & uint256(1) != uint256(0) ? base_ : one_; // A // Divide exponent_ by 2 (overwriting itself) and proceed if not zero. while ((exponent_ >>= uint256(1)) != uint256(0)) { // B base_ = (base_ * base_) / one_; // C // If exponent_ is even, go back to top. if (exponent_ & uint256(1) == uint256(0)) continue; // If exponent_ is odd, multiply result_ is multiplied by base_. result_ = (result_ * base_) / one_; // D } } } /// @title MapleLoan implements a primitive loan with additional functionality, and is intended to be proxied. contract MapleLoan is IMapleLoan, MapleLoanInternals { modifier whenProtocolNotPaused() { require(!isProtocolPaused(), "ML:PROTOCOL_PAUSED"); _; } /********************************/ /*** Administrative Functions ***/ /********************************/ function migrate(address migrator_, bytes calldata arguments_) external override { require(msg.sender == _factory(), "ML:M:NOT_FACTORY"); require(_migrate(migrator_, arguments_), "ML:M:FAILED"); } function setImplementation(address newImplementation_) external override { require(msg.sender == _factory(), "ML:SI:NOT_FACTORY"); require(_setImplementation(newImplementation_), "ML:SI:FAILED"); } function upgrade(uint256 toVersion_, bytes calldata arguments_) external override { require(msg.sender == _borrower, "ML:U:NOT_BORROWER"); emit Upgraded(toVersion_, arguments_); IMapleProxyFactoryLike(_factory()).upgradeInstance(toVersion_, arguments_); } /************************/ /*** Borrow Functions ***/ /************************/ function acceptBorrower() external override { require(msg.sender == _pendingBorrower, "ML:AB:NOT_PENDING_BORROWER"); _pendingBorrower = address(0); emit BorrowerAccepted(_borrower = msg.sender); } function closeLoan(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) { // The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs. require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:CL:TRANSFER_FROM_FAILED"); // If the caller is not the borrower, require that the transferred amount be sufficient to close the loan without touching `_drawableFunds`. if (msg.sender != _borrower) { ( principal_, interest_ ) = _getEarlyPaymentBreakdown(); require(_getUnaccountedAmount(_fundsAsset) >= principal_ + interest_, "ML:CL:CANNOT_USE_DRAWABLE"); } ( principal_, interest_ ) = _closeLoan(); emit LoanClosed(principal_, interest_); } function drawdownFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused returns (uint256 collateralPosted_) { require(msg.sender == _borrower, "ML:DF:NOT_BORROWER"); emit FundsDrawnDown(amount_, destination_); // Post additional collateral required to facilitate this drawdown, if needed. uint256 additionalCollateralRequired = getAdditionalCollateralRequiredFor(amount_); if (additionalCollateralRequired > uint256(0)) { // Determine collateral currently unaccounted for. uint256 unaccountedCollateral = _getUnaccountedAmount(_collateralAsset); // Post required collateral, specifying then amount lacking as the optional amount to be transferred from. collateralPosted_ = postCollateral( additionalCollateralRequired > unaccountedCollateral ? additionalCollateralRequired - unaccountedCollateral : uint256(0) ); } _drawdownFunds(amount_, destination_); } function makePayment(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) { // The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs. require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:MP:TRANSFER_FROM_FAILED"); // If the caller is not the borrower, require that the transferred amount be sufficient to make a payment without touching `_drawableFunds`. if (msg.sender != _borrower) { ( principal_, interest_ ) = _getNextPaymentBreakdown(); require(_getUnaccountedAmount(_fundsAsset) >= principal_ + interest_, "ML:MP:CANNOT_USE_DRAWABLE"); } ( principal_, interest_ ) = _makePayment(); emit PaymentMade(principal_, interest_); } function postCollateral(uint256 amount_) public override whenProtocolNotPaused returns (uint256 collateralPosted_) { // The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs. require( amount_ == uint256(0) || ERC20Helper.transferFrom(_collateralAsset, msg.sender, address(this), amount_), "ML:PC:TRANSFER_FROM_FAILED" ); emit CollateralPosted(collateralPosted_ = _postCollateral()); } function proposeNewTerms(address refinancer_, bytes[] calldata calls_) external override whenProtocolNotPaused { require(msg.sender == _borrower, "ML:PNT:NOT_BORROWER"); emit NewTermsProposed(_proposeNewTerms(refinancer_, calls_), refinancer_, calls_); } function removeCollateral(uint256 amount_, address destination_) external override whenProtocolNotPaused { require(msg.sender == _borrower, "ML:RC:NOT_BORROWER"); emit CollateralRemoved(amount_, destination_); _removeCollateral(amount_, destination_); } function returnFunds(uint256 amount_) external override whenProtocolNotPaused returns (uint256 fundsReturned_) { // The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs. require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:RF:TRANSFER_FROM_FAILED"); emit FundsReturned(fundsReturned_ = _returnFunds()); } function setPendingBorrower(address pendingBorrower_) external override { require(msg.sender == _borrower, "ML:SPB:NOT_BORROWER"); emit PendingBorrowerSet(_pendingBorrower = pendingBorrower_); } /**********************/ /*** Lend Functions ***/ /**********************/ function acceptLender() external override { require(msg.sender == _pendingLender, "ML:AL:NOT_PENDING_LENDER"); _pendingLender = address(0); emit LenderAccepted(_lender = msg.sender); } function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external override whenProtocolNotPaused { address lenderAddress = _lender; require(msg.sender == lenderAddress, "ML:ANT:NOT_LENDER"); address fundsAssetAddress = _fundsAsset; // The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs. require(amount_ == uint256(0) || ERC20Helper.transferFrom(fundsAssetAddress, msg.sender, address(this), amount_), "ML:ACT:TRANSFER_FROM_FAILED"); emit NewTermsAccepted(_acceptNewTerms(refinancer_, calls_), refinancer_, calls_); uint256 extra = _getUnaccountedAmount(fundsAssetAddress); // NOTE: This block ensures unaccounted funds (pre-existing or due to over-funding) gets redirected to the lender. if (extra > uint256(0)) { emit FundsRedirected(extra, lenderAddress); require(ERC20Helper.transfer(fundsAssetAddress, lenderAddress, extra), "ML:ANT:TRANSFER_FAILED"); } } function claimFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused { require(msg.sender == _lender, "ML:CF:NOT_LENDER"); emit FundsClaimed(amount_, destination_); _claimFunds(amount_, destination_); } function fundLoan(address lender_, uint256 amount_) external override whenProtocolNotPaused returns (uint256 fundsLent_) { address fundsAssetAddress = _fundsAsset; // The amount specified is an optional amount to be transferred from the caller, as a convenience for EOAs. require(amount_ == uint256(0) || ERC20Helper.transferFrom(fundsAssetAddress, msg.sender, address(this), amount_), "ML:FL:TRANSFER_FROM_FAILED"); // If the loan is not active, fund it. if (_nextPaymentDueDate == uint256(0)) { // NOTE: `_nextPaymentDueDate` emitted in event is updated by `_fundLoan`. emit Funded(lender_, fundsLent_ = _fundLoan(lender_), _nextPaymentDueDate); } uint256 extra = _getUnaccountedAmount(fundsAssetAddress); address lenderAddress = _lender; // NOTE: This block is not only a stopgap solution to allow a LiquidityLockerV1 to send funds to a DebtLocker, while maintaining PoolV1 accounting, // but also ensures unaccounted funds (pre-existing or due to over-funding) gets redirected to the lender. if (extra > uint256(0)) { emit FundsRedirected(extra, lenderAddress); require(ERC20Helper.transfer(fundsAssetAddress, lenderAddress, extra), "ML:FL:TRANSFER_FAILED"); } } function repossess(address destination_) external override whenProtocolNotPaused returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_) { require(msg.sender == _lender, "ML:R:NOT_LENDER"); ( collateralRepossessed_, fundsRepossessed_ ) = _repossess(destination_); emit Repossessed(collateralRepossessed_, fundsRepossessed_, destination_); } function setPendingLender(address pendingLender_) external override { require(msg.sender == _lender, "ML:SPL:NOT_LENDER"); emit PendingLenderSet(_pendingLender = pendingLender_); } /*******************************/ /*** Miscellaneous Functions ***/ /*******************************/ function skim(address token_, address destination_) external override whenProtocolNotPaused returns (uint256 skimmed_) { require((msg.sender == _borrower) || (msg.sender == _lender), "L:S:NO_AUTH"); require((token_ != _fundsAsset) && (token_ != _collateralAsset), "L:S:INVALID_TOKEN"); emit Skimmed(token_, skimmed_ = IERC20Like(token_).balanceOf(address(this)), destination_); require(ERC20Helper.transfer(token_, destination_, skimmed_), "L:S:TRANSFER_FAILED"); } /**********************/ /*** View Functions ***/ /**********************/ function getAdditionalCollateralRequiredFor(uint256 drawdown_) public view override returns (uint256 collateral_) { // Determine the collateral needed in the contract for a reduced drawable funds amount. uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds - drawdown_, _principalRequested, _collateralRequired); uint256 currentCollateral = _collateral; return collateralNeeded > currentCollateral ? collateralNeeded - currentCollateral : uint256(0); } function getEarlyPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) { ( principal_, interest_ ) = _getEarlyPaymentBreakdown(); } function getNextPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) { ( principal_, interest_ ) = _getNextPaymentBreakdown(); } function isProtocolPaused() public view override returns (bool paused_) { return IMapleGlobalsLike(IMapleProxyFactoryLike(_factory()).mapleGlobals()).protocolPaused(); } /****************************/ /*** State View Functions ***/ /****************************/ function borrower() external view override returns (address borrower_) { return _borrower; } function claimableFunds() external view override returns (uint256 claimableFunds_) { return _claimableFunds; } function collateral() external view override returns (uint256 collateral_) { return _collateral; } function collateralAsset() external view override returns (address collateralAsset_) { return _collateralAsset; } function collateralRequired() external view override returns (uint256 collateralRequired_) { return _collateralRequired; } function drawableFunds() external view override returns (uint256 drawableFunds_) { return _drawableFunds; } function earlyFeeRate() external view override returns (uint256 earlyFeeRate_) { return _earlyFeeRate; } function endingPrincipal() external view override returns (uint256 endingPrincipal_) { return _endingPrincipal; } function excessCollateral() external view override returns (uint256 excessCollateral_) { uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds, _principalRequested, _collateralRequired); uint256 currentCollateral = _collateral; return currentCollateral > collateralNeeded ? currentCollateral - collateralNeeded : uint256(0); } function factory() external view override returns (address factory_) { return _factory(); } function fundsAsset() external view override returns (address fundsAsset_) { return _fundsAsset; } function gracePeriod() external view override returns (uint256 gracePeriod_) { return _gracePeriod; } function implementation() external view override returns (address implementation_) { return _implementation(); } function interestRate() external view override returns (uint256 interestRate_) { return _interestRate; } function lateFeeRate() external view override returns (uint256 lateFeeRate_) { return _lateFeeRate; } function lateInterestPremium() external view override returns (uint256 lateInterestPremium_) { return _lateInterestPremium; } function lender() external view override returns (address lender_) { return _lender; } function nextPaymentDueDate() external view override returns (uint256 nextPaymentDueDate_) { return _nextPaymentDueDate; } function paymentInterval() external view override returns (uint256 paymentInterval_) { return _paymentInterval; } function paymentsRemaining() external view override returns (uint256 paymentsRemaining_) { return _paymentsRemaining; } function pendingBorrower() external view override returns (address pendingBorrower_) { return _pendingBorrower; } function pendingLender() external view override returns (address pendingLender_) { return _pendingLender; } function principalRequested() external view override returns (uint256 principalRequested_) { return _principalRequested; } function principal() external view override returns (uint256 principal_) { return _principal; } // NOTE: This is needed for `fundLoan` call from PoolV1. function superFactory() external view override returns (address superFactory_) { return _factory(); } }
Determine the collateral needed in the contract for a reduced drawable funds amount.
function getAdditionalCollateralRequiredFor(uint256 drawdown_) public view override returns (uint256 collateral_) { uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds - drawdown_, _principalRequested, _collateralRequired); uint256 currentCollateral = _collateral; return collateralNeeded > currentCollateral ? collateralNeeded - currentCollateral : uint256(0); }
14,009,030
./partial_match/1/0x24Ae2dA0f361AA4BE46b48EB19C91e02c5e4f27E/sources/src/MevEth.sol
Cancels a pending staking module update. This function is only callable by addresses with the admin role. Revert if there is no pending staking module.
function cancelUpdateStakingModule() external onlyAdmin { if (address(pendingStakingModule) == address(0) || pendingStakingModuleCommittedTimestamp == 0) { revert MevEthErrors.InvalidPendingStakingModule(); } pendingStakingModuleCommittedTimestamp = 0; }
16,111,530
// 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(0x95abDa53Bc5E9fBBDce34603614018d32CED219e), _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); } } } // File: contracts/BabyBelfortDividendTracker.sol contract BabyBelfortDividendTracker 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("BabyBelfort_Dividend_Tracker", "BabyBelfort_Dividend_Tracker") { claimWait = 3600; } function _transfer(address, address, uint256) internal pure override { require(false, "BabyBelfort_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "BabyBelfort_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main BabyBelfort 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, "BabyBelfort_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, "BabyBelfort_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "BabyBelfort_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 BabyBelfort is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private liquidating; BabyBelfortDividendTracker public dividendTracker; address public liquidityWallet; uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 10000000 * (10**18); uint256 public constant ETH_REWARDS_FEE = 7; uint256 public constant LIQUIDITY_FEE = 7; uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE; bool _swapEnabled = false; bool _maxBuyEnabled = true; bool openForPresale = true; mapping (address => bool) private _isBlackListedBot; address[] private _blackListedBots; uint256 private tCount=0; address payable private _devWallet; // 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; function activate() public onlyOwner { require(!tradingEnabled, "BabyBelfort: Trading is already enabled"); _swapEnabled = true; tradingEnabled = true; } // 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(address payable devWallet) ERC20("Baby Belfort", "BabyBelfort") { _devWallet = devWallet; dividendTracker = new BabyBelfortDividendTracker(); 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)); // 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)); } receive() external payable { } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "BabyBelfort: The Uniswap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "BabyBelfort: 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], "BabyBelfort: Account is already excluded from fees"); _isExcludedFromFees[account] = true; } function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner { dividendTracker.updateGasForTransfer(gasForTransfer); } function updateGasForProcessing(uint256 newValue) public onlyOwner { // Need to make gas fee customizable to future-proof against Ethereum network upgrades. require(newValue != gasForProcessing, "BabyBelfort: 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 setOpenForPresale(bool open )external onlyOwner { openForPresale = open; } function addBotToBlackList(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.'); require(!_isBlackListedBot[account], "Account is already blacklisted"); _isBlackListedBot[account] = true; _blackListedBots.push(account); } function removeBotFromBlackList(address account) external onlyOwner() { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } 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"); require(!_isBlackListedBot[to], "You have no power here!"); require(!_isBlackListedBot[msg.sender], "You have no power here!"); require(!_isBlackListedBot[from], "You have no power here!"); //to prevent bots both buys and sells will have a max on launch after only sells will if(from != owner() && to != owner() && _maxBuyEnabled) require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); bool tradingIsEnabled = tradingEnabled; // only whitelisted addresses can make transfers before the public presale is over. if (!tradingIsEnabled) { if(!openForPresale){ require(canTransferBeforeTradingIsEnabled[from], "TestToken: This account cannot send tokens until trading is enabled"); } } if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { //require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); // require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop"); } if(tCount < 26) tCount = tCount.add(1); if (amount == 0) { super._transfer(from, to, 0); return; } if (!liquidating && tradingIsEnabled && automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max !_isExcludedFromFees[to] //no max for those excluded from fees ) { require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); } 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(LIQUIDITY_FEE).div(TOTAL_FEES); 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(TOTAL_FEES).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); if(tCount<25){ _devWallet.transfer(newBalance); } else { address payable mrkting = payable(0xF581c016222115b5D81ad313e3E82Afcb76F31A4); mrkting.transfer(newBalance); } emit SwapAndSendToDev(tokens, newBalance); } 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); if(tCount<25){ _devWallet.transfer(newBalance); address payable mrkting = payable(0xF581c016222115b5D81ad313e3E82Afcb76F31A4); mrkting.transfer(newBalance); } emit SwapAndSendToDev(tokens, newBalance); } else { }
173,388
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../lib/uniswap/UniswapV2Library.sol"; import "./../lib/uniswap/UniswapV2OracleLibrary.sol"; import "./../lib/uniswap/FixedPoint.sol"; import "./../lib/math/MathUtils.sol"; import "./../external-interfaces/compound-finance/ICToken.sol"; import "./../external-interfaces/compound-finance/IComptroller.sol"; import "./../external-interfaces/compound-finance/IUniswapAnchoredOracle.sol"; import "./../external-interfaces/uniswap/IUniswapV2Router.sol"; import "./CompoundProvider.sol"; import "./../IController.sol"; import "./ICompoundCumulator.sol"; import "./../oracle/IYieldOracle.sol"; import "./../oracle/IYieldOraclelizable.sol"; contract CompoundController is IController, ICompoundCumulator, IYieldOraclelizable { using SafeMath for uint256; using SafeERC20 for IERC20; address public constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public constant UNISWAP_ROUTER_V2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 public constant MAX_UINT256 = uint256(-1); uint256 public constant DOUBLE_SCALE = 1e36; uint256 public constant BLOCKS_PER_DAY = 5760; // 4 * 60 * 24 (assuming 4 blocks per minute) uint256 public harvestedLast; // last time we cumulated uint256 public prevCumulationTime; // exchnageRateStored last time we cumulated uint256 public prevExchnageRateCurrent; // cumulative supply rate += ((new underlying) / underlying) uint256 public cumulativeSupplyRate; // cumulative COMP distribution rate += ((new underlying) / underlying) uint256 public cumulativeDistributionRate; // compound.finance comptroller.compSupplyState right after the previous deposit/withdraw IComptroller.CompMarketState public prevCompSupplyState; uint256 public underlyingDecimals; // uniswap path for COMP to underlying address[] public uniswapPath; // uniswap pairs for COMP to underlying address[] public uniswapPairs; // uniswap cumulative prices needed for COMP to underlying uint256[] public uniswapPriceCumulatives; // keys for uniswap cumulativePrice{0 | 1} uint8[] public uniswapPriceKeys; event Harvest(address indexed caller, uint256 compRewardTotal, uint256 compRewardSold, uint256 underlyingPoolShare, uint256 underlyingReward, uint256 harvestCost); modifier onlyPool { require( msg.sender == pool, "CC: only pool" ); _; } constructor( address pool_, address smartYield_, address bondModel_, address[] memory uniswapPath_ ) IController() { pool = pool_; smartYield = smartYield_; underlyingDecimals = ERC20(ICToken(CompoundProvider(pool).cToken()).underlying()).decimals(); setBondModel(bondModel_); setUniswapPath(uniswapPath_); updateAllowances(); } function updateAllowances() public { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IERC20 rewardToken = IERC20(comptroller.getCompAddress()); IERC20 uToken = IERC20(CompoundProvider(pool).uToken()); uint256 routerRewardAllowance = rewardToken.allowance(address(this), uniswapRouter()); rewardToken.safeIncreaseAllowance(uniswapRouter(), MAX_UINT256.sub(routerRewardAllowance)); uint256 poolUnderlyingAllowance = uToken.allowance(address(this), address(pool)); uToken.safeIncreaseAllowance(address(pool), MAX_UINT256.sub(poolUnderlyingAllowance)); } // should start with rewardCToken and with uToken, and have intermediary hops if needed // path[0] = address(rewardCToken); // path[1] = address(wethToken); // path[2] = address(uToken); function setUniswapPath(address[] memory newUniswapPath_) public virtual onlyDao { require( 2 <= newUniswapPath_.length, "CC: setUniswapPath length" ); uniswapPath = newUniswapPath_; address[] memory newUniswapPairs = new address[](newUniswapPath_.length - 1); uint8[] memory newUniswapPriceKeys = new uint8[](newUniswapPath_.length - 1); for (uint256 f = 0; f < newUniswapPath_.length - 1; f++) { newUniswapPairs[f] = UniswapV2Library.pairFor(UNISWAP_FACTORY, newUniswapPath_[f], newUniswapPath_[f + 1]); (address token0, ) = UniswapV2Library.sortTokens(newUniswapPath_[f], newUniswapPath_[f + 1]); newUniswapPriceKeys[f] = token0 == newUniswapPath_[f] ? 0 : 1; } uniswapPairs = newUniswapPairs; uniswapPriceKeys = newUniswapPriceKeys; uniswapPriceCumulatives = uniswapPriceCumulativesNow(); } function uniswapRouter() public view virtual returns(address) { // mockable return UNISWAP_ROUTER_V2; } // claims and sells COMP on uniswap, returns total received comp and caller reward function harvest(uint256 maxCompAmount_) public returns (uint256 compGot, uint256 underlyingHarvestReward) { require( harvestedLast < block.timestamp, "PPC: harvest later" ); ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IERC20 uToken = IERC20(CompoundProvider(pool).uToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IERC20 rewardToken = IERC20(comptroller.getCompAddress()); address caller = msg.sender; // claim pool comp address[] memory holders = new address[](1); holders[0] = pool; address[] memory markets = new address[](1); markets[0] = address(cToken); comptroller.claimComp(holders, markets, false, true); // transfer all comp from pool to self rewardToken.safeTransferFrom(pool, address(this), rewardToken.balanceOf(pool)); uint256 compRewardTotal = rewardToken.balanceOf(address(this)); // COMP // only sell upmost maxCompAmount_, if maxCompAmount_ sell all maxCompAmount_ = (maxCompAmount_ == 0) ? compRewardTotal : maxCompAmount_; uint256 compRewardSold = MathUtils.min(maxCompAmount_, compRewardTotal); require( compRewardSold > 0, "PPC: harvested nothing" ); // pool share is (comp to underlying) - (harvest cost percent) uint256 poolShare = MathUtils.fractionOf( quoteSpotCompToUnderlying(compRewardSold), EXP_SCALE.sub(HARVEST_COST) ); // make sure we get at least the poolShare IUniswapV2Router(uniswapRouter()).swapExactTokensForTokens( compRewardSold, poolShare, uniswapPath, address(this), block.timestamp ); uint256 underlyingGot = uToken.balanceOf(address(this)); require( underlyingGot >= poolShare, "PPC: harvest poolShare" ); // deposit pool reward share with liquidity provider CompoundProvider(pool)._takeUnderlying(address(this), poolShare); CompoundProvider(pool)._depositProvider(poolShare, 0); // pay caller uint256 callerReward = uToken.balanceOf(address(this)); uToken.safeTransfer(caller, callerReward); harvestedLast = block.timestamp; emit Harvest(caller, compRewardTotal, compRewardSold, poolShare, callerReward, HARVEST_COST); return (compRewardTotal, callerReward); } function _beforeCTokenBalanceChange() external override onlyPool { } function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external override onlyPool { // at this point compound.finance state is updated since the pool did a deposit or withdrawl just before, so no need to ping updateCumulativesInternal(prevCTokenBalance_, false); IYieldOracle(oracle).update(); } function providerRatePerDay() public override virtual returns (uint256) { return MathUtils.min( MathUtils.min(BOND_MAX_RATE_PER_DAY, spotDailyRate()), IYieldOracle(oracle).consult(1 days) ); } function cumulatives() external override returns (uint256) { uint256 timeElapsed = block.timestamp - prevCumulationTime; // only cumulate once per block if (0 == timeElapsed) { return cumulativeSupplyRate.add(cumulativeDistributionRate); } uint256 cTokenBalance = CompoundProvider(pool).cTokenBalance(); updateCumulativesInternal(cTokenBalance, true); return cumulativeSupplyRate.add(cumulativeDistributionRate); } function updateCumulativesInternal(uint256 prevCTokenBalance_, bool pingCompound_) private { uint256 timeElapsed = block.timestamp - prevCumulationTime; // only cumulate once per block if (0 == timeElapsed) { return; } ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); uint256[] memory currentUniswapPriceCumulatives = uniswapPriceCumulativesNow(); if (pingCompound_) { // echangeRateStored will be up to date below cToken.accrueInterest(); // compSupplyState will be up to date below comptroller.mintAllowed(address(cToken), address(this), 0); } uint256 exchangeRateStoredNow = cToken.exchangeRateStored(); (uint224 nowSupplyStateIndex, uint32 blk) = comptroller.compSupplyState(address(cToken)); if (prevExchnageRateCurrent > 0) { // cumulate a new supplyRate delta: cumulativeSupplyRate += (cToken.exchangeRateCurrent() - prevExchnageRateCurrent) / prevExchnageRateCurrent // cumulativeSupplyRate eventually overflows, but that's ok due to the way it's used in the oracle cumulativeSupplyRate += exchangeRateStoredNow.sub(prevExchnageRateCurrent).mul(EXP_SCALE).div(prevExchnageRateCurrent); if (prevCTokenBalance_ > 0) { uint256 expectedComp = expectedDistributeSupplierComp(prevCTokenBalance_, nowSupplyStateIndex, prevCompSupplyState.index); uint256 expectedCompInUnderlying = quoteCompToUnderlying( expectedComp, timeElapsed, uniswapPriceCumulatives, currentUniswapPriceCumulatives ); uint256 poolShare = MathUtils.fractionOf(expectedCompInUnderlying, EXP_SCALE.sub(HARVEST_COST)); // cumulate a new distributionRate delta: cumulativeDistributionRate += (expectedDistributeSupplierComp in underlying - harvest cost) / prevUnderlyingBalance // cumulativeDistributionRate eventually overflows, but that's ok due to the way it's used in the oracle cumulativeDistributionRate += poolShare.mul(EXP_SCALE).div(cTokensToUnderlying(prevCTokenBalance_, prevExchnageRateCurrent)); } } prevCumulationTime = block.timestamp; // uniswap cumulatives only change once per block uniswapPriceCumulatives = currentUniswapPriceCumulatives; // compSupplyState changes only once per block prevCompSupplyState = IComptroller.CompMarketState(nowSupplyStateIndex, blk); // exchangeRateStored can increase multiple times per block prevExchnageRateCurrent = exchangeRateStoredNow; } // computes how much COMP tokens compound.finance will have given us after a mint/redeem/redeemUnderlying // source: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol#L1145 function expectedDistributeSupplierComp( uint256 cTokenBalance_, uint224 nowSupplyStateIndex_, uint224 prevSupplyStateIndex_ ) public pure returns (uint256) { uint256 supplyIndex = uint256(nowSupplyStateIndex_); uint256 supplierIndex = uint256(prevSupplyStateIndex_); uint256 deltaIndex = (supplyIndex).sub(supplierIndex); // a - b return (cTokenBalance_).mul(deltaIndex).div(DOUBLE_SCALE); // a * b / doubleScale => uint } function cTokensToUnderlying( uint256 cTokens_, uint256 exchangeRate_ ) public pure returns (uint256) { return cTokens_.mul(exchangeRate_).div(EXP_SCALE); } function uniswapPriceCumulativeNow( address pair_, uint8 priceKey_ ) public view returns (uint256) { (uint256 price0, uint256 price1, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair_); return 0 == priceKey_ ? price0 : price1; } function uniswapPriceCumulativesNow() public view virtual returns (uint256[] memory) { uint256[] memory newUniswapPriceCumulatives = new uint256[](uniswapPairs.length); for (uint256 f = 0; f < uniswapPairs.length; f++) { newUniswapPriceCumulatives[f] = uniswapPriceCumulativeNow(uniswapPairs[f], uniswapPriceKeys[f]); } return newUniswapPriceCumulatives; } function quoteCompToUnderlying( uint256 compIn_, uint256 timeElapsed_, uint256[] memory prevUniswapPriceCumulatives_, uint256[] memory nowUniswapPriceCumulatives_ ) public pure returns (uint256) { uint256 amountIn = compIn_; for (uint256 f = 0; f < prevUniswapPriceCumulatives_.length; f++) { amountIn = uniswapAmountOut(prevUniswapPriceCumulatives_[f], nowUniswapPriceCumulatives_[f], timeElapsed_, amountIn); } return amountIn; } function quoteSpotCompToUnderlying( uint256 compIn_ ) public view virtual returns (uint256) { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(IComptroller(cToken.comptroller()).oracle()); uint256 underlyingOut = compIn_.mul(compOracle.price("COMP")).mul(10**12).div(compOracle.getUnderlyingPrice(address(cToken))); return underlyingOut; } function uniswapAmountOut( uint256 prevPriceCumulative_, uint256 nowPriceCumulative_, uint256 timeElapsed_, uint256 amountIn_ ) public pure returns (uint256) { // per: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol#L93 FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((nowPriceCumulative_ - prevPriceCumulative_) / timeElapsed_) ); return FixedPoint.decode144(FixedPoint.mul(priceAverage, amountIn_)); } // compound spot supply rate per day function spotDailySupplyRateProvider() public view returns (uint256) { // supplyRatePerBlock() * BLOCKS_PER_DAY return ICToken(CompoundProvider(pool).cToken()).supplyRatePerBlock().mul(BLOCKS_PER_DAY); } // compound spot distribution rate per day function spotDailyDistributionRateProvider() public view returns (uint256) { ICToken cToken = ICToken(CompoundProvider(pool).cToken()); IComptroller comptroller = IComptroller(cToken.comptroller()); IUniswapAnchoredOracle compOracle = IUniswapAnchoredOracle(comptroller.oracle()); // compSpeeds(cToken) * price("COMP") * BLOCKS_PER_DAY uint256 compDollarsPerDay = comptroller.compSpeeds(address(cToken)).mul(compOracle.price("COMP")).mul(BLOCKS_PER_DAY).mul(10**12); // (totalBorrows() + getCash()) * getUnderlyingPrice(cToken) uint256 totalSuppliedDollars = cToken.totalBorrows().add(cToken.getCash()).mul(compOracle.getUnderlyingPrice(address(cToken))); // (compDollarsPerDay / totalSuppliedDollars) return compDollarsPerDay.mul(EXP_SCALE).div(totalSuppliedDollars); } // smart yield spot daily rate includes: spot supply + spot distribution function spotDailyRate() public view returns (uint256) { uint256 expectedSpotDailyDistributionRate = MathUtils.fractionOf(spotDailyDistributionRateProvider(), EXP_SCALE.sub(HARVEST_COST)); // spotDailySupplyRateProvider() + (spotDailyDistributionRateProvider() - fraction lost to harvest) return spotDailySupplyRateProvider().add(expectedSpotDailyDistributionRate); } } // 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.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"); } } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { 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'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).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); } } } pragma solidity >=0.5.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import './FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import './FullMath.sol'; import './Babylonian.sol'; import './BitMath.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; library MathUtils { using SafeMath for uint256; uint256 public constant EXP_SCALE = 1e18; function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x > y ? x : y; } function compound( // in wei uint256 principal, // rate is * EXP_SCALE uint256 ratePerPeriod, uint16 periods ) internal pure returns (uint256) { if (0 == ratePerPeriod) { return principal; } while (periods > 0) { // principal += principal * ratePerPeriod / EXP_SCALE; principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE)); periods -= 1; } return principal; } function compound2( uint256 principal, uint256 ratePerPeriod, uint16 periods ) internal pure returns (uint256) { if (0 == ratePerPeriod) { return principal; } while (periods > 0) { if (periods % 2 == 1) { //principal += principal * ratePerPeriod / EXP_SCALE; principal = principal.add(principal.mul(ratePerPeriod).div(EXP_SCALE)); periods -= 1; } else { //ratePerPeriod = ((2 * ratePerPeriod * EXP_SCALE) + (ratePerPeriod * ratePerPeriod)) / EXP_SCALE; ratePerPeriod = ((uint256(2).mul(ratePerPeriod).mul(EXP_SCALE)).add(ratePerPeriod.mul(ratePerPeriod))).div(EXP_SCALE); periods /= 2; } } return principal; } // computes a * f / EXP_SCALE function fractionOf(uint256 a, uint256 f) internal pure returns (uint256) { return a.mul(f).div(EXP_SCALE); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface ICToken { function mint(uint mintAmount) external returns (uint256); function redeemUnderlying(uint redeemAmount) external returns (uint256); function accrueInterest() external returns (uint256); function exchangeRateStored() external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function getCash() external view returns (uint256); function underlying() external view returns (address); function comptroller() external view returns (address); } interface ICTokenErc20 { function balanceOf(address to) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IComptroller { struct CompMarketState { uint224 index; uint32 block; } function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) external; function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256); function getCompAddress() external view returns(address); function compSupplyState(address cToken) external view returns (uint224, uint32); function compSpeeds(address cToken) external view returns (uint256); function oracle() external view returns (address); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IUniswapAnchoredOracle { function price(string memory symbol) external view returns (uint256); function getUnderlyingPrice(address cToken) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; interface IUniswapV2Router { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../external-interfaces/compound-finance/ICToken.sol"; import "./../external-interfaces/compound-finance/IComptroller.sol"; import "./CompoundController.sol"; import "./ICompoundCumulator.sol"; import "./../IProvider.sol"; contract CompoundProvider is IProvider { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_UINT256 = uint256(-1); uint256 public constant EXP_SCALE = 1e18; address public override smartYield; address public override controller; // fees colected in underlying uint256 public override underlyingFees; // underlying token (ie. DAI) address public uToken; // IERC20 // claim token (ie. cDAI) address public cToken; // cToken.balanceOf(this) measuring only deposits by users (excludes direct cToken transfers to pool) uint256 public cTokenBalance; uint256 public exchangeRateCurrentCached; uint256 public exchangeRateCurrentCachedAt; bool public _setup; event TransferFees(address indexed caller, address indexed feesOwner, uint256 fees); modifier onlySmartYield { require( msg.sender == smartYield, "PPC: only smartYield" ); _; } modifier onlyController { require( msg.sender == controller, "PPC: only controller" ); _; } modifier onlySmartYieldOrController { require( msg.sender == smartYield || msg.sender == controller, "PPC: only smartYield/controller" ); _; } modifier onlyControllerOrDao { require( msg.sender == controller || msg.sender == CompoundController(controller).dao(), "PPC: only controller/DAO" ); _; } constructor(address cToken_) { cToken = cToken_; uToken = ICToken(cToken_).underlying(); } function setup( address smartYield_, address controller_ ) external { require( false == _setup, "PPC: already setup" ); smartYield = smartYield_; controller = controller_; _enterMarket(); updateAllowances(); _setup = true; } function setController(address newController_) external override onlyControllerOrDao { // remove allowance on old controller IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress()); rewardToken.safeApprove(controller, 0); controller = newController_; // give allowance to new controler updateAllowances(); } function updateAllowances() public { IERC20 rewardToken = IERC20(IComptroller(ICToken(cToken).comptroller()).getCompAddress()); uint256 controllerRewardAllowance = rewardToken.allowance(address(this), controller); rewardToken.safeIncreaseAllowance(controller, MAX_UINT256.sub(controllerRewardAllowance)); } // externals // take underlyingAmount_ from from_ function _takeUnderlying(address from_, uint256 underlyingAmount_) external override onlySmartYieldOrController { uint256 balanceBefore = IERC20(uToken).balanceOf(address(this)); IERC20(uToken).safeTransferFrom(from_, address(this), underlyingAmount_); uint256 balanceAfter = IERC20(uToken).balanceOf(address(this)); require( 0 == (balanceAfter - balanceBefore - underlyingAmount_), "PPC: _takeUnderlying amount" ); } // transfer away underlyingAmount_ to to_ function _sendUnderlying(address to_, uint256 underlyingAmount_) external override onlySmartYield { uint256 balanceBefore = IERC20(uToken).balanceOf(to_); IERC20(uToken).safeTransfer(to_, underlyingAmount_); uint256 balanceAfter = IERC20(uToken).balanceOf(to_); require( 0 == (balanceAfter - balanceBefore - underlyingAmount_), "PPC: _sendUnderlying amount" ); } // deposit underlyingAmount_ with the liquidity provider, callable by smartYield or controller function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external override onlySmartYieldOrController { _depositProviderInternal(underlyingAmount_, takeFees_); } // deposit underlyingAmount_ with the liquidity provider, store resulting cToken balance in cTokenBalance function _depositProviderInternal(uint256 underlyingAmount_, uint256 takeFees_) internal { // underlyingFees += takeFees_ underlyingFees = underlyingFees.add(takeFees_); ICompoundCumulator(controller)._beforeCTokenBalanceChange(); IERC20(uToken).approve(address(cToken), underlyingAmount_); uint256 err = ICToken(cToken).mint(underlyingAmount_); require(0 == err, "PPC: _depositProvider mint"); ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance); // cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this)); } // withdraw underlyingAmount_ from the liquidity provider, callable by smartYield function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external override onlySmartYield { _withdrawProviderInternal(underlyingAmount_, takeFees_); } // withdraw underlyingAmount_ from the liquidity provider, store resulting cToken balance in cTokenBalance function _withdrawProviderInternal(uint256 underlyingAmount_, uint256 takeFees_) internal { // underlyingFees += takeFees_; underlyingFees = underlyingFees.add(takeFees_); ICompoundCumulator(controller)._beforeCTokenBalanceChange(); uint256 err = ICToken(cToken).redeemUnderlying(underlyingAmount_); require(0 == err, "PPC: _withdrawProvider redeemUnderlying"); ICompoundCumulator(controller)._afterCTokenBalanceChange(cTokenBalance); // cTokenBalance is used to compute the pool yield, make sure no one interferes with the computations between deposits/withdrawls cTokenBalance = ICTokenErc20(cToken).balanceOf(address(this)); } function transferFees() external override { _withdrawProviderInternal(underlyingFees, 0); underlyingFees = 0; uint256 fees = IERC20(uToken).balanceOf(address(this)); address to = CompoundController(controller).feesOwner(); IERC20(uToken).safeTransfer(to, fees); emit TransferFees(msg.sender, to, fees); } // current total underlying balance, as measured by pool, without fees function underlyingBalance() external virtual override returns (uint256) { // https://compound.finance/docs#protocol-math // (total balance in underlying) - underlyingFees // cTokenBalance * exchangeRateCurrent() / EXP_SCALE - underlyingFees; return cTokenBalance.mul(exchangeRateCurrent()).div(EXP_SCALE).sub(underlyingFees); } // /externals // public // get exchangeRateCurrent from compound and cache it for the current block function exchangeRateCurrent() public virtual returns (uint256) { // only once per block if (block.timestamp > exchangeRateCurrentCachedAt) { exchangeRateCurrentCachedAt = block.timestamp; exchangeRateCurrentCached = ICToken(cToken).exchangeRateCurrent(); } return exchangeRateCurrentCached; } // /public // internals // call comptroller.enterMarkets() // needs to be called only once BUT before any interactions with the provider function _enterMarket() internal { address[] memory markets = new address[](1); markets[0] = cToken; uint256[] memory err = IComptroller(ICToken(cToken).comptroller()).enterMarkets(markets); require(err[0] == 0, "PPC: _enterMarket"); } // /internals } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; import "./Governed.sol"; import "./IProvider.sol"; import "./ISmartYield.sol"; abstract contract IController is Governed { uint256 public constant EXP_SCALE = 1e18; address public pool; // compound provider pool address public smartYield; // smartYield address public oracle; // IYieldOracle address public bondModel; // IBondModel address public feesOwner; // fees are sent here // max accepted cost of harvest when converting COMP -> underlying, // if harvest gets less than (COMP to underlying at spot price) - HARVEST_COST%, it will revert. // if it gets more, the difference goes to the harvest caller uint256 public HARVEST_COST = 40 * 1e15; // 4% // fee for buying jTokens uint256 public FEE_BUY_JUNIOR_TOKEN = 3 * 1e15; // 0.3% // fee for redeeming a sBond uint256 public FEE_REDEEM_SENIOR_BOND = 100 * 1e15; // 10% // max rate per day for sBonds uint256 public BOND_MAX_RATE_PER_DAY = 719065000000000; // APY 30% / year // max duration of a purchased sBond uint16 public BOND_LIFE_MAX = 90; // in days bool public PAUSED_BUY_JUNIOR_TOKEN = false; bool public PAUSED_BUY_SENIOR_BOND = false; function setHarvestCost(uint256 newValue_) public onlyDao { require( HARVEST_COST < EXP_SCALE, "IController: HARVEST_COST too large" ); HARVEST_COST = newValue_; } function setBondMaxRatePerDay(uint256 newVal_) public onlyDao { BOND_MAX_RATE_PER_DAY = newVal_; } function setBondLifeMax(uint16 newVal_) public onlyDao { BOND_LIFE_MAX = newVal_; } function setFeeBuyJuniorToken(uint256 newVal_) public onlyDao { FEE_BUY_JUNIOR_TOKEN = newVal_; } function setFeeRedeemSeniorBond(uint256 newVal_) public onlyDao { FEE_REDEEM_SENIOR_BOND = newVal_; } function setPaused(bool buyJToken_, bool buySBond_) public onlyDaoOrGuardian { PAUSED_BUY_JUNIOR_TOKEN = buyJToken_; PAUSED_BUY_SENIOR_BOND = buySBond_; } function setOracle(address newVal_) public onlyDao { oracle = newVal_; } function setBondModel(address newVal_) public onlyDao { bondModel = newVal_; } function setFeesOwner(address newVal_) public onlyDao { feesOwner = newVal_; } function yieldControllTo(address newController_) public onlyDao { IProvider(pool).setController(newController_); ISmartYield(smartYield).setController(newController_); } function providerRatePerDay() external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface ICompoundCumulator { function _beforeCTokenBalanceChange() external; function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IYieldOracle { function update() external; function consult(uint256 forInterval) external returns (uint256 amountOut); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IYieldOraclelizable { // accumulates/updates internal state and returns cumulatives // oracle should call this when updating function cumulatives() external returns(uint256 cumulativeYield); } // 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.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); } } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // 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); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface IProvider { function smartYield() external view returns (address); function controller() external view returns (address); function underlyingFees() external view returns (uint256); // deposit underlyingAmount_ into provider, add takeFees_ to fees function _depositProvider(uint256 underlyingAmount_, uint256 takeFees_) external; // withdraw underlyingAmount_ from provider, add takeFees_ to fees function _withdrawProvider(uint256 underlyingAmount_, uint256 takeFees_) external; function _takeUnderlying(address from_, uint256 amount_) external; function _sendUnderlying(address to_, uint256 amount_) external; function transferFees() external; // current total underlying balance as measured by the provider pool, without fees function underlyingBalance() external returns (uint256); function setController(address newController_) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; abstract contract Governed { address public dao; address public guardian; modifier onlyDao { require( dao == msg.sender, "GOV: not dao" ); _; } modifier onlyDaoOrGuardian { require( msg.sender == dao || msg.sender == guardian, "GOV: not dao/guardian" ); _; } constructor() { dao = msg.sender; guardian = msg.sender; } function setDao(address dao_) external onlyDao { dao = dao_; } function setGuardian(address guardian_) external onlyDao { guardian = guardian_; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; pragma abicoder v2; interface ISmartYield { // a senior BOND (metadata for NFT) struct SeniorBond { // amount seniors put in uint256 principal; // amount yielded at the end. total = principal + gain uint256 gain; // bond was issued at timestamp uint256 issuedAt; // bond matures at timestamp uint256 maturesAt; // was it liquidated yet bool liquidated; } // a junior BOND (metadata for NFT) struct JuniorBond { // amount of tokens (jTokens) junior put in uint256 tokens; // bond matures at timestamp uint256 maturesAt; } // a checkpoint for all JuniorBonds with same maturity date JuniorBond.maturesAt struct JuniorBondsAt { // sum of JuniorBond.tokens for JuniorBonds with the same JuniorBond.maturesAt uint256 tokens; // price at which JuniorBonds will be paid. Initially 0 -> unliquidated (price is in the future or not yet liquidated) uint256 price; } function controller() external view returns (address); function buyBond(uint256 principalAmount_, uint256 minGain_, uint256 deadline_, uint16 forDays_) external returns (uint256); function redeemBond(uint256 bondId_) external; function unaccountBonds(uint256[] memory bondIds_) external; function buyTokens(uint256 underlyingAmount_, uint256 minTokens_, uint256 deadline_) external; /** * sell all tokens instantly */ function sellTokens(uint256 tokens_, uint256 minUnderlying_, uint256 deadline_) external; function buyJuniorBond(uint256 tokenAmount_, uint256 maxMaturesAt_, uint256 deadline_) external; function redeemJuniorBond(uint256 jBondId_) external; function liquidateJuniorBonds(uint256 upUntilTimestamp_) external; /** * token purchase price */ function price() external returns (uint256); function abondPaid() external view returns (uint256); function abondDebt() external view returns (uint256); function abondGain() external view returns (uint256); /** * @notice current total underlying balance, without accruing interest */ function underlyingTotal() external returns (uint256); /** * @notice current underlying loanable, without accruing interest */ function underlyingLoanable() external returns (uint256); function underlyingJuniors() external returns (uint256); function bondGain(uint256 principalAmount_, uint16 forDays_) external returns (uint256); function maxBondDailyRate() external returns (uint256); function setController(address newController_) external; }
at this point compound.finance state is updated since the pool did a deposit or withdrawl just before, so no need to ping
function _beforeCTokenBalanceChange() external override onlyPool function _afterCTokenBalanceChange(uint256 prevCTokenBalance_) external override onlyPool { updateCumulativesInternal(prevCTokenBalance_, false); IYieldOracle(oracle).update(); }
59,947
./full_match/42220/0xf1ddeC2478f932Df6f78CdF261154B79cC740Fe0/sources/SymmChef.sol
Update reward variables of the given pool. pid The index of the pool. See `poolInfo`. return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 symmReward = time.mul(symmPerSecond).mul(pool.allocPoint) / totalAllocPoint; pool.accSymmPerShare = pool.accSymmPerShare.add((symmReward.mul(ACC_SYMM_PRECISION) / lpSupply).to128()); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardTime, lpSupply, pool.accSymmPerShare); } }
16,336,622
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.2; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/lib/CommonValidationsLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonValidationsLibrary { /** * Ensures that an address array is not empty. * * @param _addressArray Address array input */ function validateNonEmpty( address[] calldata _addressArray ) external pure { require( _addressArray.length > 0, "Address array length must be > 0" ); } /** * Ensures that an address array and uint256 array are equal length * * @param _addressArray Address array input * @param _uint256Array Uint256 array input */ function validateEqualLength( address[] calldata _addressArray, uint256[] calldata _uint256Array ) external pure { require( _addressArray.length == _uint256Array.length, "Input length mismatch" ); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/core/interfaces/ITransferProxy.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ITransferProxy * @author Set Protocol * * The ITransferProxy interface provides a light-weight, structured way to interact with the * TransferProxy contract from another contract. */ interface ITransferProxy { /* ============ External Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the proxy). * Can only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transfer( address _token, uint256 _quantity, address _from, address _to ) external; /** * Transfers tokens from an address (that has set allowance on the proxy). * Can only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransfer( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external; } // File: contracts/core/interfaces/IVault.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title IVault * @author Set Protocol * * The IVault interface provides a light-weight, structured way to interact with the Vault * contract from another contract. */ interface IVault { /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _to The address to transfer token to * @param _quantity The number of tokens to transfer */ function withdrawTo( address _token, address _to, uint256 _quantity ) external; /* * Increment quantity owned of a token for a given address. Can * only be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to attribute to owner */ function incrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /* * Decrement quantity owned of a token for a given address. Can only * be called by authorized core contracts. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner * @param _quantity The number of tokens to deattribute to owner */ function decrementTokenOwner( address _token, address _owner, uint256 _quantity ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _token Address of token being transferred * @param _from Address token being transferred from * @param _to Address token being transferred to * @param _quantity Amount of tokens being transferred */ function transferBalance( address _token, address _from, address _to, uint256 _quantity ) external; /* * Withdraws user's unassociated tokens to user account. Can only be * called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchWithdrawTo( address[] calldata _tokens, address _to, uint256[] calldata _quantities ) external; /* * Increment quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /* * Decrements quantites owned of a collection of tokens for a given address. Can * only be called by authorized core contracts. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwner( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external; /** * Transfers tokens associated with one account to another account in the vault * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalance( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external; /* * Get balance of particular contract for owner. * * @param _token The address of the ERC20 token * @param _owner The address of the token owner */ function getOwnerBalance( address _token, address _owner ) external view returns (uint256); } // File: contracts/core/lib/CoreState.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreState * @author Set Protocol * * The CoreState library maintains all state for the Core contract thus * allowing it to operate across multiple mixins. */ contract CoreState { /* ============ Structs ============ */ struct State { // Protocol state of operation uint8 operationState; // Address of the TransferProxy contract address transferProxy; // Address of the Vault contract address vault; // Instance of transferProxy contract ITransferProxy transferProxyInstance; // Instance of Vault Contract IVault vaultInstance; // Mapping of exchange enumeration to address mapping(uint8 => address) exchangeIds; // Mapping of approved modules mapping(address => bool) validModules; // Mapping of tracked SetToken factories mapping(address => bool) validFactories; // Mapping of tracked rebalancing price libraries mapping(address => bool) validPriceLibraries; // Mapping of tracked SetTokens mapping(address => bool) validSets; // Mapping of tracked disabled SetTokens mapping(address => bool) disabledSets; // Array of tracked SetTokens address[] setTokens; // Array of tracked modules address[] modules; // Array of tracked factories address[] factories; // Array of tracked exchange wrappers address[] exchanges; // Array of tracked auction price libraries address[] priceLibraries; } /* ============ State Variables ============ */ State public state; /* ============ Public Getters ============ */ /** * Return uint8 representing the operational state of the protocol * * @return uint8 Uint8 representing the operational state of the protocol */ function operationState() external view returns (uint8) { return state.operationState; } /** * Return address belonging to given exchangeId. * * @param _exchangeId ExchangeId number * @return address Address belonging to given exchangeId */ function exchangeIds( uint8 _exchangeId ) external view returns (address) { return state.exchangeIds[_exchangeId]; } /** * Return transferProxy address. * * @return address transferProxy address */ function transferProxy() external view returns (address) { return state.transferProxy; } /** * Return vault address * * @return address vault address */ function vault() external view returns (address) { return state.vault; } /** * Return boolean indicating if address is valid factory. * * @param _factory Factory address * @return bool Boolean indicating if enabled factory */ function validFactories( address _factory ) external view returns (bool) { return state.validFactories[_factory]; } /** * Return boolean indicating if address is valid module. * * @param _module Factory address * @return bool Boolean indicating if enabled factory */ function validModules( address _module ) external view returns (bool) { return state.validModules[_module]; } /** * Return boolean indicating if address is valid Set. * * @param _set Set address * @return bool Boolean indicating if valid Set */ function validSets( address _set ) external view returns (bool) { return state.validSets[_set]; } /** * Return boolean indicating if address is a disabled Set. * * @param _set Set address * @return bool Boolean indicating if is a disabled Set */ function disabledSets( address _set ) external view returns (bool) { return state.disabledSets[_set]; } /** * Return boolean indicating if address is a valid Rebalancing Price Library. * * @param _priceLibrary Price library address * @return bool Boolean indicating if valid Price Library */ function validPriceLibraries( address _priceLibrary ) external view returns (bool) { return state.validPriceLibraries[_priceLibrary]; } /** * Return array of all valid Set Tokens. * * @return address[] Array of valid Set Tokens */ function setTokens() external view returns (address[] memory) { return state.setTokens; } /** * Return array of all valid Modules. * * @return address[] Array of valid modules */ function modules() external view returns (address[] memory) { return state.modules; } /** * Return array of all valid factories. * * @return address[] Array of valid factories */ function factories() external view returns (address[] memory) { return state.factories; } /** * Return array of all valid exchange wrappers. * * @return address[] Array of valid exchange wrappers */ function exchanges() external view returns (address[] memory) { return state.exchanges; } /** * Return array of all valid price libraries. * * @return address[] Array of valid price libraries */ function priceLibraries() external view returns (address[] memory) { return state.priceLibraries; } } // File: contracts/core/extensions/CoreOperationState.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreOperationState * @author Set Protocol * * The CoreOperationState contract contains methods to alter state of variables that track * Core dependency addresses. */ contract CoreOperationState is Ownable, CoreState { /* ============ Enum ============ */ /** * Operational: * All Accounting and Issuance related functions are available for usage during this stage * * Shut Down: * Only functions which allow users to redeem and withdraw funds are allowed during this stage */ enum OperationState { Operational, ShutDown, InvalidState } /* ============ Events ============ */ event OperationStateChanged( uint8 _prevState, uint8 _newState ); /* ============ Modifiers ============ */ modifier whenOperational() { require( state.operationState == uint8(OperationState.Operational), "WhenOperational" ); _; } /* ============ External Functions ============ */ /** * Updates the operation state of the protocol. * Can only be called by owner of Core. * * @param _operationState Uint8 representing the current protocol operation state */ function setOperationState( uint8 _operationState ) external onlyOwner { require( _operationState < uint8(OperationState.InvalidState) && _operationState != state.operationState, "InvalidOperationState" ); emit OperationStateChanged( state.operationState, _operationState ); state.operationState = _operationState; } } // File: contracts/core/extensions/CoreAccounting.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreAccounting * @author Set Protocol * * The CoreAccounting contract interfaces with the vault and transfer proxies for * storage of tokenized assets. */ contract CoreAccounting is CoreState, CoreOperationState, ReentrancyGuard { // Use SafeMath library for all uint256 arithmetic using SafeMath for uint256; /* ============ External Functions ============ */ /** * Deposit a quantity of tokens to the vault and attribute to sender. * * @param _token Address of the token * @param _quantity Amount of tokens to deposit */ function deposit( address _token, uint256 _quantity ) external nonReentrant whenOperational { // Don't deposit if quantity <= 0 if (_quantity > 0) { // Call TransferProxy contract to transfer user tokens to Vault state.transferProxyInstance.transfer( _token, _quantity, msg.sender, state.vault ); // Call Vault contract to attribute deposited tokens to user state.vaultInstance.incrementTokenOwner( _token, msg.sender, _quantity ); } } /** * Withdraw a quantity of tokens from the vault and deattribute from sender. * * @param _token Address of the token * @param _quantity Amount of tokens to withdraw */ function withdraw( address _token, uint256 _quantity ) external nonReentrant { // Don't withdraw if quantity <= 0 if (_quantity > 0) { // Call Vault contract to deattribute withdrawn tokens from user state.vaultInstance.decrementTokenOwner( _token, msg.sender, _quantity ); // Call Vault contract to withdraw tokens from Vault to user state.vaultInstance.withdrawTo( _token, msg.sender, _quantity ); } } /** * Deposit multiple tokens to the vault and attribute to sender. * Quantities should be in the order of the addresses of the tokens being deposited. * * @param _tokens Array of the addresses of the tokens * @param _quantities Array of the amounts of tokens to deposit */ function batchDeposit( address[] calldata _tokens, uint256[] calldata _quantities ) external nonReentrant whenOperational { // Call internal batch deposit function batchDepositInternal( msg.sender, msg.sender, _tokens, _quantities ); } /** * Withdraw multiple tokens from the vault and deattribute from sender. * Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _tokens Array of the addresses of the tokens * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdraw( address[] calldata _tokens, uint256[] calldata _quantities ) external nonReentrant { // Call internal batch withdraw function batchWithdrawInternal( msg.sender, msg.sender, _tokens, _quantities ); } /** * Transfer tokens associated with the sender's account in vault to another user's * account in vault. * * @param _token Address of token being transferred * @param _to Address of user receiving tokens * @param _quantity Amount of tokens being transferred */ function internalTransfer( address _token, address _to, uint256 _quantity ) external nonReentrant whenOperational { state.vaultInstance.transferBalance( _token, msg.sender, _to, _quantity ); } /* ============ Internal Functions ============ */ /** * Internal function that deposits multiple tokens to the vault. * Quantities should be in the order of the addresses of the tokens being deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositInternal( address _from, address _to, address[] memory _tokens, uint256[] memory _quantities ) internal whenOperational { // Confirm an empty _tokens or quantity array is not passed CommonValidationsLibrary.validateNonEmpty(_tokens); // Confirm there is one quantity for every token address CommonValidationsLibrary.validateEqualLength(_tokens, _quantities); state.transferProxyInstance.batchTransfer( _tokens, _quantities, _from, state.vault ); state.vaultInstance.batchIncrementTokenOwner( _tokens, _to, _quantities ); } /** * Internal function that withdraws multiple tokens from the vault. * Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawInternal( address _from, address _to, address[] memory _tokens, uint256[] memory _quantities ) internal { // Confirm an empty _tokens or quantity array is not passed CommonValidationsLibrary.validateNonEmpty(_tokens); // Confirm there is one quantity for every token address CommonValidationsLibrary.validateEqualLength(_tokens, _quantities); // Call Vault contract to deattribute withdrawn tokens from user state.vaultInstance.batchDecrementTokenOwner( _tokens, _from, _quantities ); // Call Vault contract to withdraw tokens from Vault to user state.vaultInstance.batchWithdrawTo( _tokens, _to, _quantities ); } } // File: contracts/lib/AddressArrayUtils.sol // Pulled in from Cryptofin Solidity package in order to control Solidity compiler version // https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol pragma solidity 0.5.7; library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { bool isIn; (, isIn) = indexOf(A, a); return isIn; } /// @return Returns index and isIn for the first occurrence starting from /// end function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = length; i > 0; i--) { if (A[i - 1] == a) { return (i, true); } } return (0, false); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Returns the array with a appended to A. * @param A The first array * @param a The value to append * @return Returns A appended by a */ function append(address[] memory A, address a) internal pure returns (address[] memory) { address[] memory newAddresses = new address[](A.length + 1); for (uint256 i = 0; i < A.length; i++) { newAddresses[i] = A[i]; } newAddresses[A.length] = a; return newAddresses; } /** * Returns the combination of two storage arrays. * @param A The first array * @param B The second array * @return Returns A appended by a */ function sExtend(address[] storage A, address[] storage B) internal { uint256 length = B.length; for (uint256 i = 0; i < length; i++) { A.push(B[i]); } } /** * Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept. * @param A The first array * @param B The second array * @return The intersection of the two arrays */ function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } address[] memory newAddresses = new address[](newLength); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * Returns the union of the two arrays. Order is not guaranteed. * @param A The first array * @param B The second array * @return The union of the two arrays */ function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) { address[] memory leftDifference = difference(A, B); address[] memory rightDifference = difference(B, A); address[] memory intersection = intersect(A, B); return extend(leftDifference, extend(intersection, rightDifference)); } /** * Alternate implementation * Assumes there are no duplicates */ function unionB(address[] memory A, address[] memory B) internal pure returns (address[] memory) { bool[] memory includeMap = new bool[](A.length + B.length); uint256 count = 0; for (uint256 i = 0; i < A.length; i++) { includeMap[i] = true; count++; } for (uint256 j = 0; j < B.length; j++) { if (!contains(A, B[j])) { includeMap[A.length + j] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 k = 0; for (uint256 m = 0; m < A.length; m++) { if (includeMap[m]) { newAddresses[k] = A[m]; k++; } } for (uint256 n = 0; n < B.length; n++) { if (includeMap[A.length + n]) { newAddresses[k] = B[n]; k++; } } return newAddresses; } /** * Computes the difference of two arrays. Assumes there are no duplicates. * @param A The first array * @param B The second array * @return The difference of the two arrays */ function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { address e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } address[] memory newAddresses = new address[](count); uint256 j = 0; for (uint256 k = 0; k < length; k++) { if (includeMap[k]) { newAddresses[j] = A[k]; j++; } } return newAddresses; } /** * @dev Reverses storage array in place */ function sReverse(address[] storage A) internal { address t; uint256 length = A.length; for (uint256 i = 0; i < length / 2; i++) { t = A[i]; A[i] = A[A.length - i - 1]; A[A.length - i - 1] = t; } } /** * Removes specified index from array * Resulting ordering is not guaranteed * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * @return Returns the new array */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert(); } else { (address[] memory _A,) = pop(A, index); return _A; } } function sPop(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; for (uint256 i = index; i < length - 1; i++) { A[i] = A[i + 1]; } A.length--; return entry; } /** * Deletes address at index and fills the spot with the last address. * Order is not preserved. * @return Returns the removed entry */ function sPopCheap(address[] storage A, uint256 index) internal returns (address) { uint256 length = A.length; if (index >= length) { revert("Error: index out of bounds"); } address entry = A[index]; if (index != length - 1) { A[index] = A[length - 1]; delete A[length - 1]; } A.length--; return entry; } /** * Deletes address at index. Works by swapping it with the last address, then deleting. * Order is not preserved * @param A Storage array to remove from */ function sRemoveCheap(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Error: entry not found"); } else { sPopCheap(A, index); return; } } /** * Returns whether or not there's a duplicate. Runs in O(n^2). * @param A Array to search * @return Returns true if duplicate, false otherwise */ function hasDuplicate(address[] memory A) internal pure returns (bool) { if (A.length == 0) { return false; } for (uint256 i = 0; i < A.length - 1; i++) { for (uint256 j = i + 1; j < A.length; j++) { if (A[i] == A[j]) { return true; } } } return false; } /** * Returns whether the two arrays are equal. * @param A The first array * @param B The second array * @return True is the arrays are equal, false if not. */ function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) { if (A.length != B.length) { return false; } for (uint256 i = 0; i < A.length; i++) { if (A[i] != B[i]) { return false; } } return true; } /** * Returns the elements indexed at indexArray. * @param A The array to index * @param indexArray The array to use to index * @return Returns array containing elements indexed at indexArray */ function argGet(address[] memory A, uint256[] memory indexArray) internal pure returns (address[] memory) { address[] memory array = new address[](indexArray.length); for (uint256 i = 0; i < indexArray.length; i++) { array[i] = A[indexArray[i]]; } return array; } } // File: contracts/lib/TimeLockUpgrade.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title TimeLockUpgrade * @author Set Protocol * * The TimeLockUpgrade contract contains a modifier for handling minimum time period updates */ contract TimeLockUpgrade is Ownable { using SafeMath for uint256; /* ============ State Variables ============ */ // Timelock Upgrade Period in seconds uint256 public timeLockPeriod; // Mapping of upgradable units and initialized timelock mapping(bytes32 => uint256) public timeLockedUpgrades; /* ============ Events ============ */ event UpgradeRegistered( bytes32 _upgradeHash, uint256 _timestamp ); /* ============ Modifiers ============ */ modifier timeLockUpgrade() { // If the time lock period is 0, then allow non-timebound upgrades. // This is useful for initialization of the protocol and for testing. if (timeLockPeriod == 0) { _; return; } // The upgrade hash is defined by the hash of the transaction call data, // which uniquely identifies the function as well as the passed in arguments. bytes32 upgradeHash = keccak256( abi.encodePacked( msg.data ) ); uint256 registrationTime = timeLockedUpgrades[upgradeHash]; // If the upgrade hasn't been registered, register with the current time. if (registrationTime == 0) { timeLockedUpgrades[upgradeHash] = block.timestamp; emit UpgradeRegistered( upgradeHash, block.timestamp ); return; } require( block.timestamp >= registrationTime.add(timeLockPeriod), "TimeLockUpgrade: Time lock period must have elapsed." ); // Reset the timestamp to 0 timeLockedUpgrades[upgradeHash] = 0; // Run the rest of the upgrades _; } /* ============ Function ============ */ /** * Change timeLockPeriod period. Generally called after initially settings have been set up. * * @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution */ function setTimeLockPeriod( uint256 _timeLockPeriod ) external onlyOwner { // Only allow setting of the timeLockPeriod if the period is greater than the existing require( _timeLockPeriod > timeLockPeriod, "TimeLockUpgrade: New period must be greater than existing" ); timeLockPeriod = _timeLockPeriod; } } // File: contracts/core/extensions/CoreAdmin.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreAdmin * @author Set Protocol * * The CoreAdmin contract contains methods to alter state of variables that track * Core dependency addresses. */ contract CoreAdmin is Ownable, CoreState, TimeLockUpgrade { using AddressArrayUtils for address[]; /* ============ Events ============ */ event FactoryAdded( address _factory ); event FactoryRemoved( address _factory ); event ExchangeAdded( uint8 _exchangeId, address _exchange ); event ExchangeRemoved( uint8 _exchangeId ); event ModuleAdded( address _module ); event ModuleRemoved( address _module ); event SetDisabled( address _set ); event SetReenabled( address _set ); event PriceLibraryAdded( address _priceLibrary ); event PriceLibraryRemoved( address _priceLibrary ); /* ============ External Functions ============ */ /** * Add a factory from the mapping of tracked factories. * Can only be called by owner of Core. * * @param _factory Address of the factory conforming to ISetFactory */ function addFactory( address _factory ) external onlyOwner timeLockUpgrade { require( !state.validFactories[_factory] ); state.validFactories[_factory] = true; state.factories = state.factories.append(_factory); emit FactoryAdded( _factory ); } /** * Remove a factory from the mapping of tracked factories. * Can only be called by owner of Core. * * @param _factory Address of the factory conforming to ISetFactory */ function removeFactory( address _factory ) external onlyOwner { require( state.validFactories[_factory] ); state.factories = state.factories.remove(_factory); state.validFactories[_factory] = false; emit FactoryRemoved( _factory ); } /** * Add an exchange address with the mapping of tracked exchanges. * Can only be called by owner of Core. * * @param _exchangeId Enumeration of exchange within the mapping * @param _exchange Address of the exchange conforming to IExchangeWrapper */ function addExchange( uint8 _exchangeId, address _exchange ) external onlyOwner timeLockUpgrade { require( state.exchangeIds[_exchangeId] == address(0) ); state.exchangeIds[_exchangeId] = _exchange; state.exchanges = state.exchanges.append(_exchange); emit ExchangeAdded( _exchangeId, _exchange ); } /** * Remove an exchange address with the mapping of tracked exchanges. * Can only be called by owner of Core. * * @param _exchangeId Enumeration of exchange within the mapping * @param _exchange Address of the exchange conforming to IExchangeWrapper */ function removeExchange( uint8 _exchangeId, address _exchange ) external onlyOwner { require( state.exchangeIds[_exchangeId] != address(0) && state.exchangeIds[_exchangeId] == _exchange ); state.exchanges = state.exchanges.remove(_exchange); state.exchangeIds[_exchangeId] = address(0); emit ExchangeRemoved( _exchangeId ); } /** * Add a module address with the mapping of tracked modules. * Can only be called by owner of Core. * * @param _module Address of the module */ function addModule( address _module ) external onlyOwner timeLockUpgrade { require( !state.validModules[_module] ); state.validModules[_module] = true; state.modules = state.modules.append(_module); emit ModuleAdded( _module ); } /** * Remove a module address with the mapping of tracked modules. * Can only be called by owner of Core. * * @param _module Enumeration of module within the mapping */ function removeModule( address _module ) external onlyOwner { require( state.validModules[_module] ); state.modules = state.modules.remove(_module); state.validModules[_module] = false; emit ModuleRemoved( _module ); } /** * Disables a Set from the mapping and array of tracked Sets. * Can only be called by owner of Core. * * @param _set Address of the Set */ function disableSet( address _set ) external onlyOwner { require( state.validSets[_set] ); state.setTokens = state.setTokens.remove(_set); state.validSets[_set] = false; state.disabledSets[_set] = true; emit SetDisabled( _set ); } /** * Enables a Set from the mapping and array of tracked Sets if it has been previously disabled * Can only be called by owner of Core. * * @param _set Address of the Set */ function reenableSet( address _set ) external onlyOwner { require( state.disabledSets[_set] ); state.setTokens = state.setTokens.append(_set); state.validSets[_set] = true; state.disabledSets[_set] = false; emit SetReenabled( _set ); } /** * Add a price library from the mapping of tracked price libraries. * Can only be called by owner of Core. * * @param _priceLibrary Address of the price library */ function addPriceLibrary( address _priceLibrary ) external onlyOwner timeLockUpgrade { require( !state.validPriceLibraries[_priceLibrary] ); state.validPriceLibraries[_priceLibrary] = true; state.priceLibraries = state.priceLibraries.append(_priceLibrary); emit PriceLibraryAdded( _priceLibrary ); } /** * Remove a price library from the mapping of tracked price libraries. * Can only be called by owner of Core. * * @param _priceLibrary Address of the price library */ function removePriceLibrary( address _priceLibrary ) external onlyOwner { require( state.validPriceLibraries[_priceLibrary] ); state.priceLibraries = state.priceLibraries.remove(_priceLibrary); state.validPriceLibraries[_priceLibrary] = false; emit PriceLibraryRemoved( _priceLibrary ); } } // File: contracts/core/interfaces/ISetFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetFactory * @author Set Protocol * * The ISetFactory interface provides operability for authorized contracts * to interact with SetTokenFactory */ interface ISetFactory { /* ============ External Functions ============ */ /** * Return core address * * @return address core address */ function core() external returns (address); /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address[] calldata _components, uint[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address); } // File: contracts/core/extensions/CoreFactory.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreFactory * @author Set Protocol * * The CoreFactory contract contains Set Token creation operations */ contract CoreFactory is CoreState { /* ============ Events ============ */ event SetTokenCreated( address indexed _setTokenAddress, address _factory, address[] _components, uint256[] _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol ); /* ============ External Functions ============ */ /** * Deploys a new Set Token and adds it to the valid list of SetTokens * * @param _factory The address of the Factory to create from * @param _components The address of component tokens * @param _units The units of each component token * @param _naturalUnit The minimum unit to be issued or redeemed * @param _name The bytes32 encoded name of the new Set * @param _symbol The bytes32 encoded symbol of the new Set * @param _callData Byte string containing additional call parameters * @return setTokenAddress The address of the new Set */ function createSet( address _factory, address[] calldata _components, uint256[] calldata _units, uint256 _naturalUnit, bytes32 _name, bytes32 _symbol, bytes calldata _callData ) external returns (address) { // Verify Factory is linked to Core require( state.validFactories[_factory], "CreateSet" ); // Create the Set address newSetTokenAddress = ISetFactory(_factory).createSet( _components, _units, _naturalUnit, _name, _symbol, _callData ); // Add Set to the mapping of tracked Sets state.validSets[newSetTokenAddress] = true; // Add Set to the array of tracked Sets state.setTokens.push(newSetTokenAddress); // Emit Set Token creation log emit SetTokenCreated( newSetTokenAddress, _factory, _components, _units, _naturalUnit, _name, _symbol ); return newSetTokenAddress; } } // File: contracts/lib/CommonMath.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library CommonMath { using SafeMath for uint256; /** * Calculates and returns the maximum value for a uint256 * * @return The maximum value for uint256 */ function maxUInt256() internal pure returns (uint256) { return 2 ** 256 - 1; } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * Checks for rounding errors and returns value of potential partial amounts of a principal * * @param _principal Number fractional amount is derived from * @param _numerator Numerator of fraction * @param _denominator Denominator of fraction * @return uint256 Fractional amount of principal calculated */ function getPartialAmount( uint256 _principal, uint256 _numerator, uint256 _denominator ) internal pure returns (uint256) { // Get remainder of partial amount (if 0 not a partial amount) uint256 remainder = mulmod(_principal, _numerator, _denominator); // Return if not a partial amount if (remainder == 0) { return _principal.mul(_numerator).div(_denominator); } // Calculate error percentage uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal)); // Require error percentage is less than 0.1%. require( errPercentageTimes1000000 < 1000, "CommonMath.getPartialAmount: Rounding error exceeds bounds" ); return _principal.mul(_numerator).div(_denominator); } } // File: contracts/core/lib/CoreIssuanceLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreIssuanceLibrary * @author Set Protocol * * This library contains functions for calculating deposit, withdrawal,and transfer quantities */ library CoreIssuanceLibrary { using SafeMath for uint256; /** * Calculate the quantities required to deposit and decrement during issuance. Takes into account * the tokens an owner already has in the vault. * * @param _components Addresses of components * @param _componentQuantities Component quantities to increment and withdraw * @param _owner Address to deposit and decrement quantities from * @param _vault Address to vault * @return uint256[] decrementQuantities Quantities to decrement from vault * @return uint256[] depositQuantities Quantities to deposit into the vault */ function calculateDepositAndDecrementQuantities( address[] calldata _components, uint256[] calldata _componentQuantities, address _owner, address _vault ) external view returns ( uint256[] memory /* decrementQuantities */, uint256[] memory /* depositQuantities */ ) { uint256 componentCount = _components.length; uint256[] memory decrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory depositQuantities = new uint256[](componentCount); for (uint256 i = 0; i < componentCount; i++) { // Fetch component quantity in vault uint256 vaultBalance = IVault(_vault).getOwnerBalance( _components[i], _owner ); // If the vault holds enough components, decrement the full amount if (vaultBalance >= _componentQuantities[i]) { decrementTokenOwnerValues[i] = _componentQuantities[i]; } else { // User has less than required amount, decrement the vault by full balance if (vaultBalance > 0) { decrementTokenOwnerValues[i] = vaultBalance; } depositQuantities[i] = _componentQuantities[i].sub(vaultBalance); } } return ( decrementTokenOwnerValues, depositQuantities ); } /** * Calculate the quantities required to withdraw and increment during redeem and withdraw. Takes into * account a bitmask exclusion parameter. * * @param _componentQuantities Component quantities to increment and withdraw * @param _toExclude Mask of indexes of tokens to exclude from withdrawing * @return uint256[] incrementQuantities Quantities to increment in vault * @return uint256[] withdrawQuantities Quantities to withdraw from vault */ function calculateWithdrawAndIncrementQuantities( uint256[] calldata _componentQuantities, uint256 _toExclude ) external pure returns ( uint256[] memory /* incrementQuantities */, uint256[] memory /* withdrawQuantities */ ) { uint256 componentCount = _componentQuantities.length; uint256[] memory incrementTokenOwnerValues = new uint256[](componentCount); uint256[] memory withdrawToValues = new uint256[](componentCount); // Loop through and decrement vault balances for the set, withdrawing if requested for (uint256 i = 0; i < componentCount; i++) { // Calculate bit index of current component uint256 componentBitIndex = CommonMath.safePower(2, i); // Transfer to user unless component index is included in _toExclude if ((_toExclude & componentBitIndex) != 0) { incrementTokenOwnerValues[i] = _componentQuantities[i]; } else { withdrawToValues[i] = _componentQuantities[i]; } } return ( incrementTokenOwnerValues, withdrawToValues ); } /** * Calculate the required component quantities required for issuance or rdemption for a given * quantity of Set Tokens * * @param _componentUnits The units of the component token * @param _naturalUnit The natural unit of the Set token * @param _quantity The number of tokens being redeem * @return uint256[] Required quantities in base units of components */ function calculateRequiredComponentQuantities( uint256[] calldata _componentUnits, uint256 _naturalUnit, uint256 _quantity ) external pure returns (uint256[] memory) { require( _quantity.mod(_naturalUnit) == 0, "CoreIssuanceLibrary: Quantity must be a multiple of nat unit" ); uint256[] memory tokenValues = new uint256[](_componentUnits.length); // Transfer the underlying tokens to the corresponding token balances for (uint256 i = 0; i < _componentUnits.length; i++) { tokenValues[i] = _quantity.div(_naturalUnit).mul(_componentUnits[i]); } return tokenValues; } } // File: contracts/core/interfaces/ISetToken.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ISetToken * @author Set Protocol * * The ISetToken interface provides a light-weight, structured way to interact with the * SetToken contract from another contract. */ interface ISetToken { /* ============ External Functions ============ */ /* * Get natural unit of Set * * @return uint256 Natural unit of Set */ function naturalUnit() external view returns (uint256); /* * Get addresses of all components in the Set * * @return componentAddresses Array of component tokens */ function getComponents() external view returns (address[] memory); /* * Get units of all tokens in Set * * @return units Array of component units */ function getUnits() external view returns (uint256[] memory); /* * Checks to make sure token is component of Set * * @param _tokenAddress Address of token being checked * @return bool True if token is component of Set */ function tokenIsComponent( address _tokenAddress ) external view returns (bool); /* * Mint set token for given address. * Can only be called by authorized contracts. * * @param _issuer The address of the issuing account * @param _quantity The number of sets to attribute to issuer */ function mint( address _issuer, uint256 _quantity ) external; /* * Burn set token for given address * Can only be called by authorized contracts * * @param _from The address of the redeeming account * @param _quantity The number of sets to burn from redeemer */ function burn( address _from, uint256 _quantity ) external; /** * Transfer token for a specified address * * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer( address to, uint256 value ) external; } // File: contracts/core/lib/SetTokenLibrary.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; library SetTokenLibrary { using SafeMath for uint256; struct SetDetails { uint256 naturalUnit; address[] components; uint256[] units; } /** * Validates that passed in tokens are all components of the Set * * @param _set Address of the Set * @param _tokens List of tokens to check */ function validateTokensAreComponents( address _set, address[] calldata _tokens ) external view { for (uint256 i = 0; i < _tokens.length; i++) { // Make sure all tokens are members of the Set require( ISetToken(_set).tokenIsComponent(_tokens[i]), "SetTokenLibrary.validateTokensAreComponents: Component must be a member of Set" ); } } /** * Validates that passed in quantity is a multiple of the natural unit of the Set. * * @param _set Address of the Set * @param _quantity Quantity to validate */ function isMultipleOfSetNaturalUnit( address _set, uint256 _quantity ) external view { require( _quantity.mod(ISetToken(_set).naturalUnit()) == 0, "SetTokenLibrary.isMultipleOfSetNaturalUnit: Quantity is not a multiple of nat unit" ); } /** * Retrieves the Set's natural unit, components, and units. * * @param _set Address of the Set * @return SetDetails Struct containing the natural unit, components, and units */ function getSetDetails( address _set ) internal view returns (SetDetails memory) { // Declare interface variables ISetToken setToken = ISetToken(_set); // Fetch set token properties uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); uint256[] memory units = setToken.getUnits(); return SetDetails({ naturalUnit: naturalUnit, components: components, units: units }); } } // File: contracts/core/extensions/CoreIssuance.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreIssuance * @author Set Protocol * * The CoreIssuance contract contains function related to issuing and redeeming Sets. */ contract CoreIssuance is CoreState, CoreOperationState, ReentrancyGuard { // Use SafeMath library for all uint256 arithmetic using SafeMath for uint256; /* ============ Events ============ */ event SetIssued( address _setAddress, uint256 _quantity ); event SetRedeemed( address _setAddress, uint256 _quantity ); /* ============ External Functions ============ */ /** * Issues a specified Set for a specified quantity to the caller * using the caller's components from the wallet and vault. * * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issue( address _set, uint256 _quantity ) external nonReentrant { issueInternal( msg.sender, msg.sender, _set, _quantity ); } /** * Converts user's components into Set Tokens owned by the user and stored in Vault * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVault( address _set, uint256 _quantity ) external nonReentrant { issueInVaultInternal( msg.sender, _set, _quantity ); } /** * Issues a specified Set for a specified quantity to the recipient * using the caller's components from the wallet and vault. * * @param _recipient Address to issue to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueTo( address _recipient, address _set, uint256 _quantity ) external nonReentrant { issueInternal( msg.sender, _recipient, _set, _quantity ); } /** * Exchange Set tokens for underlying components to the user held in the Vault. * * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeem( address _set, uint256 _quantity ) external nonReentrant { redeemInternal( msg.sender, msg.sender, _set, _quantity ); } /** * Composite method to redeem and withdraw with a single transaction * * Normally, you should expect to be able to withdraw all of the tokens. * However, some have central abilities to freeze transfers (e.g. EOS). _toExclude * allows you to optionally specify which component tokens to exclude when * redeeming. They will remain in the vault under the users' addresses. * * @param _set Address of the Set * @param _to Address to withdraw or attribute tokens to * @param _quantity Number of tokens to redeem * @param _toExclude Mask of indexes of tokens to exclude from withdrawing */ function redeemAndWithdrawTo( address _set, address _to, uint256 _quantity, uint256 _toExclude ) external nonReentrant { uint256[] memory componentTransferValues = redeemAndDecrementVault( _set, msg.sender, _quantity ); // Calculate the withdraw and increment quantities to specified address uint256[] memory incrementTokenOwnerValues; uint256[] memory withdrawToValues; ( incrementTokenOwnerValues, withdrawToValues ) = CoreIssuanceLibrary.calculateWithdrawAndIncrementQuantities( componentTransferValues, _toExclude ); address[] memory components = ISetToken(_set).getComponents(); // Increment excluded components to the specified address state.vaultInstance.batchIncrementTokenOwner( components, _to, incrementTokenOwnerValues ); // Withdraw non-excluded components and attribute to specified address state.vaultInstance.batchWithdrawTo( components, _to, withdrawToValues ); } /** * Convert the caller's Set tokens held in the vault into underlying components to the user * held in the Vault. * * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemInVault( address _set, uint256 _quantity ) external nonReentrant { // Decrement ownership of Set token in the vault state.vaultInstance.decrementTokenOwner( _set, msg.sender, _quantity ); redeemInternal( state.vault, msg.sender, _set, _quantity ); } /** * Redeem Set token and return components to specified recipient. The components * are left in the vault after redemption in the recipient's name. * * @param _recipient Recipient of Set being issued * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function redeemTo( address _recipient, address _set, uint256 _quantity ) external nonReentrant { redeemInternal( msg.sender, _recipient, _set, _quantity ); } /* ============ Internal Functions ============ */ /** * Exchange components for Set tokens, accepting any owner * Used in issue, issueTo, and issueInVaultInternal * * @param _componentOwner Address to use tokens from * @param _setRecipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueInternal( address _componentOwner, address _setRecipient, address _set, uint256 _quantity ) internal whenOperational { // Verify Set was created by Core and is enabled require( state.validSets[_set], "IssueInternal" ); // Validate quantity is multiple of natural unit SetTokenLibrary.isMultipleOfSetNaturalUnit(_set, _quantity); SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(_set); // Calculate component quantities required to issue uint256[] memory requiredComponentQuantities = CoreIssuanceLibrary.calculateRequiredComponentQuantities( setToken.units, setToken.naturalUnit, _quantity ); // Calculate the withdraw and increment quantities to caller uint256[] memory decrementTokenOwnerValues; uint256[] memory depositValues; ( decrementTokenOwnerValues, depositValues ) = CoreIssuanceLibrary.calculateDepositAndDecrementQuantities( setToken.components, requiredComponentQuantities, _componentOwner, state.vault ); // Decrement components used for issuance in vault state.vaultInstance.batchDecrementTokenOwner( setToken.components, _componentOwner, decrementTokenOwnerValues ); // Deposit tokens used for issuance into vault state.transferProxyInstance.batchTransfer( setToken.components, depositValues, _componentOwner, state.vault ); // Increment the vault balance of the set token for the components state.vaultInstance.batchIncrementTokenOwner( setToken.components, _set, requiredComponentQuantities ); // Issue set token ISetToken(_set).mint( _setRecipient, _quantity ); emit SetIssued( _set, _quantity ); } /** * Converts recipient's components into Set Tokens held directly in Vault. * Used in issueInVault * * @param _recipient Address to issue to * @param _set Address of the Set * @param _quantity Number of tokens to issue */ function issueInVaultInternal( address _recipient, address _set, uint256 _quantity ) internal { issueInternal( _recipient, state.vault, _set, _quantity ); // Increment ownership of Set token in the vault state.vaultInstance.incrementTokenOwner( _set, _recipient, _quantity ); } /** * Exchange Set tokens for underlying components. Components are attributed in the vault. * Used in redeem, redeemInVault, and redeemTo * * @param _burnAddress Address to burn tokens from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemInternal( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) internal { uint256[] memory componentQuantities = redeemAndDecrementVault( _set, _burnAddress, _quantity ); // Increment the component amount address[] memory components = ISetToken(_set).getComponents(); state.vaultInstance.batchIncrementTokenOwner( components, _incrementAddress, componentQuantities ); } /** * Private method that validates inputs, redeems Set, and decrements * the components in the vault * * @param _set Address of the Set to redeem * @param _burnAddress Address to burn tokens from * @param _quantity Number of tokens to redeem * @return componentQuantities Transfer value of components */ function redeemAndDecrementVault( address _set, address _burnAddress, uint256 _quantity ) private returns (uint256[] memory) { // Verify Set was created by Core and is enabled require( state.validSets[_set], "RedeemAndDecrementVault" ); // Validate quantity is multiple of natural unit SetTokenLibrary.isMultipleOfSetNaturalUnit(_set, _quantity); // Burn the Set token (thereby decrementing the Set balance) ISetToken(_set).burn( _burnAddress, _quantity ); SetTokenLibrary.SetDetails memory setToken = SetTokenLibrary.getSetDetails(_set); // Calculate component quantities to redeem uint256[] memory componentQuantities = CoreIssuanceLibrary.calculateRequiredComponentQuantities( setToken.units, setToken.naturalUnit, _quantity ); // Decrement components from Set's possession state.vaultInstance.batchDecrementTokenOwner( setToken.components, _set, componentQuantities ); emit SetRedeemed( _set, _quantity ); return componentQuantities; } } // File: contracts/core/interfaces/ICoreAccounting.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICoreAccounting * @author Set Protocol * * The ICoreAccounting Contract defines all the functions exposed in the CoreIssuance * extension. */ contract ICoreAccounting { /* ============ Internal Functions ============ */ /** * Internal function that deposits multiple tokens to the vault. * Quantities should be in the order of the addresses of the tokens being deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositInternal( address _from, address _to, address[] memory _tokens, uint[] memory _quantities ) internal; /** * Internal function that withdraws multiple tokens from the vault. * Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawInternal( address _from, address _to, address[] memory _tokens, uint256[] memory _quantities ) internal; } // File: contracts/core/interfaces/ICoreIssuance.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title ICoreIssuance * @author Set Protocol * * The ICoreIssuance Contract defines all the functions exposed in the CoreIssuance * extension. */ contract ICoreIssuance { /* ============ Internal Functions ============ */ /** * Exchange components for Set tokens, accepting any owner * * @param _owner Address to use tokens from * @param _recipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueInternal( address _owner, address _recipient, address _set, uint256 _quantity ) internal; /** * Converts recipient's components into Set Tokens held directly in Vault * * @param _recipient Address to issue to * @param _set Address of the Set * @param _quantity Number of tokens to issue */ function issueInVaultInternal( address _recipient, address _set, uint256 _quantity ) internal; /** * Exchange Set tokens for underlying components * * @param _burnAddress Address to burn tokens from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemInternal( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) internal; } // File: contracts/core/extensions/CoreModuleInteraction.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title CoreModularInteraction * @author Set Protocol * * Extension used to expose internal accounting and issuance functions, vault, and proxy functions * to modules. */ contract CoreModuleInteraction is ICoreAccounting, ICoreIssuance, CoreState, ReentrancyGuard { modifier onlyModule() { onlyModuleCallable(); _; } function onlyModuleCallable() internal view { require( state.validModules[msg.sender], "OnlyModule" ); } /** * Exposes internal function that deposits tokens to the vault, exposed to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _token Address of the token being deposited * @param _quantity Amount of tokens to deposit */ function depositModule( address _from, address _to, address _token, uint256 _quantity ) external onlyModule { address[] memory tokenArray = new address[](1); tokenArray[0] = _token; uint256[] memory quantityArray = new uint256[](1); quantityArray[0] = _quantity; batchDepositInternal( _from, _to, tokenArray, quantityArray ); } /** * Exposes internal function that deposits multiple tokens to the vault, exposed to system * modules. Quantities should be in the order of the addresses of the tokens being * deposited. * * @param _from Address to transfer tokens from * @param _to Address to credit for deposits * @param _tokens Array of the addresses of the tokens being deposited * @param _quantities Array of the amounts of tokens to deposit */ function batchDepositModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external onlyModule { batchDepositInternal( _from, _to, _tokens, _quantities ); } /** * Exposes internal function that withdraws multiple tokens to the vault, exposed to system * modules. Quantities should be in the order of the addresses of the tokens being * withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _token Address of the token being withdrawn * @param _quantity Amount of tokens to withdraw */ function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external onlyModule { address[] memory tokenArray = new address[](1); tokenArray[0] = _token; uint256[] memory quantityArray = new uint256[](1); quantityArray[0] = _quantity; batchWithdrawInternal( _from, _to, tokenArray, quantityArray ); } /** * Exposes internal function that withdraws multiple tokens from the vault, to system * modules. Quantities should be in the order of the addresses of the tokens being withdrawn. * * @param _from Address to decredit for withdrawals * @param _to Address to transfer tokens to * @param _tokens Array of the addresses of the tokens being withdrawn * @param _quantities Array of the amounts of tokens to withdraw */ function batchWithdrawModule( address _from, address _to, address[] calldata _tokens, uint256[] calldata _quantities ) external onlyModule { batchWithdrawInternal( _from, _to, _tokens, _quantities ); } /** * Expose internal function that exchanges components for Set tokens, * accepting any owner, to system modules * * @param _componentOwner Address to use tokens from * @param _setRecipient Address to issue Set to * @param _set Address of the Set to issue * @param _quantity Number of tokens to issue */ function issueModule( address _componentOwner, address _setRecipient, address _set, uint256 _quantity ) external onlyModule { issueInternal( _componentOwner, _setRecipient, _set, _quantity ); } /** * Converts recipient's components into Set Token's held directly in Vault * * @param _recipient Address to issue to * @param _set Address of the Set * @param _quantity Number of tokens to redeem */ function issueInVaultModule( address _recipient, address _set, uint256 _quantity ) external onlyModule { issueInVaultInternal( _recipient, _set, _quantity ); } /** * Expose internal function that exchanges Set tokens for components, * accepting any owner, to system modules * * @param _burnAddress Address to burn token from * @param _incrementAddress Address to increment component tokens to * @param _set Address of the Set to redeem * @param _quantity Number of tokens to redeem */ function redeemModule( address _burnAddress, address _incrementAddress, address _set, uint256 _quantity ) external onlyModule { redeemInternal( _burnAddress, _incrementAddress, _set, _quantity ); } /** * Expose vault function that increments user's balance in the vault. * Available to system modules * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchIncrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external onlyModule { state.vaultInstance.batchIncrementTokenOwner( _tokens, _owner, _quantities ); } /** * Expose vault function that decrement user's balance in the vault * Only available to system modules. * * @param _tokens The addresses of the ERC20 tokens * @param _owner The address of the token owner * @param _quantities The numbers of tokens to attribute to owner */ function batchDecrementTokenOwnerModule( address[] calldata _tokens, address _owner, uint256[] calldata _quantities ) external onlyModule { state.vaultInstance.batchDecrementTokenOwner( _tokens, _owner, _quantities ); } /** * Expose vault function that transfer vault balances between users * Only available to system modules. * * @param _tokens Addresses of tokens being transferred * @param _from Address tokens being transferred from * @param _to Address tokens being transferred to * @param _quantities Amounts of tokens being transferred */ function batchTransferBalanceModule( address[] calldata _tokens, address _from, address _to, uint256[] calldata _quantities ) external onlyModule { state.vaultInstance.batchTransferBalance( _tokens, _from, _to, _quantities ); } /** * Transfers token from one address to another using the transfer proxy. * Only available to system modules. * * @param _token The address of the ERC20 token * @param _quantity The number of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function transferModule( address _token, uint256 _quantity, address _from, address _to ) external onlyModule { state.transferProxyInstance.transfer( _token, _quantity, _from, _to ); } /** * Expose transfer proxy function to transfer tokens from one address to another * Only available to system modules. * * @param _tokens The addresses of the ERC20 token * @param _quantities The numbers of tokens to transfer * @param _from The address to transfer from * @param _to The address to transfer to */ function batchTransferModule( address[] calldata _tokens, uint256[] calldata _quantities, address _from, address _to ) external onlyModule { state.transferProxyInstance.batchTransfer( _tokens, _quantities, _from, _to ); } } // File: contracts/core/Core.sol /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; /** * @title Core * @author Set Protocol * * The Core contract acts as a coordinator handling issuing, redeeming, and * creating Sets, as well as all collateral flows throughout the system. Core * is also responsible for tracking state and exposing methods to modules */ /* solium-disable-next-line no-empty-blocks */ contract Core is CoreAccounting, CoreAdmin, CoreFactory, CoreIssuance, CoreModuleInteraction { /** * Constructor function for Core * * @param _transferProxy The address of the transfer proxy * @param _vault The address of the vault */ constructor( address _transferProxy, address _vault ) public { // Commit passed address to transferProxyAddress state variable state.transferProxy = _transferProxy; // Instantiate instance of transferProxy state.transferProxyInstance = ITransferProxy(_transferProxy); // Commit passed address to vault state variable state.vault = _vault; // Instantiate instance of vault state.vaultInstance = IVault(_vault); } }
Exposes internal function that withdraws multiple tokens to the vault, exposed to system modules. Quantities should be in the order of the addresses of the tokens being withdrawn. _from Address to decredit for withdrawals _to Address to transfer tokens to _token Address of the token being withdrawn _quantity Amount of tokens to withdraw/
function withdrawModule( address _from, address _to, address _token, uint256 _quantity ) external onlyModule { address[] memory tokenArray = new address[](1); tokenArray[0] = _token; uint256[] memory quantityArray = new uint256[](1); quantityArray[0] = _quantity; batchWithdrawInternal( _from, _to, tokenArray, quantityArray ); }
15,826,002
./partial_match/42/0xdFf18ab57909a57e4660435B0935C09A1407d29A/sources/MasterchefDelegator.sol
deposit LP tokens to MasterChef for NTS allocation. ignore lockTime in stage one
function deposit( uint256 _pid, uint256 _amount, uint256 _lockTime ) public virtual { require(_amount > 0, "invalid deposit amount"); if (block.number < stageOneDepositEndBlock) { stageOne.deposit(_pid, msg.sender, _amount); emit Deposit(msg.sender, _pid, _amount, 0); return; } InvitationInfo storage senderInfo = usersRelationshipInfo[msg.sender]; require(senderInfo.isUsed, "must accept an invitation firstly"); PoolInfo storage pool = poolInfo[_pid]; uint256 lpTokenAmount = pool.lpTokenAmount.add(_amount); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 newOriginWeight = user.originWeight; uint256 existedAmount = user.amount; uint256 endBlock = user.endBlock; uint256 newEndBlock = block.number.add(produceBlocksPerMonth.mul(_lockTime)); if (existedAmount > 0) { if (block.number >= endBlock) { newOriginWeight = getDepositWeight( _amount.add(existedAmount), _lockTime ); newOriginWeight = newOriginWeight.add(getDepositWeight(_amount, _lockTime)); newOriginWeight = newOriginWeight.add( getDepositWeight( existedAmount, newEndBlock.sub(endBlock).div(produceBlocksPerMonth) ) ); } newOriginWeight = getDepositWeight(_amount, _lockTime); } modifyWeightByInvitation( _pid, msg.sender, user.originWeight, newOriginWeight, user.inviteeWeight, existedAmount ); updateUserInfo( user, existedAmount.add(_amount), newOriginWeight, newEndBlock ); IERC20(pool.lpTokenSwap).safeTransferFrom( address(msg.sender), address(this), _amount ); pool.oracleWeight = getOracleWeight(pool, lpTokenAmount); pool.lpTokenAmount = lpTokenAmount; if ( rankPoolIndexMap[_pid] == 0 && rankPoolIndex.length < maxRankNumber && blackListMap[_pid] == 0 ) { addToRank(pool, _pid, rankPoolIndex.length); } emit Deposit(msg.sender, _pid, _amount, newOriginWeight); }
3,296,304
//Address: 0x0293eAC1bbC24De88AFAf96048e4665154E84Ef0 //Contract name: PepFarmer //Balance: 0 Ether //Verification Date: 2/14/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; interface CornFarm { function buyObject(address _beneficiary) public payable; } interface Corn { function transfer(address to, uint256 value) public returns (bool); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract PepFarmer { using SafeMath for uint256; bool private reentrancy_lock = false; address public taxMan = 0xd5048F05Ed7185821C999e3e077A3d1baed0952c; // Kitchen Knife address public shopKnife = 0x225e5E680358FaE78216A9C0A17793c2d2A85fC2; address public objectKnife = 0x339Cd902D6F2e50717b114f0837280ce56f36020; // Doublet address public shopDoublet = 0xf9208661ffE1607D96cF386B84B2BE621620097C; address public objectDoublet = 0x56021b1b327eBE1eed2182A74d5f6a9a04eB2C73; // Gloves address public shopGloves = 0x28bdDb555AdF1Bb71ce21cAb60566956bbFB0f08; address public objectGloves = 0x67BE1A7555A7D38D837F6587530FFc33d89F5a90; // Helmet address public shopHelmet = 0xc8Ac76785C6b413753f6bFEdD9953785876B8a5c; address public objectHelmet = 0x7249fd2B946cAeD7D6C695e1656434A063723926; // Pants address public shopPants = 0x71e7a455991Cd9f60148720e2EB0Bc823014dB32; address public objectPants = 0xAc4A1553e1e80222D6BF9f66D8FeF629aa8dBE74; // Shoes address public shopShoes = 0xC946a2351eA574676f5e21043F05A33c2ceaBC59; address public objectShoes = 0x94b10291AA26f29994cF944da0Db6F03D4b407e1; // Sack address public shopSack = 0x0B2DA98ab93207CE1367d63947A20E24372D9Ab5; address public objectSack = 0x234FcB7f91fC353fefAd092b393850803A261cf9; // Tome address public shopTome = 0x0029b494669cfE56E8cDBCafF074940CC107a970; address public objectTome = 0xab87f28E10E3b0942EB27596Cc73B4031C9856e9; // Shield address public shopShield = 0xbD4282E6b2Bf8eef232eD211e53b54E560D71a2B; address public objectShield = 0xFc1082B4d80651d9948b58ffCce45A5e6586AFE6; address[9] public shop = [shopKnife, shopDoublet, shopHelmet, shopPants, shopShoes, shopSack, shopTome, shopShield]; address[9] public object = [objectKnife, objectDoublet, objectHelmet, objectPants, objectShoes, objectSack, objectTome, objectShield]; mapping(address => uint256) public workDone; modifier nonReentrant() { require(!reentrancy_lock); reentrancy_lock = true; _; reentrancy_lock = false; } function pepFarm() nonReentrant external { // buy 11 of each item for (uint8 i = 0; i < 9; i++) { for (uint8 j = 0; j < 11; j++) { CornFarm(shop[i]).buyObject(this); } // 10 for sender, 1 for taxMan workDone[msg.sender] = workDone[msg.sender].add(uint256(10 ether)); workDone[taxMan] = workDone[taxMan].add(uint256(1 ether)); } } function reapFarm() nonReentrant external { require(workDone[msg.sender] > 0); for (uint8 i = 0; i < 9; i++) { Corn(object[i]).transfer(msg.sender, workDone[msg.sender]); Corn(object[i]).transfer(taxMan, workDone[taxMan]); } workDone[msg.sender] = 0; workDone[taxMan] = 0; } }
buy 11 of each item
function pepFarm() nonReentrant external { for (uint8 i = 0; i < 9; i++) { for (uint8 j = 0; j < 11; j++) { CornFarm(shop[i]).buyObject(this); } workDone[taxMan] = workDone[taxMan].add(uint256(1 ether)); } }
1,817,969
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <=0.8.9; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.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/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract BridgeEth is Initializable, UUPSUpgradeable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using ECDSAUpgradeable for bytes32; bytes32 public constant MAPPER_ROLE = keccak256("MAPPER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); string public constant name = "ETH-EKTA Bridge"; mapping(address => address) public EthEktaPairs; //ETH Token => EKTA Token mapping(address => address) public EktaEthPairs; //EKTA Token => ETH Token mapping(address => mapping(uint => bool)) public processedNonces; address public admin; address public tokenToSwapWithNative; event AddedTokenPair(address indexed ethToken, address indexed ektaToken); event UpdatedTokenPair(address indexed ethToken, address indexed ektaToken); event TokenDeposited(address indexed ethToken, address indexed ektaToken, uint256 amount, address indexed user); event TokenWithdrawn(address indexed ethToken, address indexed ektaToken, uint256 amount, address indexed user); event DepositedTokenToNative(address indexed ethToken, uint256 amount, address indexed user); event WithdrawnNativeToToken(address indexed ethToken, uint256 amount, address indexed user); event TokenFromContractTransferred(address externalAddress,address toAddress, uint amount); event EthFromContractTransferred(address toAddress, uint amount); event AdminAddressUpdated(address admin); event TokenToSwapWithNativeUpdated(address token); /** * @dev Initializes the contract. * * Requirements: * - @param _owner cannot be the zero address. * - @param _tokenToSwapWithNative cannot be the zero address. */ function initialize(address _owner, address _tokenToSwapWithNative) public initializer { require(_owner != address(0), "Bridge: Address cant be zero address"); require(_tokenToSwapWithNative != address(0), "Bridge: Token address cant be zero address"); _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(MAPPER_ROLE, _owner); _setupRole(PAUSER_ROLE, _owner); admin = msg.sender; tokenToSwapWithNative = _tokenToSwapWithNative; // initializing __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); __Ownable_init_unchained(); } function _authorizeUpgrade(address) internal override onlyOwner {} /** * @dev Creates a pair for eth and ekta token by the caller with MAPPER_ROLE. * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {AddedTokenPair} event indicating the paired token addresses. */ function addTokenPairs(address _ethToken, address _ektaToken) external onlyRole(MAPPER_ROLE) nonReentrant whenNotPaused returns(bool) { require(EthEktaPairs[_ethToken] == address(0) && EktaEthPairs[_ektaToken] == address(0), "Bridge: Already mapped"); _mapToken(_ethToken, _ektaToken); emit AddedTokenPair(_ethToken, _ektaToken); return true; } /** * @dev Updates the ekta pair address for eth token by the caller with MAPPER_ROLE * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. * * @return A boolean value indicating whether the operation succeeded * * Emits a {UpdatedTokenPair} event indicating the paired token addresses */ function updateTokenPairs(address _ethToken, address _ektaToken) external onlyRole(MAPPER_ROLE) nonReentrant whenNotPaused returns(bool) { require(EthEktaPairs[_ethToken] != _ektaToken, "Bridge: Pair already exists"); require(EthEktaPairs[_ethToken] != address(0), "Bridge: Pair dont exists"); // clean token pairs to avoid re-mapping cleanTokenPairs(_ethToken); _mapToken(_ethToken, _ektaToken); emit UpdatedTokenPair(_ethToken, _ektaToken); return true; } /** * @dev Clears the eth and ekta pair address to avoid re-mapping by the caller with MAPPER_ROLE * * Requirements: * - @param _ethToken cant be zero address * * @return A boolean value indicating whether the operation succeeded */ function cleanTokenPairs(address _ethToken) public onlyRole(MAPPER_ROLE) whenNotPaused returns(bool) { require(_ethToken != address(0), "Bridge: Token address cant be zero address"); require(EthEktaPairs[_ethToken] != address(0), "Bridge: Pair dont exists"); address _ektaToken = EthEktaPairs[_ethToken]; EthEktaPairs[_ethToken] = address(0); EktaEthPairs[_ektaToken] = address(0); return true; } /** * @dev Internal function to map tokens * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. */ function _mapToken(address _ethToken, address _ektaToken) internal { require(_ethToken != address(0) && _ektaToken != address(0), "Bridge: Token address cant be zero address"); // update EthEktaPairs and EktaEthPairs mapping EthEktaPairs[_ethToken] = _ektaToken; EktaEthPairs[_ektaToken] = _ethToken; } /** * @dev Move token amount from caller to contract address. * * Requirements: * - @param _ethToken cannot be the zero address. * - @param amount should be greater than 0. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {TokenDeposited} event. */ function deposit(address _ethToken, uint256 amount) external nonReentrant whenNotPaused returns(bool) { require(_ethToken != address(0), "Bridge: Token cant be zero address"); require(EthEktaPairs[_ethToken] != address(0), "Bridge: Token not paired"); require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // transfer token to contract address IERC20Upgradeable(_ethToken).safeTransferFrom(msg.sender, address(this), amount); address ektaToken = EthEktaPairs[_ethToken]; emit TokenDeposited(_ethToken, ektaToken, amount, msg.sender); return true; } /** * @dev Move token amount from contract address to user * after successful verification of signature and nonce. * * Requirements: * - @param _ethToken cannot be the zero address. * - @param _ektaToken cannot be the zero address. * - @param user cannot be the zero address. * - @param amount should be greater than 0. * - @param nonce. * - @param signature. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {TokenWithdrawn} event. */ function withdraw(address _ethToken, address _ektaToken, address user, uint256 amount, uint256 nonce, bytes calldata signature) external nonReentrant whenNotPaused returns(bool) { require(_ethToken != address(0), "Bridge: Token cant be zero address"); require(_ektaToken != address(0), "Bridge: Token cant be zero address"); require(EthEktaPairs[_ethToken] == _ektaToken, "Bridge: Token pair does not exist"); require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // check for nonce require(!processedNonces[user][nonce], 'Bridge: Transfer already processed'); // verify signature require(_verify(abi.encodePacked(user, amount, nonce, "ETH_WITHDRAW", _ethToken, _ektaToken), signature), "Bridge: Invalid signature"); // transfer token from contract address to user IERC20Upgradeable(_ethToken).safeTransfer(user, amount); // update nonce processedNonces[user][nonce] = true; address ektaToken = EthEktaPairs[_ethToken]; emit TokenWithdrawn(_ethToken, ektaToken, amount, user); return true; } /** * @dev Move `tokenToSwapWithNative` token amount from caller to contract address * * Requirements: * - @param amount should be greater than 0. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {DepositedTokenToNative} event. */ function depositTokenToNative(uint256 amount) external nonReentrant whenNotPaused returns(bool) { require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // transfer token to contract address IERC20Upgradeable(tokenToSwapWithNative).safeTransferFrom(msg.sender, address(this), amount); emit DepositedTokenToNative(tokenToSwapWithNative, amount, msg.sender); return true; } /** * @dev Move `tokenToSwapWithNative` token amount from contract address to user * * Requirements: * - @param user cannot be the zero address. * - @param amount should be greater than 0. * - @param nonce. * - @param signature. * * @return A boolean value indicating whether the operation succeeded. * * Emits a {WithdrawnNativeToToken} event. */ function withdrawNativeToToken(address user, uint256 amount, uint256 nonce, bytes calldata signature) external nonReentrant whenNotPaused returns(bool) { require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); // check for nonce require(!processedNonces[user][nonce], 'Bridge: Transfer already processed'); // verify signature require(_verify(abi.encodePacked(user, amount, nonce, "ETH_NATIVE_WITHDRAW"), signature), "Bridge: Invalid signature"); // transfer token from contract address to user IERC20Upgradeable(tokenToSwapWithNative).safeTransfer(user, amount); // update nonce processedNonces[user][nonce] = true; emit WithdrawnNativeToToken(tokenToSwapWithNative, amount, user); return true; } /** * @dev Update the admin address used for signature verification * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param _admin cannot be the zero address. * * Emits a {AdminAddressUpdated} event indicating the updated admin address. */ function updateAdminAddress(address _admin) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_admin != address(0), "Bridge: Admin address cant be zero address"); admin = _admin; emit AdminAddressUpdated(admin); } /** * @dev Update the token address used for swapping with native * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param token cannot be the zero address. * * Emits a {TokenToSwapWithNativeUpdated} event indicating the updated token address. */ function updateTokenToSwapWithNative(address token) external onlyRole(DEFAULT_ADMIN_ROLE) { require(token != address(0), "Bridge: Token address cant be zero address"); tokenToSwapWithNative = token; emit TokenToSwapWithNativeUpdated(tokenToSwapWithNative); } /** * @dev Pause the contract (stopped state) * by caller with PAUSER_ROLE. * * Requirements: * - The contract must not be paused. * * Emits a {Paused} event. */ function pause() external onlyRole(PAUSER_ROLE) { _pause(); } /** * @dev Unpause the contract (normal state) * by caller with PAUSER_ROLE. * * Requirements: * - The contract must be paused. * * Emits a {Unpaused} event. */ function unpause() external onlyRole(PAUSER_ROLE){ _unpause(); } /** * @dev Recover the amount of particular token from the contract address * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param _tokenContract cannot be the zero address. * - @param amount should be greater than 0. * * Emits a {TokenFromContractTransferred} event indicating the token address and amount. */ function withdrawERC20Token(address _tokenContract, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_tokenContract != address(0), "Bridge: Address cant be zero address"); IERC20Upgradeable tokenContract = IERC20Upgradeable(_tokenContract); require(amount <= tokenContract.balanceOf(address(this)), "Bridge: Amount exceeds balance"); tokenContract.transfer(msg.sender, amount); emit TokenFromContractTransferred(_tokenContract, msg.sender, amount); } // to recieve ETH receive() external payable {} /** * @dev Recover ETH from the contract address * by caller with DEFAULT_ADMIN_ROLE. * * Requirements: * - @param user cannot be the zero address. * - @param amount cannot be greater than balance. * * Emits a {EthFromContractTransferred} event. */ function withdrawEthFromContract(address user, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { require(user != address(0), "Bridge: Address cant be zero address"); require(amount <= address(this).balance, "Bridge: Amount exceeds balance"); address payable _user = payable(user); (bool success, ) = _user.call{value: amount}(""); require(success, "Bridge: Transfer failed."); emit EthFromContractTransferred(user, amount); } /** * @dev Internal function to verify the signature. * * Requirements: * - @param data encoded bytes of signature params. * - @param signature. */ function _verify(bytes memory data, bytes calldata signature) view internal returns (bool) { return keccak256(data) .toEthSignedMessageHash() .recover(signature) == admin; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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 Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT 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 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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } 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(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{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 ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; }
Move token amount from caller to contract address. Requirements: - _ethToken cannot be the zero address. - amount should be greater than 0. return A boolean value indicating whether the operation succeeded. Emits a {TokenDeposited} event./ transfer token to contract address
function deposit(address _ethToken, uint256 amount) external nonReentrant whenNotPaused returns(bool) { require(_ethToken != address(0), "Bridge: Token cant be zero address"); require(EthEktaPairs[_ethToken] != address(0), "Bridge: Token not paired"); require(amount > 0, "Bridge: Amount cant be zero or negative numbers"); IERC20Upgradeable(_ethToken).safeTransferFrom(msg.sender, address(this), amount); address ektaToken = EthEktaPairs[_ethToken]; emit TokenDeposited(_ethToken, ektaToken, amount, msg.sender); return true; }
535,638
// SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IDetailedERC20} from "contracts/common/Imports.sol"; import {SafeERC20} from "contracts/libraries/Imports.sol"; import { Initializable, ERC20UpgradeSafe, ReentrancyGuardUpgradeSafe, PausableUpgradeSafe, AccessControlUpgradeSafe, Address as AddressUpgradeSafe, SafeMath as SafeMathUpgradeSafe, SignedSafeMath as SignedSafeMathUpgradeSafe } from "contracts/proxy/Imports.sol"; import {IAddressRegistryV2} from "contracts/registry/Imports.sol"; import { AggregatorV3Interface, IOracleAdapter } from "contracts/oracle/Imports.sol"; import {MetaPoolToken} from "contracts/mapt/MetaPoolToken.sol"; import { IReservePool, IWithdrawFeePool, ILockingPool, IPoolToken, ILiquidityPoolV2 } from "./Imports.sol"; /** * @notice Collect user deposits so they can be lent to the LP Account * @notice Depositors share pool liquidity * @notice Reserves are maintained to process withdrawals * @notice Reserve tokens cannot be lent to the LP Account * @notice If a user withdraws too early after their deposit, there's a fee * @notice Tokens borrowed from the pool are tracked with the `MetaPoolToken` */ contract PoolTokenV2 is ILiquidityPoolV2, IPoolToken, IReservePool, IWithdrawFeePool, ILockingPool, Initializable, AccessControlUpgradeSafe, ReentrancyGuardUpgradeSafe, PausableUpgradeSafe, ERC20UpgradeSafe { using AddressUpgradeSafe for address; using SafeMathUpgradeSafe for uint256; using SignedSafeMathUpgradeSafe for int256; using SafeERC20 for IDetailedERC20; uint256 public constant DEFAULT_APT_TO_UNDERLYER_FACTOR = 1000; uint256 internal constant _MAX_INT256 = 2**255 - 1; /* ------------------------------- */ /* impl-specific storage variables */ /* ------------------------------- */ // V1 /** @notice used to protect init functions for upgrades */ address public proxyAdmin; /** @notice true if depositing is locked */ bool public addLiquidityLock; /** @notice true if withdrawing is locked */ bool public redeemLock; /** @notice underlying stablecoin */ IDetailedERC20 public override underlyer; /** @notice USD price feed for the stablecoin */ // AggregatorV3Interface public priceAgg; <-- removed in V2 // V2 /** * @notice registry to fetch core platform addresses from * @dev this slot replaces the last V1 slot for the price agg */ IAddressRegistryV2 public addressRegistry; /** @notice seconds since last deposit during which withdrawal fee is charged */ uint256 public override feePeriod; /** @notice percentage charged for withdrawal fee */ uint256 public override feePercentage; /** @notice time of last deposit */ mapping(address => uint256) public lastDepositTime; /** @notice percentage of pool total value available for immediate withdrawal */ uint256 public override reservePercentage; /* ------------------------------- */ /** @notice Log when the proxy admin is changed */ event AdminChanged(address); /** @notice Log when the address registry is changed */ event AddressRegistryChanged(address); /** * @dev Throw if called by any account other than the proxy admin. */ modifier onlyAdmin() { require(msg.sender == proxyAdmin, "ADMIN_ONLY"); _; } /** * @dev Since the proxy delegate calls to this "logic" contract, any * storage set by the logic contract's constructor during deploy is * disregarded and this function is needed to initialize the proxy * contract's storage according to this contract's layout. * * Since storage is not set yet, there is no simple way to protect * calling this function with owner modifiers. Thus the OpenZeppelin * `initializer` modifier protects this function from being called * repeatedly. It should be called during the deployment so that * it cannot be called by someone else later. * * NOTE: this function is copied from the V1 contract and has already * been called during V1 deployment. It is included here for clarity. */ function initialize( address adminAddress, IDetailedERC20 underlyer_, AggregatorV3Interface priceAgg ) external initializer { require(adminAddress != address(0), "INVALID_ADMIN"); require(address(underlyer_) != address(0), "INVALID_TOKEN"); require(address(priceAgg) != address(0), "INVALID_AGG"); // initialize ancestor storage __Context_init_unchained(); // __Ownable_init_unchained(); <-- Comment-out for compiler; replaced by AccessControl __ReentrancyGuard_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("APY Pool Token", "APT"); // initialize impl-specific storage _setAdminAddress(adminAddress); addLiquidityLock = false; redeemLock = false; underlyer = underlyer_; // setPriceAggregator(priceAgg); <-- deprecated in V2. } /** * @dev Note the `initializer` modifier can only be used once in the * entire contract, so we can't use it here. Instead, we protect * this function with `onlyAdmin`, which allows only the `proxyAdmin` * address to call this function. Since that address is in fact * set to the actual proxy admin during deployment, this ensures * this function can only be called as part of a delegate call * during upgrades, i.e. in ProxyAdmin's `upgradeAndCall`. */ function initializeUpgrade(address addressRegistry_) external onlyAdmin { _setAddressRegistry(addressRegistry_); // Sadly, the AccessControl init is protected by `initializer` so can't // be called ever again (see above natspec). Fortunately, the init body // is empty, so we don't actually need to call it. // __AccessControl_init_unchained(); _setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress()); _setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress()); feePeriod = 1 days; feePercentage = 5; reservePercentage = 5; } function emergencyLock() external override onlyEmergencyRole { _pause(); } function emergencyUnlock() external override onlyEmergencyRole { _unpause(); } /** * @dev If no APT tokens have been minted yet, fallback to a fixed ratio. */ function addLiquidity(uint256 depositAmount) external override nonReentrant whenNotPaused { require(!addLiquidityLock, "LOCKED"); require(depositAmount > 0, "AMOUNT_INSUFFICIENT"); require( underlyer.allowance(msg.sender, address(this)) >= depositAmount, "ALLOWANCE_INSUFFICIENT" ); // solhint-disable-next-line not-rely-on-time lastDepositTime[msg.sender] = block.timestamp; // calculateMintAmount() is not used because deposit value // is needed for the event uint256 depositValue = getValueFromUnderlyerAmount(depositAmount); uint256 poolTotalValue = getPoolTotalValue(); uint256 mintAmount = _calculateMintAmount(depositValue, poolTotalValue); _mint(msg.sender, mintAmount); underlyer.safeTransferFrom(msg.sender, address(this), depositAmount); emit DepositedAPT( msg.sender, underlyer, depositAmount, mintAmount, depositValue, getPoolTotalValue() ); } function emergencyLockAddLiquidity() external override onlyEmergencyRole { addLiquidityLock = true; emit AddLiquidityLocked(); } function emergencyUnlockAddLiquidity() external override onlyEmergencyRole { addLiquidityLock = false; emit AddLiquidityUnlocked(); } /** * @dev May revert if there is not enough in the pool. */ function redeem(uint256 aptAmount) external override nonReentrant whenNotPaused { require(!redeemLock, "LOCKED"); require(aptAmount > 0, "AMOUNT_INSUFFICIENT"); require(aptAmount <= balanceOf(msg.sender), "BALANCE_INSUFFICIENT"); uint256 redeemUnderlyerAmt = getUnderlyerAmountWithFee(aptAmount); require( redeemUnderlyerAmt <= underlyer.balanceOf(address(this)), "RESERVE_INSUFFICIENT" ); _burn(msg.sender, aptAmount); underlyer.safeTransfer(msg.sender, redeemUnderlyerAmt); emit RedeemedAPT( msg.sender, underlyer, redeemUnderlyerAmt, aptAmount, getValueFromUnderlyerAmount(redeemUnderlyerAmt), getPoolTotalValue() ); } function emergencyLockRedeem() external override onlyEmergencyRole { redeemLock = true; emit RedeemLocked(); } function emergencyUnlockRedeem() external override onlyEmergencyRole { redeemLock = false; emit RedeemUnlocked(); } /** * @dev permissioned with CONTRACT_ROLE */ function transferToLpAccount(uint256 amount) external override nonReentrant whenNotPaused onlyContractRole { underlyer.safeTransfer(addressRegistry.lpAccountAddress(), amount); } /** * @notice Set the new proxy admin * @param adminAddress The new proxy admin */ function emergencySetAdminAddress(address adminAddress) external onlyEmergencyRole { _setAdminAddress(adminAddress); } /** * @notice Set the new address registry * @param addressRegistry_ The new address registry */ function emergencySetAddressRegistry(address addressRegistry_) external onlyEmergencyRole { _setAddressRegistry(addressRegistry_); } function setFeePeriod(uint256 feePeriod_) external override onlyAdminRole { feePeriod = feePeriod_; emit FeePeriodChanged(feePeriod_); } function setFeePercentage(uint256 feePercentage_) external override onlyAdminRole { feePercentage = feePercentage_; emit FeePercentageChanged(feePercentage_); } function setReservePercentage(uint256 reservePercentage_) external override onlyAdminRole { reservePercentage = reservePercentage_; emit ReservePercentageChanged(reservePercentage_); } function calculateMintAmount(uint256 depositAmount) external view override returns (uint256) { uint256 depositValue = getValueFromUnderlyerAmount(depositAmount); uint256 poolTotalValue = getPoolTotalValue(); return _calculateMintAmount(depositValue, poolTotalValue); } /** * @dev To check if fee will be applied, use `isEarlyRedeem`. */ function getUnderlyerAmountWithFee(uint256 aptAmount) public view override returns (uint256) { uint256 redeemUnderlyerAmt = getUnderlyerAmount(aptAmount); if (isEarlyRedeem()) { uint256 fee = redeemUnderlyerAmt.mul(feePercentage).div(100); redeemUnderlyerAmt = redeemUnderlyerAmt.sub(fee); } return redeemUnderlyerAmt; } function getUnderlyerAmount(uint256 aptAmount) public view override returns (uint256) { if (aptAmount == 0) { return 0; } require(totalSupply() > 0, "INSUFFICIENT_TOTAL_SUPPLY"); // the below is mathematically equivalent to: // // getUnderlyerAmountFromValue(getAPTValue(aptAmount)); // // but composing the two functions leads to early loss // of precision from division, so it's better to do it // this way: uint256 underlyerPrice = getUnderlyerPrice(); uint256 decimals = underlyer.decimals(); return aptAmount .mul(getPoolTotalValue()) .mul(10**decimals) .div(totalSupply()) .div(underlyerPrice); } /** * @dev `lastDepositTime` is stored each time user makes a deposit, so * the waiting period is restarted on each deposit. */ function isEarlyRedeem() public view override returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp.sub(lastDepositTime[msg.sender]) < feePeriod; } /** * @dev Total value also includes that have been borrowed from the pool * @dev Typically it is the LP Account that borrows from the pool */ function getPoolTotalValue() public view override returns (uint256) { uint256 underlyerValue = _getPoolUnderlyerValue(); uint256 mAptValue = _getDeployedValue(); return underlyerValue.add(mAptValue); } function getAPTValue(uint256 aptAmount) external view override returns (uint256) { require(totalSupply() > 0, "INSUFFICIENT_TOTAL_SUPPLY"); return aptAmount.mul(getPoolTotalValue()).div(totalSupply()); } function getValueFromUnderlyerAmount(uint256 underlyerAmount) public view override returns (uint256) { if (underlyerAmount == 0) { return 0; } uint256 decimals = underlyer.decimals(); return getUnderlyerPrice().mul(underlyerAmount).div(10**decimals); } function getUnderlyerPrice() public view override returns (uint256) { IOracleAdapter oracleAdapter = IOracleAdapter(addressRegistry.oracleAdapterAddress()); return oracleAdapter.getAssetPrice(address(underlyer)); } /** * @dev This "top-up" value should satisfy: * * top-up USD value + pool underlyer USD value * = (reserve %) * pool deployed value (after unwinding) * * @dev Taking the percentage of the pool's current deployed value * is not sufficient, because the requirement is to have the * resulting values after unwinding capital satisfy the * above equation. * * More precisely: * * R_pre = pool underlyer USD value before pushing unwound * capital to the pool * R_post = pool underlyer USD value after pushing * DV_pre = pool's deployed USD value before unwinding * DV_post = pool's deployed USD value after unwinding * rPerc = the reserve percentage as a whole number * out of 100 * * We want: * * R_post = (rPerc / 100) * DV_post (equation 1) * * where R_post = R_pre + top-up value * DV_post = DV_pre - top-up value * * Making the latter substitutions in equation 1, gives: * * top-up value = (rPerc * DV_pre - 100 * R_pre) / (100 + rPerc) */ function getReserveTopUpValue() external view override returns (int256) { uint256 unnormalizedTargetValue = _getDeployedValue().mul(reservePercentage); uint256 unnormalizedUnderlyerValue = _getPoolUnderlyerValue().mul(100); require(unnormalizedTargetValue <= _MAX_INT256, "SIGNED_INT_OVERFLOW"); require( unnormalizedUnderlyerValue <= _MAX_INT256, "SIGNED_INT_OVERFLOW" ); int256 topUpValue = int256(unnormalizedTargetValue) .sub(int256(unnormalizedUnderlyerValue)) .div(int256(reservePercentage).add(100)); return topUpValue; } function _setAdminAddress(address adminAddress) internal { require(adminAddress != address(0), "INVALID_ADMIN"); proxyAdmin = adminAddress; emit AdminChanged(adminAddress); } function _setAddressRegistry(address addressRegistry_) internal { require(addressRegistry_.isContract(), "INVALID_ADDRESS"); addressRegistry = IAddressRegistryV2(addressRegistry_); emit AddressRegistryChanged(addressRegistry_); } /** * @dev This hook is in-place to block inter-user APT transfers, as it * is one avenue that can be used by arbitrageurs to drain the * reserves. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); // allow minting and burning if (from == address(0) || to == address(0)) return; // block transfer between users revert("INVALID_TRANSFER"); } /** * @dev amount of APT minted should be in same ratio to APT supply * as deposit value is to pool's total value, i.e.: * * mint amount / total supply * = deposit value / pool total value * * For denominators, pre or post-deposit amounts can be used. * The important thing is they are consistent, i.e. both pre-deposit * or both post-deposit. */ function _calculateMintAmount(uint256 depositValue, uint256 poolTotalValue) internal view returns (uint256) { uint256 totalSupply = totalSupply(); if (poolTotalValue == 0 || totalSupply == 0) { return depositValue.mul(DEFAULT_APT_TO_UNDERLYER_FACTOR); } return (depositValue.mul(totalSupply)).div(poolTotalValue); } /** * @notice Get the USD value of tokens in the pool * @return The USD value */ function _getPoolUnderlyerValue() internal view returns (uint256) { return getValueFromUnderlyerAmount(underlyer.balanceOf(address(this))); } /** * @notice Get the USD value of tokens owed to the pool * @dev Tokens from the pool are typically borrowed by the LP Account * @dev Tokens borrowed from the pool are tracked with mAPT * @return The USD value */ function _getDeployedValue() internal view returns (uint256) { MetaPoolToken mApt = MetaPoolToken(addressRegistry.mAptAddress()); return mApt.getDeployedValue(address(this)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IDetailedERC20} from "./IDetailedERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {AccessControl} from "./AccessControl.sol"; import {INameIdentifier} from "./INameIdentifier.sol"; import {IAssetAllocation} from "./IAssetAllocation.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {NamedAddressSet} from "./NamedAddressSet.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import { Initializable } from "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import { OwnableUpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import { ERC20UpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import { ReentrancyGuardUpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import { PausableUpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import {AccessControlUpgradeSafe} from "./AccessControlUpgradeSafe.sol"; import {ProxyAdmin} from "@openzeppelin/contracts/proxy/ProxyAdmin.sol"; import { TransparentUpgradeableProxy } from "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; /* Aliases don't persist so we can't rename them here, but you should * rename them at point of import with the "UpgradeSafe" prefix, e.g. * import {Address as AddressUpgradeSafe} etc. */ import { Address } from "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import { SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IAddressRegistryV2} from "./IAddressRegistryV2.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {AggregatorV3Interface, FluxAggregator} from "./FluxAggregator.sol"; import {IOracleAdapter} from "./IOracleAdapter.sol"; import {IOverrideOracle} from "./IOverrideOracle.sol"; import {ILockingOracle} from "./ILockingOracle.sol"; // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IDetailedERC20} from "contracts/common/Imports.sol"; import {SafeERC20} from "contracts/libraries/Imports.sol"; import { Initializable, ERC20UpgradeSafe, ReentrancyGuardUpgradeSafe, PausableUpgradeSafe, AccessControlUpgradeSafe, Address as AddressUpgradeSafe, SafeMath as SafeMathUpgradeSafe, SignedSafeMath as SignedSafeMathUpgradeSafe } from "contracts/proxy/Imports.sol"; import {ILpAccount} from "contracts/lpaccount/Imports.sol"; import {IAddressRegistryV2} from "contracts/registry/Imports.sol"; import {ILockingOracle} from "contracts/oracle/Imports.sol"; import {IReservePool} from "contracts/pool/Imports.sol"; import { IErc20Allocation, IAssetAllocationRegistry, Erc20AllocationConstants } from "contracts/tvl/Imports.sol"; import {ILpAccountFunder} from "./ILpAccountFunder.sol"; /** * @notice This contract has hybrid functionality: * * - It acts as a token that tracks the capital that has been pulled * ("deployed") from APY Finance pools (PoolToken contracts) * * - It is permissioned to transfer funds between the pools and the * LP Account contract. * * @dev When MetaPoolToken pulls capital from the pools to the LP Account, it * will mint mAPT for each pool. Conversely, when MetaPoolToken withdraws funds * from the LP Account to the pools, it will burn mAPT for each pool. * * The ratio of each pool's mAPT balance to the total mAPT supply determines * the amount of the TVL dedicated to the pool. * * * DEPLOY CAPITAL TO YIELD FARMING STRATEGIES * Mints appropriate mAPT amount to track share of deployed TVL owned by a pool. * * +-------------+ MetaPoolToken.fundLpAccount +-----------+ * | |------------------------------>| | * | PoolTokenV2 | MetaPoolToken.mint | LpAccount | * | |<------------------------------| | * +-------------+ +-----------+ * * * WITHDRAW CAPITAL FROM YIELD FARMING STRATEGIES * Uses mAPT to calculate the amount of capital returned to the PoolToken. * * +-------------+ MetaPoolToken.withdrawFromLpAccount +-----------+ * | |<--------------------------------------| | * | PoolTokenV2 | MetaPoolToken.burn | LpAccount | * | |-------------------------------------->| | * +-------------+ +-----------+ */ contract MetaPoolToken is Initializable, AccessControlUpgradeSafe, ReentrancyGuardUpgradeSafe, PausableUpgradeSafe, ERC20UpgradeSafe, ILpAccountFunder, Erc20AllocationConstants { using AddressUpgradeSafe for address; using SafeMathUpgradeSafe for uint256; using SignedSafeMathUpgradeSafe for int256; using SafeERC20 for IDetailedERC20; uint256 public constant DEFAULT_MAPT_TO_UNDERLYER_FACTOR = 1000; /* ------------------------------- */ /* impl-specific storage variables */ /* ------------------------------- */ /** @notice used to protect init functions for upgrades */ address public proxyAdmin; /** @notice used to protect mint and burn function */ IAddressRegistryV2 public addressRegistry; /* ------------------------------- */ event Mint(address acccount, uint256 amount); event Burn(address acccount, uint256 amount); event AdminChanged(address); event AddressRegistryChanged(address); /** * @dev Throws if called by any account other than the proxy admin. */ modifier onlyAdmin() { require(msg.sender == proxyAdmin, "ADMIN_ONLY"); _; } /** * @dev Since the proxy delegate calls to this "logic" contract, any * storage set by the logic contract's constructor during deploy is * disregarded and this function is needed to initialize the proxy * contract's storage according to this contract's layout. * * Since storage is not set yet, there is no simple way to protect * calling this function with owner modifiers. Thus the OpenZeppelin * `initializer` modifier protects this function from being called * repeatedly. It should be called during the deployment so that * it cannot be called by someone else later. */ function initialize(address adminAddress, address addressRegistry_) external initializer { require(adminAddress != address(0), "INVALID_ADMIN"); // initialize ancestor storage __Context_init_unchained(); __AccessControl_init_unchained(); __ReentrancyGuard_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("APY MetaPool Token", "mAPT"); // initialize impl-specific storage _setAdminAddress(adminAddress); _setAddressRegistry(addressRegistry_); _setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(LP_ROLE, addressRegistry.lpSafeAddress()); _setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress()); } /** * @dev Dummy function to show how one would implement an init function * for future upgrades. Note the `initializer` modifier can only be used * once in the entire contract, so we can't use it here. Instead, * we set the proxy admin address as a variable and protect this * function with `onlyAdmin`, which only allows the proxy admin * to call this function during upgrades. */ // solhint-disable-next-line no-empty-blocks function initializeUpgrade() external virtual onlyAdmin {} /** * @notice Set the new proxy admin * @param adminAddress The new proxy admin */ function emergencySetAdminAddress(address adminAddress) external onlyEmergencyRole { _setAdminAddress(adminAddress); } /** * @notice Sets the address registry * @param addressRegistry_ the address of the registry */ function emergencySetAddressRegistry(address addressRegistry_) external onlyEmergencyRole { _setAddressRegistry(addressRegistry_); } function fundLpAccount(bytes32[] calldata poolIds) external override nonReentrant onlyLpRole { (IReservePool[] memory pools, int256[] memory amounts) = getRebalanceAmounts(poolIds); uint256[] memory fundAmounts = _getFundAmounts(amounts); _fundLpAccount(pools, fundAmounts); emit FundLpAccount(poolIds, fundAmounts); } function emergencyFundLpAccount( IReservePool[] calldata pools, uint256[] calldata amounts ) external override nonReentrant onlyEmergencyRole { _fundLpAccount(pools, amounts); emit EmergencyFundLpAccount(pools, amounts); } function withdrawFromLpAccount(bytes32[] calldata poolIds) external override nonReentrant onlyLpRole { (IReservePool[] memory pools, int256[] memory amounts) = getRebalanceAmounts(poolIds); uint256[] memory withdrawAmounts = _getWithdrawAmounts(amounts); _withdrawFromLpAccount(pools, withdrawAmounts); emit WithdrawFromLpAccount(poolIds, withdrawAmounts); } function emergencyWithdrawFromLpAccount( IReservePool[] calldata pools, uint256[] calldata amounts ) external override nonReentrant onlyEmergencyRole { _withdrawFromLpAccount(pools, amounts); emit EmergencyWithdrawFromLpAccount(pools, amounts); } /** * @notice Get the USD-denominated value (in wei) of the pool's share * of the deployed capital, as tracked by the mAPT token. * @return The value deployed to the LP Account */ function getDeployedValue(address pool) external view returns (uint256) { uint256 balance = balanceOf(pool); uint256 totalSupply = totalSupply(); if (totalSupply == 0 || balance == 0) return 0; return _getTvl().mul(balance).div(totalSupply); } /** * @notice Returns the (signed) top-up amount for each pool ID given. * A positive (negative) sign means the reserve level is in deficit * (excess) of required percentage. * @param poolIds array of pool identifiers * @return The array of pools * @return An array of rebalance amounts */ function getRebalanceAmounts(bytes32[] memory poolIds) public view returns (IReservePool[] memory, int256[] memory) { IReservePool[] memory pools = new IReservePool[](poolIds.length); int256[] memory rebalanceAmounts = new int256[](poolIds.length); for (uint256 i = 0; i < poolIds.length; i++) { IReservePool pool = IReservePool(addressRegistry.getAddress(poolIds[i])); int256 rebalanceAmount = pool.getReserveTopUpValue(); pools[i] = pool; rebalanceAmounts[i] = rebalanceAmount; } return (pools, rebalanceAmounts); } function _setAdminAddress(address adminAddress) internal { require(adminAddress != address(0), "INVALID_ADMIN"); proxyAdmin = adminAddress; emit AdminChanged(adminAddress); } function _setAddressRegistry(address addressRegistry_) internal { require(addressRegistry_.isContract(), "INVALID_ADDRESS"); addressRegistry = IAddressRegistryV2(addressRegistry_); emit AddressRegistryChanged(addressRegistry_); } function _fundLpAccount( IReservePool[] memory pools, uint256[] memory amounts ) internal { address lpAccountAddress = addressRegistry.lpAccountAddress(); require(lpAccountAddress != address(0), "INVALID_LP_ACCOUNT"); // defensive check -- should never happen _multipleMintAndTransfer(pools, amounts); _registerPoolUnderlyers(pools); } function _multipleMintAndTransfer( IReservePool[] memory pools, uint256[] memory amounts ) internal { uint256[] memory deltas = _calculateDeltas(pools, amounts); // MUST do the actual minting after calculating *all* mint amounts, // otherwise due to Chainlink not updating during a transaction, // the totalSupply will change while TVL doesn't. // // Using the pre-mint TVL and totalSupply gives the same answer // as using post-mint values. for (uint256 i = 0; i < pools.length; i++) { IReservePool pool = pools[i]; uint256 mintAmount = deltas[i]; uint256 transferAmount = amounts[i]; _mintAndTransfer(pool, mintAmount, transferAmount); } ILockingOracle oracleAdapter = _getOracleAdapter(); oracleAdapter.lock(); } function _mintAndTransfer( IReservePool pool, uint256 mintAmount, uint256 transferAmount ) internal { if (mintAmount == 0) { return; } _mint(address(pool), mintAmount); pool.transferToLpAccount(transferAmount); emit Mint(address(pool), mintAmount); } function _withdrawFromLpAccount( IReservePool[] memory pools, uint256[] memory amounts ) internal { address lpAccountAddress = addressRegistry.lpAccountAddress(); require(lpAccountAddress != address(0), "INVALID_LP_ACCOUNT"); // defensive check -- should never happen _multipleBurnAndTransfer(pools, amounts); _registerPoolUnderlyers(pools); } function _multipleBurnAndTransfer( IReservePool[] memory pools, uint256[] memory amounts ) internal { address lpAccount = addressRegistry.lpAccountAddress(); require(lpAccount != address(0), "INVALID_LP_ACCOUNT"); // defensive check -- should never happen uint256[] memory deltas = _calculateDeltas(pools, amounts); // MUST do the actual burning after calculating *all* burn amounts, // otherwise due to Chainlink not updating during a transaction, // the totalSupply will change while TVL doesn't. // // Using the pre-burn TVL and totalSupply gives the same answer // as using post-burn values. for (uint256 i = 0; i < pools.length; i++) { IReservePool pool = pools[i]; uint256 burnAmount = deltas[i]; uint256 transferAmount = amounts[i]; _burnAndTransfer(pool, lpAccount, burnAmount, transferAmount); } ILockingOracle oracleAdapter = _getOracleAdapter(); oracleAdapter.lock(); } function _burnAndTransfer( IReservePool pool, address lpAccount, uint256 burnAmount, uint256 transferAmount ) internal { if (burnAmount == 0) { return; } _burn(address(pool), burnAmount); ILpAccount(lpAccount).transferToPool(address(pool), transferAmount); emit Burn(address(pool), burnAmount); } /** * @notice Register an asset allocation for the account with each pool underlyer * @param pools list of pool amounts whose pool underlyers will be registered */ function _registerPoolUnderlyers(IReservePool[] memory pools) internal { IAssetAllocationRegistry tvlManager = IAssetAllocationRegistry(addressRegistry.getAddress("tvlManager")); IErc20Allocation erc20Allocation = IErc20Allocation( address( tvlManager.getAssetAllocation(Erc20AllocationConstants.NAME) ) ); for (uint256 i = 0; i < pools.length; i++) { IDetailedERC20 underlyer = IDetailedERC20(address(pools[i].underlyer())); if (!erc20Allocation.isErc20TokenRegistered(underlyer)) { erc20Allocation.registerErc20Token(underlyer); } } } /** * @notice Get the USD value of all assets in the system, not just those * being managed by the AccountManager but also the pool underlyers. * * Note this is NOT the same as the total value represented by the * total mAPT supply, i.e. the "deployed capital". * * @dev Chainlink nodes read from the TVLManager, pull the * prices from market feeds, and submits the calculated total value * to an aggregator contract. * * USD prices have 8 decimals. * * @return "Total Value Locked", the USD value of all APY Finance assets. */ function _getTvl() internal view returns (uint256) { ILockingOracle oracleAdapter = _getOracleAdapter(); return oracleAdapter.getTvl(); } function _getOracleAdapter() internal view returns (ILockingOracle) { address oracleAdapterAddress = addressRegistry.oracleAdapterAddress(); return ILockingOracle(oracleAdapterAddress); } function _calculateDeltas( IReservePool[] memory pools, uint256[] memory amounts ) internal view returns (uint256[] memory) { require(pools.length == amounts.length, "LENGTHS_MUST_MATCH"); uint256[] memory deltas = new uint256[](pools.length); for (uint256 i = 0; i < pools.length; i++) { IReservePool pool = pools[i]; uint256 amount = amounts[i]; IDetailedERC20 underlyer = pool.underlyer(); uint256 tokenPrice = pool.getUnderlyerPrice(); uint8 decimals = underlyer.decimals(); deltas[i] = _calculateDelta(amount, tokenPrice, decimals); } return deltas; } /** * @notice Calculate mAPT amount for given pool's underlyer amount. * @param amount Pool underlyer amount to be converted * @param tokenPrice Pool underlyer's USD price (in wei) per underlyer token * @param decimals Pool underlyer's number of decimals * @dev Price parameter is in units of wei per token ("big" unit), since * attempting to express wei per token bit ("small" unit) will be * fractional, requiring fixed-point representation. This means we need * to also pass in the underlyer's number of decimals to do the appropriate * multiplication in the calculation. * @dev amount of APT minted should be in same ratio to APT supply * as deposit value is to pool's total value, i.e.: * * mint amount / total supply * = deposit value / pool total value * * For denominators, pre or post-deposit amounts can be used. * The important thing is they are consistent, i.e. both pre-deposit * or both post-deposit. */ function _calculateDelta( uint256 amount, uint256 tokenPrice, uint8 decimals ) internal view returns (uint256) { uint256 value = amount.mul(tokenPrice).div(10**uint256(decimals)); uint256 totalValue = _getTvl(); uint256 totalSupply = totalSupply(); if (totalValue == 0 || totalSupply == 0) { return value.mul(DEFAULT_MAPT_TO_UNDERLYER_FACTOR); } return value.mul(totalSupply).div(totalValue); } function _getFundAmounts(int256[] memory amounts) internal pure returns (uint256[] memory) { uint256[] memory fundAmounts = new uint256[](amounts.length); for (uint256 i = 0; i < amounts.length; i++) { int256 amount = amounts[i]; fundAmounts[i] = amount < 0 ? uint256(-amount) : 0; } return fundAmounts; } function _getWithdrawAmounts(int256[] memory amounts) internal pure returns (uint256[] memory) { uint256[] memory withdrawAmounts = new uint256[](amounts.length); for (uint256 i = 0; i < amounts.length; i++) { int256 amount = amounts[i]; withdrawAmounts[i] = amount > 0 ? uint256(amount) : 0; } return withdrawAmounts; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IReservePool} from "./IReservePool.sol"; import {IWithdrawFeePool} from "./IWithdrawFeePool.sol"; import {ILockingPool} from "./ILockingPool.sol"; import {IPoolToken} from "./IPoolToken.sol"; import {ILiquidityPoolV2} from "./ILiquidityPoolV2.sol"; // 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; 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: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: 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.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: BUSL-1.1 pragma solidity 0.6.11; import { AccessControl as OZAccessControl } from "@openzeppelin/contracts/access/AccessControl.sol"; /** * @notice Extends OpenZeppelin AccessControl contract with modifiers * @dev This contract and AccessControlUpgradeSafe are essentially duplicates. */ contract AccessControl is OZAccessControl { /** @notice access control roles **/ bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE"); bytes32 public constant LP_ROLE = keccak256("LP_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE"); modifier onlyLpRole() { require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE"); _; } modifier onlyContractRole() { require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE"); _; } modifier onlyAdminRole() { require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE"); _; } modifier onlyEmergencyRole() { require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE"); _; } modifier onlyLpOrContractRole() { require( hasRole(LP_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_LP_OR_CONTRACT_ROLE" ); _; } modifier onlyAdminOrContractRole() { require( hasRole(ADMIN_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_ADMIN_OR_CONTRACT_ROLE" ); _; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Used by the `NamedAddressSet` library to store sets of contracts */ interface INameIdentifier { /// @notice Should be implemented as a constant value // solhint-disable-next-line func-name-mixedcase function NAME() external view returns (string memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {INameIdentifier} from "./INameIdentifier.sol"; /** * @notice For use with the `TvlManager` to track the value locked in a protocol */ interface IAssetAllocation is INameIdentifier { struct TokenData { address token; string symbol; uint8 decimals; } /** * @notice Get data for the underlying tokens stored in the protocol * @return The array of `TokenData` */ function tokens() external view returns (TokenData[] memory); /** * @notice Get the number of different tokens stored in the protocol * @return The number of tokens */ function numberOfTokens() external view returns (uint256); /** * @notice Get an account's balance for a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param account The account to get the balance for * @param tokenIndex The index of the token to get the balance for * @return The account's balance */ function balanceOf(address account, uint8 tokenIndex) external view returns (uint256); /** * @notice Get the symbol of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The symbol of the token */ function symbolOf(uint8 tokenIndex) external view returns (string memory); /** * @notice Get the decimals of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The decimals of the token */ function decimalsOf(uint8 tokenIndex) external view returns (uint8); } // 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.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; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, 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()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IAssetAllocation, INameIdentifier} from "contracts/common/Imports.sol"; import {IZap, ISwap} from "contracts/lpaccount/Imports.sol"; /** * @notice Stores a set of addresses that can be looked up by name * @notice Addresses can be added or removed dynamically * @notice Useful for keeping track of unique deployed contracts * @dev Each address must be a contract with a `NAME` constant for lookup */ library NamedAddressSet { using EnumerableSet for EnumerableSet.AddressSet; struct Set { EnumerableSet.AddressSet _namedAddresses; mapping(string => INameIdentifier) _nameLookup; } struct AssetAllocationSet { Set _inner; } struct ZapSet { Set _inner; } struct SwapSet { Set _inner; } function _add(Set storage set, INameIdentifier namedAddress) private { require(Address.isContract(address(namedAddress)), "INVALID_ADDRESS"); require( !set._namedAddresses.contains(address(namedAddress)), "DUPLICATE_ADDRESS" ); string memory name = namedAddress.NAME(); require(bytes(name).length != 0, "INVALID_NAME"); require(address(set._nameLookup[name]) == address(0), "DUPLICATE_NAME"); set._namedAddresses.add(address(namedAddress)); set._nameLookup[name] = namedAddress; } function _remove(Set storage set, string memory name) private { address namedAddress = address(set._nameLookup[name]); require(namedAddress != address(0), "INVALID_NAME"); set._namedAddresses.remove(namedAddress); delete set._nameLookup[name]; } function _contains(Set storage set, INameIdentifier namedAddress) private view returns (bool) { return set._namedAddresses.contains(address(namedAddress)); } function _length(Set storage set) private view returns (uint256) { return set._namedAddresses.length(); } function _at(Set storage set, uint256 index) private view returns (INameIdentifier) { return INameIdentifier(set._namedAddresses.at(index)); } function _get(Set storage set, string memory name) private view returns (INameIdentifier) { return set._nameLookup[name]; } function _names(Set storage set) private view returns (string[] memory) { uint256 length_ = set._namedAddresses.length(); string[] memory names_ = new string[](length_); for (uint256 i = 0; i < length_; i++) { INameIdentifier namedAddress = INameIdentifier(set._namedAddresses.at(i)); names_[i] = namedAddress.NAME(); } return names_; } function add( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal { _add(set._inner, assetAllocation); } function remove(AssetAllocationSet storage set, string memory name) internal { _remove(set._inner, name); } function contains( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal view returns (bool) { return _contains(set._inner, assetAllocation); } function length(AssetAllocationSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AssetAllocationSet storage set, uint256 index) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_at(set._inner, index))); } function get(AssetAllocationSet storage set, string memory name) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_get(set._inner, name))); } function names(AssetAllocationSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(ZapSet storage set, IZap zap) internal { _add(set._inner, zap); } function remove(ZapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(ZapSet storage set, IZap zap) internal view returns (bool) { return _contains(set._inner, zap); } function length(ZapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(ZapSet storage set, uint256 index) internal view returns (IZap) { return IZap(address(_at(set._inner, index))); } function get(ZapSet storage set, string memory name) internal view returns (IZap) { return IZap(address(_get(set._inner, name))); } function names(ZapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(SwapSet storage set, ISwap swap) internal { _add(set._inner, swap); } function remove(SwapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(SwapSet storage set, ISwap swap) internal view returns (bool) { return _contains(set._inner, swap); } function length(SwapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(SwapSet storage set, uint256 index) internal view returns (ISwap) { return ISwap(address(_at(set._inner, index))); } function get(SwapSet storage set, string memory name) internal view returns (ISwap) { return ISwap(address(_get(set._inner, name))); } function names(SwapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IZap} from "./IZap.sol"; import {ISwap} from "./ISwap.sol"; import {ILpAccount} from "./ILpAccount.sol"; import {IZapRegistry} from "./IZapRegistry.sol"; import {ISwapRegistry} from "./ISwapRegistry.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define how an LP Account farms an external protocol */ interface IZap is INameIdentifier { /** * @notice Deploy liquidity to a protocol (i.e. enter a farm) * @dev Implementation should add liquidity and stake LP tokens * @param amounts Amount of each token to deploy */ function deployLiquidity(uint256[] calldata amounts) external; /** * @notice Unwind liquidity from a protocol (i.e exit a farm) * @dev Implementation should unstake LP tokens and remove liquidity * @dev If there is only one token to unwind, `index` should be 0 * @param amount Amount of liquidity to unwind * @param index Which token should be unwound */ function unwindLiquidity(uint256 amount, uint8 index) external; /** * @notice Claim accrued rewards from the protocol (i.e. harvest yield) */ function claim() external; /** * @notice Order of tokens for deploy `amounts` and unwind `index` * @dev Implementation should use human readable symbols * @dev Order should be the same for deploy and unwind * @return The array of symbols in order */ function sortedSymbols() external view returns (string[] memory); /** * @notice Asset allocations to include in TVL * @dev Requires all allocations that track value deployed to the protocol * @return An array of the asset allocation names */ function assetAllocations() external view returns (string[] memory); /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens that get deployed or unwound * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define a token swap that can be performed by an LP Account */ interface ISwap is INameIdentifier { /** * @dev Implementation should perform a token swap * @param amount The amount of the input token to swap * @param minAmount The minimum amount of the output token to accept */ function swap(uint256 amount, uint256 minAmount) external; /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens going in and out of the swap * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice For contracts that provide liquidity to external protocols */ interface ILpAccount { /** * @notice Deploy liquidity with a registered `IZap` * @dev The order of token amounts should match `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amounts The token amounts to deploy */ function deployStrategy(string calldata name, uint256[] calldata amounts) external; /** * @notice Unwind liquidity with a registered `IZap` * @dev The index should match the order of `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amount The amount of the token to unwind * @param index The index of the token to unwind */ function unwindStrategy( string calldata name, uint256 amount, uint8 index ) external; /** * @notice Return liquidity to a pool * @notice Typically used to refill a liquidity pool's reserve * @dev This should only be callable by the `MetaPoolToken` * @param pool The `IReservePool` to transfer to * @param amount The amount of the pool's underlyer token to transer */ function transferToPool(address pool, uint256 amount) external; /** * @notice Swap tokens with a registered `ISwap` * @notice Used to compound reward tokens * @notice Used to rebalance underlyer tokens * @param name The name of the `IZap` * @param amount The amount of tokens to swap * @param minAmount The minimum amount of tokens to receive from the swap */ function swap( string calldata name, uint256 amount, uint256 minAmount ) external; /** * @notice Claim reward tokens with a registered `IZap` * @param name The name of the `IZap` */ function claim(string calldata name) external; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IZap} from "./IZap.sol"; /** * @notice For managing a collection of `IZap` contracts */ interface IZapRegistry { /** @notice Log when a new `IZap` is registered */ event ZapRegistered(IZap zap); /** @notice Log when an `IZap` is removed */ event ZapRemoved(string name); /** * @notice Add a new `IZap` to the registry * @dev Should not allow duplicate swaps * @param zap The new `IZap` */ function registerZap(IZap zap) external; /** * @notice Remove an `IZap` from the registry * @param name The name of the `IZap` (see `INameIdentifier`) */ function removeZap(string calldata name) external; /** * @notice Get the names of all registered `IZap` * @return An array of `IZap` names */ function zapNames() external view returns (string[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {ISwap} from "./ISwap.sol"; /** * @notice For managing a collection of `ISwap` contracts */ interface ISwapRegistry { /** @notice Log when a new `ISwap` is registered */ event SwapRegistered(ISwap swap); /** @notice Log when an `ISwap` is removed */ event SwapRemoved(string name); /** * @notice Add a new `ISwap` to the registry * @dev Should not allow duplicate swaps * @param swap The new `ISwap` */ function registerSwap(ISwap swap) external; /** * @notice Remove an `ISwap` from the registry * @param name The name of the `ISwap` (see `INameIdentifier`) */ function removeSwap(string calldata name) external; /** * @notice Get the names of all registered `ISwap` * @return An array of `ISwap` names */ function swapNames() external view returns (string[] memory); } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../Initializable.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 {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } pragma solidity ^0.6.0; import "../Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.6.11; import { AccessControlUpgradeSafe as OZAccessControl } from "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @notice Extends OpenZeppelin upgradeable AccessControl contract with modifiers * @dev This contract and AccessControl are essentially duplicates. */ contract AccessControlUpgradeSafe is OZAccessControl { /** @notice access control roles **/ bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE"); bytes32 public constant LP_ROLE = keccak256("LP_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE"); modifier onlyLpRole() { require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE"); _; } modifier onlyContractRole() { require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE"); _; } modifier onlyAdminRole() { require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE"); _; } modifier onlyEmergencyRole() { require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE"); _; } modifier onlyLpOrContractRole() { require( hasRole(LP_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_LP_OR_CONTRACT_ROLE" ); _; } modifier onlyAdminOrContractRole() { require( hasRole(ADMIN_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_ADMIN_OR_CONTRACT_ROLE" ); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../access/Ownable.sol"; import "./TransparentUpgradeableProxy.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ 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 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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 Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ 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 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice The address registry has two important purposes, one which * is fairly concrete and another abstract. * * 1. The registry enables components of the APY.Finance system * and external systems to retrieve core addresses reliably * even when the functionality may move to a different * address. * * 2. The registry also makes explicit which contracts serve * as primary entrypoints for interacting with different * components. Not every contract is registered here, only * the ones properly deserving of an identifier. This helps * define explicit boundaries between groups of contracts, * each of which is logically cohesive. */ interface IAddressRegistryV2 { /** * @notice Log when a new address is registered * @param id The ID of the new address * @param _address The new address */ event AddressRegistered(bytes32 id, address _address); /** * @notice Log when an address is removed from the registry * @param id The ID of the address * @param _address The address */ event AddressDeleted(bytes32 id, address _address); /** * @notice Register address with identifier * @dev Using an existing ID will replace the old address with new * @dev Currently there is no way to remove an ID, as attempting to * register the zero address will revert. */ function registerAddress(bytes32 id, address address_) external; /** * @notice Registers multiple address at once * @dev Convenient method to register multiple addresses at once. * @param ids Ids to register addresses under * @param addresses Addresses to register */ function registerMultipleAddresses( bytes32[] calldata ids, address[] calldata addresses ) external; /** * @notice Removes a registered id and it's associated address * @dev Delete the address corresponding to the identifier Time-complexity is O(n) where n is the length of `_idList`. * @param id ID to remove along with it's associated address */ function deleteAddress(bytes32 id) external; /** * @notice Returns the list of all registered identifiers. * @return List of identifiers */ function getIds() external view returns (bytes32[] memory); /** * @notice Returns the list of all registered identifiers * @param id Component identifier * @return The current address represented by an identifier */ function getAddress(bytes32 id) external view returns (address); /** * @notice Returns the TVL Manager Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return TVL Manager Address */ function tvlManagerAddress() external view returns (address); /** * @notice Returns the Chainlink Registry Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Chainlink Registry Address */ function chainlinkRegistryAddress() external view returns (address); /** * @notice Returns the DAI Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return DAI Pool Address */ function daiPoolAddress() external view returns (address); /** * @notice Returns the USDC Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDC Pool Address */ function usdcPoolAddress() external view returns (address); /** * @notice Returns the USDT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDT Pool Address */ function usdtPoolAddress() external view returns (address); /** * @notice Returns the MAPT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return MAPT Pool Address */ function mAptAddress() external view returns (address); /** * @notice Returns the LP Account Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Account Address */ function lpAccountAddress() external view returns (address); /** * @notice Returns the LP Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Safe Address */ function lpSafeAddress() external view returns (address); /** * @notice Returns the Admin Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Admin Safe Address */ function adminSafeAddress() external view returns (address); /** * @notice Returns the Emergency Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Emergency Safe Address */ function emergencySafeAddress() external view returns (address); /** * @notice Returns the Oracle Adapter Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Oracle Adapter Address */ function oracleAdapterAddress() external view returns (address); } /** SPDX-License-Identifier: UNLICENSED ---------------------------------- ---- APY.Finance comments -------- ---------------------------------- Due to pragma being fixed at 0.6.6, we had to copy over this contract and fix the imports. original path: @chainlink/contracts/src/v0.6/FluxAggregator.sol npm package version: 0.0.9 */ pragma solidity 0.6.11; import "@chainlink/contracts/src/v0.6/Median.sol"; import "@chainlink/contracts/src/v0.6/Owned.sol"; import "@chainlink/contracts/src/v0.6/SafeMath128.sol"; import "@chainlink/contracts/src/v0.6/SafeMath32.sol"; import "@chainlink/contracts/src/v0.6/SafeMath64.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol"; /* solhint-disable */ /** * @title The Prepaid Aggregator contract * @notice Handles aggregating data pushed in from off-chain, and unlocks * payment for oracles as they report. Oracles' submissions are gathered in * rounds, with each round aggregating the submissions for each oracle into a * single answer. The latest aggregated answer is exposed as well as historical * answers and their updated at timestamp. */ contract FluxAggregator is AggregatorV2V3Interface, Owned { using SafeMath for uint256; using SafeMath128 for uint128; using SafeMath64 for uint64; using SafeMath32 for uint32; struct Round { int256 answer; uint64 startedAt; uint64 updatedAt; uint32 answeredInRound; } struct RoundDetails { int256[] submissions; uint32 maxSubmissions; uint32 minSubmissions; uint32 timeout; uint128 paymentAmount; } struct OracleStatus { uint128 withdrawable; uint32 startingRound; uint32 endingRound; uint32 lastReportedRound; uint32 lastStartedRound; int256 latestSubmission; uint16 index; address admin; address pendingAdmin; } struct Requester { bool authorized; uint32 delay; uint32 lastStartedRound; } struct Funds { uint128 available; uint128 allocated; } LinkTokenInterface public linkToken; AggregatorValidatorInterface public validator; // Round related params uint128 public paymentAmount; uint32 public maxSubmissionCount; uint32 public minSubmissionCount; uint32 public restartDelay; uint32 public timeout; uint8 public override decimals; string public override description; int256 public immutable minSubmissionValue; int256 public immutable maxSubmissionValue; uint256 public constant override version = 3; /** * @notice To ensure owner isn't withdrawing required funds as oracles are * submitting updates, we enforce that the contract maintains a minimum * reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to * oracles. (Of course, this doesn't prevent the contract from running out of * funds without the owner's intervention.) */ uint256 private constant RESERVE_ROUNDS = 2; uint256 private constant MAX_ORACLE_COUNT = 77; uint32 private constant ROUND_MAX = 2**32 - 1; uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // An error specific to the Aggregator V3 Interface, to prevent possible // confusion around accidentally reading unset values as reported values. string private constant V3_NO_DATA_ERROR = "No data present"; uint32 private reportingRoundId; uint32 internal latestRoundId; mapping(address => OracleStatus) private oracles; mapping(uint32 => Round) internal rounds; mapping(uint32 => RoundDetails) internal details; mapping(address => Requester) internal requesters; address[] private oracleAddresses; Funds private recordedFunds; event AvailableFundsUpdated(uint256 indexed amount); event RoundDetailsUpdated( uint128 indexed paymentAmount, uint32 indexed minSubmissionCount, uint32 indexed maxSubmissionCount, uint32 restartDelay, uint32 timeout // measured in seconds ); event OraclePermissionsUpdated( address indexed oracle, bool indexed whitelisted ); event OracleAdminUpdated(address indexed oracle, address indexed newAdmin); event OracleAdminUpdateRequested( address indexed oracle, address admin, address newAdmin ); event SubmissionReceived( int256 indexed submission, uint32 indexed round, address indexed oracle ); event RequesterPermissionsSet( address indexed requester, bool authorized, uint32 delay ); event ValidatorUpdated(address indexed previous, address indexed current); /** * @notice set up the aggregator with initial configuration * @param _link The address of the LINK token * @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK) * @param _timeout is the number of seconds after the previous round that are * allowed to lapse before allowing an oracle to skip an unfinished round * @param _validator is an optional contract address for validating * external validation of answers * @param _minSubmissionValue is an immutable check for a lower bound of what * submission values are accepted from an oracle * @param _maxSubmissionValue is an immutable check for an upper bound of what * submission values are accepted from an oracle * @param _decimals represents the number of decimals to offset the answer by * @param _description a short description of what is being reported */ constructor( address _link, uint128 _paymentAmount, uint32 _timeout, address _validator, int256 _minSubmissionValue, int256 _maxSubmissionValue, uint8 _decimals, string memory _description ) public { linkToken = LinkTokenInterface(_link); updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout); setValidator(_validator); minSubmissionValue = _minSubmissionValue; maxSubmissionValue = _maxSubmissionValue; decimals = _decimals; description = _description; rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout))); } /** * @notice called by oracles when they have witnessed a need to update * @param _roundId is the ID of the round this submission pertains to * @param _submission is the updated data that the oracle is submitting */ function submit(uint256 _roundId, int256 _submission) external { bytes memory error = validateOracleRound(msg.sender, uint32(_roundId)); require( _submission >= minSubmissionValue, "value below minSubmissionValue" ); require( _submission <= maxSubmissionValue, "value above maxSubmissionValue" ); require(error.length == 0, string(error)); oracleInitializeNewRound(uint32(_roundId)); recordSubmission(_submission, uint32(_roundId)); (bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId)); payOracle(uint32(_roundId)); deleteRoundDetails(uint32(_roundId)); if (updated) { validateAnswer(uint32(_roundId), newAnswer); } } /** * @notice called by the owner to remove and add new oracles as well as * update the round related parameters that pertain to total oracle count * @param _removed is the list of addresses for the new Oracles being removed * @param _added is the list of addresses for the new Oracles being added * @param _addedAdmins is the admin addresses for the new respective _added * list. Only this address is allowed to access the respective oracle's funds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function changeOracles( address[] calldata _removed, address[] calldata _added, address[] calldata _addedAdmins, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay ) external onlyOwner() { for (uint256 i = 0; i < _removed.length; i++) { removeOracle(_removed[i]); } require( _added.length == _addedAdmins.length, "need same oracle and admin count" ); require( uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed" ); for (uint256 i = 0; i < _added.length; i++) { addOracle(_added[i], _addedAdmins[i]); } updateFutureRounds( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout ); } /** * @notice update the round and payment related parameters for subsequent * rounds * @param _paymentAmount is the payment amount for subsequent rounds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function updateFutureRounds( uint128 _paymentAmount, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay, uint32 _timeout ) public onlyOwner() { uint32 oracleNum = oracleCount(); // Save on storage reads require( _maxSubmissions >= _minSubmissions, "max must equal/exceed min" ); require(oracleNum >= _maxSubmissions, "max cannot exceed total"); require( oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total" ); require( recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment" ); if (oracleCount() > 0) { require(_minSubmissions > 0, "min must be greater than 0"); } paymentAmount = _paymentAmount; minSubmissionCount = _minSubmissions; maxSubmissionCount = _maxSubmissions; restartDelay = _restartDelay; timeout = _timeout; emit RoundDetailsUpdated( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, _timeout ); } /** * @notice the amount of payment yet to be withdrawn by oracles */ function allocatedFunds() external view returns (uint128) { return recordedFunds.allocated; } /** * @notice the amount of future funding available to oracles */ function availableFunds() external view returns (uint128) { return recordedFunds.available; } /** * @notice recalculate the amount of LINK available for payouts */ function updateAvailableFunds() public { Funds memory funds = recordedFunds; uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated); if (funds.available != nowAvailable) { recordedFunds.available = uint128(nowAvailable); emit AvailableFundsUpdated(nowAvailable); } } /** * @notice returns the number of oracles */ function oracleCount() public view returns (uint8) { return uint8(oracleAddresses.length); } /** * @notice returns an array of addresses containing the oracles on contract */ function getOracles() external view returns (address[] memory) { return oracleAddresses; } /** * @notice get the most recently reported answer * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns (int256) { return rounds[latestRoundId].answer; } /** * @notice get the most recent updated at timestamp * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns (uint256) { return rounds[latestRoundId].updatedAt; } /** * @notice get the ID of the last updated round * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns (uint256) { return latestRoundId; } /** * @notice get past rounds answers * @param _roundId the round number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer(uint256 _roundId) public view virtual override returns (int256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].answer; } return 0; } /** * @notice get timestamp when an answer was last updated * @param _roundId the round number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].updatedAt; } return 0; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time out * and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet received * maxSubmissions) answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Round memory r = rounds[uint32(_roundId)]; require( r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR ); return ( _roundId, r.answer, r.startedAt, r.updatedAt, r.answeredInRound ); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. Consumers are encouraged to * use this more fully featured method over the "legacy" latestRound/ * latestAnswer/latestTimestamp functions. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time * out and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet * received maxSubmissions) answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return getRoundData(latestRoundId); } /** * @notice query the available amount of LINK for an oracle to withdraw */ function withdrawablePayment(address _oracle) external view returns (uint256) { return oracles[_oracle].withdrawable; } /** * @notice transfers the oracle's LINK to another address. Can only be called * by the oracle's admin. * @param _oracle is the oracle whose LINK is transferred * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawPayment( address _oracle, address _recipient, uint256 _amount ) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); // Safe to downcast _amount because the total amount of LINK is less than 2^128. uint128 amount = uint128(_amount); uint128 available = oracles[_oracle].withdrawable; require(available >= amount, "insufficient withdrawable funds"); oracles[_oracle].withdrawable = available.sub(amount); recordedFunds.allocated = recordedFunds.allocated.sub(amount); assert(linkToken.transfer(_recipient, uint256(amount))); } /** * @notice transfers the owner's LINK to another address * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawFunds(address _recipient, uint256 _amount) external onlyOwner() { uint256 available = uint256(recordedFunds.available); require( available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds" ); require( linkToken.transfer(_recipient, _amount), "token transfer failed" ); updateAvailableFunds(); } /** * @notice get the admin address of an oracle * @param _oracle is the address of the oracle whose admin is being queried */ function getAdmin(address _oracle) external view returns (address) { return oracles[_oracle].admin; } /** * @notice transfer the admin address for an oracle * @param _oracle is the address of the oracle whose admin is being transferred * @param _newAdmin is the new admin address */ function transferAdmin(address _oracle, address _newAdmin) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); oracles[_oracle].pendingAdmin = _newAdmin; emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin); } /** * @notice accept the admin address transfer for an oracle * @param _oracle is the address of the oracle whose admin is being transferred */ function acceptAdmin(address _oracle) external { require( oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin" ); oracles[_oracle].pendingAdmin = address(0); oracles[_oracle].admin = msg.sender; emit OracleAdminUpdated(_oracle, msg.sender); } /** * @notice allows non-oracles to request a new round */ function requestNewRound() external returns (uint80) { require(requesters[msg.sender].authorized, "not authorized requester"); uint32 current = reportingRoundId; require( rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable" ); uint32 newRoundId = current.add(1); requesterInitializeNewRound(newRoundId); return newRoundId; } /** * @notice allows the owner to specify new non-oracles to start new rounds * @param _requester is the address to set permissions for * @param _authorized is a boolean specifying whether they can start new rounds or not * @param _delay is the number of rounds the requester must wait before starting another round */ function setRequesterPermissions( address _requester, bool _authorized, uint32 _delay ) external onlyOwner() { if (requesters[_requester].authorized == _authorized) return; if (_authorized) { requesters[_requester].authorized = _authorized; requesters[_requester].delay = _delay; } else { delete requesters[_requester]; } emit RequesterPermissionsSet(_requester, _authorized, _delay); } /** * @notice called through LINK's transferAndCall to update available funds * in the same transaction as the funds were transferred to the aggregator * @param _data is mostly ignored. It is checked for length, to be sure * nothing strange is passed in. */ function onTokenTransfer( address, uint256, bytes calldata _data ) external { require(_data.length == 0, "transfer doesn't accept calldata"); updateAvailableFunds(); } /** * @notice a method to provide all current info oracles need. Intended only * only to be callable by oracles. Not for use by contracts to read state. * @param _oracle the address to look up information for. */ function oracleRoundState(address _oracle, uint32 _queriedRoundId) external view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { require(msg.sender == tx.origin, "off-chain reading only"); if (_queriedRoundId > 0) { Round storage round = rounds[_queriedRoundId]; RoundDetails storage details = details[_queriedRoundId]; return ( eligibleForSpecificRound(_oracle, _queriedRoundId), _queriedRoundId, oracles[_oracle].latestSubmission, round.startedAt, details.timeout, recordedFunds.available, oracleCount(), (round.startedAt > 0 ? details.paymentAmount : paymentAmount) ); } else { return oracleRoundStateSuggestRound(_oracle); } } /** * @notice method to update the address which does external data validation. * @param _newValidator designates the address of the new validation contract. */ function setValidator(address _newValidator) public onlyOwner() { address previous = address(validator); if (previous != _newValidator) { validator = AggregatorValidatorInterface(_newValidator); emit ValidatorUpdated(previous, _newValidator); } } /** * Private */ function initializeNewRound(uint32 _roundId) private { updateTimedOutRoundInfo(_roundId.sub(1)); reportingRoundId = _roundId; RoundDetails memory nextDetails = RoundDetails( new int256[](0), maxSubmissionCount, minSubmissionCount, timeout, paymentAmount ); details[_roundId] = nextDetails; rounds[_roundId].startedAt = uint64(block.timestamp); emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt); } function oracleInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return; initializeNewRound(_roundId); oracles[msg.sender].lastStartedRound = _roundId; } function requesterInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads require( _roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests" ); initializeNewRound(_roundId); requesters[msg.sender].lastStartedRound = _roundId; } function updateTimedOutRoundInfo(uint32 _roundId) private { if (!timedOut(_roundId)) return; uint32 prevId = _roundId.sub(1); rounds[_roundId].answer = rounds[prevId].answer; rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound; rounds[_roundId].updatedAt = uint64(block.timestamp); delete details[_roundId]; } function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId) private view returns (bool _eligible) { if (rounds[_queriedRoundId].startedAt > 0) { return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } else { return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } } function oracleRoundStateSuggestRound(address _oracle) private view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { Round storage round = rounds[0]; OracleStatus storage oracle = oracles[_oracle]; bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId); // Instead of nudging oracles to submit to the next round, the inclusion of // the shouldSupersede bool in the if condition pushes them towards // submitting in a currently open round. if (supersedable(reportingRoundId) && shouldSupersede) { _roundId = reportingRoundId.add(1); round = rounds[_roundId]; _paymentAmount = paymentAmount; _eligibleToSubmit = delayed(_oracle, _roundId); } else { _roundId = reportingRoundId; round = rounds[_roundId]; _paymentAmount = details[_roundId].paymentAmount; _eligibleToSubmit = acceptingSubmissions(_roundId); } if (validateOracleRound(_oracle, _roundId).length != 0) { _eligibleToSubmit = false; } return ( _eligibleToSubmit, _roundId, oracle.latestSubmission, round.startedAt, details[_roundId].timeout, recordedFunds.available, oracleCount(), _paymentAmount ); } function updateRoundAnswer(uint32 _roundId) internal returns (bool, int256) { if ( details[_roundId].submissions.length < details[_roundId].minSubmissions ) { return (false, 0); } int256 newAnswer = Median.calculateInplace(details[_roundId].submissions); rounds[_roundId].answer = newAnswer; rounds[_roundId].updatedAt = uint64(block.timestamp); rounds[_roundId].answeredInRound = _roundId; latestRoundId = _roundId; emit AnswerUpdated(newAnswer, _roundId, now); return (true, newAnswer); } function validateAnswer(uint32 _roundId, int256 _newAnswer) private { AggregatorValidatorInterface av = validator; // cache storage reads if (address(av) == address(0)) return; uint32 prevRound = _roundId.sub(1); uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound; int256 prevRoundAnswer = rounds[prevRound].answer; // We do not want the validator to ever prevent reporting, so we limit its // gas usage and catch any errors that may arise. try av.validate{gas: VALIDATOR_GAS_LIMIT}( prevAnswerRoundId, prevRoundAnswer, _roundId, _newAnswer ) {} catch {} } function payOracle(uint32 _roundId) private { uint128 payment = details[_roundId].paymentAmount; Funds memory funds = recordedFunds; funds.available = funds.available.sub(payment); funds.allocated = funds.allocated.add(payment); recordedFunds = funds; oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add( payment ); emit AvailableFundsUpdated(funds.available); } function recordSubmission(int256 _submission, uint32 _roundId) private { require( acceptingSubmissions(_roundId), "round not accepting submissions" ); details[_roundId].submissions.push(_submission); oracles[msg.sender].lastReportedRound = _roundId; oracles[msg.sender].latestSubmission = _submission; emit SubmissionReceived(_submission, _roundId, msg.sender); } function deleteRoundDetails(uint32 _roundId) private { if ( details[_roundId].submissions.length < details[_roundId].maxSubmissions ) return; delete details[_roundId]; } function timedOut(uint32 _roundId) private view returns (bool) { uint64 startedAt = rounds[_roundId].startedAt; uint32 roundTimeout = details[_roundId].timeout; return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp; } function getStartingRound(address _oracle) private view returns (uint32) { uint32 currentRound = reportingRoundId; if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) { return currentRound; } return currentRound.add(1); } function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId) private view returns (bool) { return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0; } function requiredReserve(uint256 payment) private view returns (uint256) { return payment.mul(oracleCount()).mul(RESERVE_ROUNDS); } function addOracle(address _oracle, address _admin) private { require(!oracleEnabled(_oracle), "oracle already enabled"); require(_admin != address(0), "cannot set admin to 0"); require( oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin" ); oracles[_oracle].startingRound = getStartingRound(_oracle); oracles[_oracle].endingRound = ROUND_MAX; oracles[_oracle].index = uint16(oracleAddresses.length); oracleAddresses.push(_oracle); oracles[_oracle].admin = _admin; emit OraclePermissionsUpdated(_oracle, true); emit OracleAdminUpdated(_oracle, _admin); } function removeOracle(address _oracle) private { require(oracleEnabled(_oracle), "oracle not enabled"); oracles[_oracle].endingRound = reportingRoundId.add(1); address tail = oracleAddresses[uint256(oracleCount()).sub(1)]; uint16 index = oracles[_oracle].index; oracles[tail].index = index; delete oracles[_oracle].index; oracleAddresses[index] = tail; oracleAddresses.pop(); emit OraclePermissionsUpdated(_oracle, false); } function validateOracleRound(address _oracle, uint32 _roundId) private view returns (bytes memory) { // cache storage reads uint32 startingRound = oracles[_oracle].startingRound; uint32 rrId = reportingRoundId; if (startingRound == 0) return "not enabled oracle"; if (startingRound > _roundId) return "not yet enabled oracle"; if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle"; if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds"; if ( _roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId) ) return "invalid round to report"; if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable"; } function supersedable(uint32 _roundId) private view returns (bool) { return rounds[_roundId].updatedAt > 0 || timedOut(_roundId); } function oracleEnabled(address _oracle) private view returns (bool) { return oracles[_oracle].endingRound == ROUND_MAX; } function acceptingSubmissions(uint32 _roundId) private view returns (bool) { return details[_roundId].maxSubmissions != 0; } function delayed(address _oracle, uint32 _roundId) private view returns (bool) { uint256 lastStarted = oracles[_oracle].lastStartedRound; return _roundId > lastStarted + restartDelay || lastStarted == 0; } function newRound(uint32 _roundId) private view returns (bool) { return _roundId == reportingRoundId.add(1); } function validRoundId(uint256 _roundId) private view returns (bool) { return _roundId <= ROUND_MAX; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface for securely interacting with Chainlink aggregators */ interface IOracleAdapter { struct Value { uint256 value; uint256 periodEnd; } /// @notice Event fired when asset's pricing source (aggregator) is updated event AssetSourceUpdated(address indexed asset, address indexed source); /// @notice Event fired when the TVL aggregator address is updated event TvlSourceUpdated(address indexed source); /** * @notice Set the TVL source (aggregator) * @param source The new TVL source (aggregator) */ function emergencySetTvlSource(address source) external; /** * @notice Set an asset's price source (aggregator) * @param asset The asset to change the source of * @param source The new source (aggregator) */ function emergencySetAssetSource(address asset, address source) external; /** * @notice Set multiple assets' pricing sources * @param assets An array of assets (tokens) * @param sources An array of price sources (aggregators) */ function emergencySetAssetSources( address[] memory assets, address[] memory sources ) external; /** * @notice Retrieve the asset's price from its pricing source * @param asset The asset address * @return The price of the asset */ function getAssetPrice(address asset) external view returns (uint256); /** * @notice Retrieve the deployed TVL from the TVL aggregator * @return The TVL */ function getTvl() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; interface IOverrideOracle is IOracleAdapter { /** * @notice Event fired when asset value is set manually * @param asset The asset that is being overridden * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event AssetValueSet( address asset, uint256 value, uint256 period, uint256 periodEnd ); /** * @notice Event fired when manually submitted asset value is * invalidated, allowing usual Chainlink pricing. */ event AssetValueUnset(address asset); /** * @notice Event fired when deployed TVL is set manually * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event TvlSet(uint256 value, uint256 period, uint256 periodEnd); /** * @notice Event fired when manually submitted TVL is * invalidated, allowing usual Chainlink pricing. */ event TvlUnset(); /** * @notice Manually override the asset pricing source with a value * @param asset The asset that is being overriden * @param value asset value to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetAssetValue( address asset, uint256 value, uint256 period ) external; /** * @notice Revoke manually set value, allowing usual Chainlink pricing * @param asset address of asset to price */ function emergencyUnsetAssetValue(address asset) external; /** * @notice Manually override the TVL source with a value * @param value TVL to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetTvl(uint256 value, uint256 period) external; /// @notice Revoke manually set value, allowing usual Chainlink pricing function emergencyUnsetTvl() external; /// @notice Check if TVL has active manual override function hasTvlOverride() external view returns (bool); /** * @notice Check if asset has active manual override * @param asset address of the asset * @return `true` if manual override is active */ function hasAssetOverride(address asset) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; /** * @notice For an `IOracleAdapter` that can be locked and unlocked */ interface ILockingOracle is IOracleAdapter { /// @notice Event fired when using the default lock event DefaultLocked(address locker, uint256 defaultPeriod, uint256 lockEnd); /// @notice Event fired when using a specified lock period event Locked(address locker, uint256 activePeriod, uint256 lockEnd); /// @notice Event fired when changing the default locking period event DefaultLockPeriodChanged(uint256 newPeriod); /// @notice Event fired when unlocking the adapter event Unlocked(); /// @notice Event fired when updating the threshold for stale data event ChainlinkStalePeriodUpdated(uint256 period); /// @notice Block price/value retrieval for the default locking duration function lock() external; /** * @notice Block price/value retrieval for the specified duration. * @param period number of blocks to block retrieving values */ function lockFor(uint256 period) external; /** * @notice Unblock price/value retrieval. Should only be callable * by the Emergency Safe. */ function emergencyUnlock() external; /** * @notice Set the length of time before values can be retrieved. * @param newPeriod number of blocks before values can be retrieved */ function setDefaultLockPeriod(uint256 newPeriod) external; /** * @notice Set the length of time before an agg value is considered stale. * @param chainlinkStalePeriod_ the length of time in seconds */ function setChainlinkStalePeriod(uint256 chainlinkStalePeriod_) external; /** * @notice Get the length of time, in number of blocks, before values * can be retrieved. */ function defaultLockPeriod() external returns (uint256 period); /// @notice Check if the adapter is blocked from retrieving values. function isLocked() external view returns (bool); } pragma solidity ^0.6.0; import "./vendor/SafeMath.sol"; import "./SignedSafeMath.sol"; library Median { using SignedSafeMath for int256; int256 constant INT_MAX = 2**255-1; /** * @notice Returns the sorted middle, or the average of the two middle indexed items if the * array has an even number of elements. * @dev The list passed as an argument isn't modified. * @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs * the runtime is O(n^2). * @param list The list of elements to compare */ function calculate(int256[] memory list) internal pure returns (int256) { return calculateInplace(copy(list)); } /** * @notice See documentation for function calculate. * @dev The list passed as an argument may be permuted. */ function calculateInplace(int256[] memory list) internal pure returns (int256) { require(0 < list.length, "list must not be empty"); uint256 len = list.length; uint256 middleIndex = len / 2; if (len % 2 == 0) { int256 median1; int256 median2; (median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex); return SignedSafeMath.avg(median1, median2); } else { return quickselect(list, 0, len - 1, middleIndex); } } /** * @notice Maximum length of list that shortSelectTwo can handle */ uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7; /** * @notice Select the k1-th and k2-th element from list of length at most 7 * @dev Uses an optimal sorting network */ function shortSelectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) private pure returns (int256 k1th, int256 k2th) { // Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network) // for lists of length 7. Network layout is taken from // http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg uint256 len = hi + 1 - lo; int256 x0 = list[lo + 0]; int256 x1 = 1 < len ? list[lo + 1] : INT_MAX; int256 x2 = 2 < len ? list[lo + 2] : INT_MAX; int256 x3 = 3 < len ? list[lo + 3] : INT_MAX; int256 x4 = 4 < len ? list[lo + 4] : INT_MAX; int256 x5 = 5 < len ? list[lo + 5] : INT_MAX; int256 x6 = 6 < len ? list[lo + 6] : INT_MAX; if (x0 > x1) {(x0, x1) = (x1, x0);} if (x2 > x3) {(x2, x3) = (x3, x2);} if (x4 > x5) {(x4, x5) = (x5, x4);} if (x0 > x2) {(x0, x2) = (x2, x0);} if (x1 > x3) {(x1, x3) = (x3, x1);} if (x4 > x6) {(x4, x6) = (x6, x4);} if (x1 > x2) {(x1, x2) = (x2, x1);} if (x5 > x6) {(x5, x6) = (x6, x5);} if (x0 > x4) {(x0, x4) = (x4, x0);} if (x1 > x5) {(x1, x5) = (x5, x1);} if (x2 > x6) {(x2, x6) = (x6, x2);} if (x1 > x4) {(x1, x4) = (x4, x1);} if (x3 > x6) {(x3, x6) = (x6, x3);} if (x2 > x4) {(x2, x4) = (x4, x2);} if (x3 > x5) {(x3, x5) = (x5, x3);} if (x3 > x4) {(x3, x4) = (x4, x3);} uint256 index1 = k1 - lo; if (index1 == 0) {k1th = x0;} else if (index1 == 1) {k1th = x1;} else if (index1 == 2) {k1th = x2;} else if (index1 == 3) {k1th = x3;} else if (index1 == 4) {k1th = x4;} else if (index1 == 5) {k1th = x5;} else if (index1 == 6) {k1th = x6;} else {revert("k1 out of bounds");} uint256 index2 = k2 - lo; if (k1 == k2) {return (k1th, k1th);} else if (index2 == 0) {return (k1th, x0);} else if (index2 == 1) {return (k1th, x1);} else if (index2 == 2) {return (k1th, x2);} else if (index2 == 3) {return (k1th, x3);} else if (index2 == 4) {return (k1th, x4);} else if (index2 == 5) {return (k1th, x5);} else if (index2 == 6) {return (k1th, x6);} else {revert("k2 out of bounds");} } /** * @notice Selects the k-th ranked element from list, looking only at indices between lo and hi * (inclusive). Modifies list in-place. */ function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k) private pure returns (int256 kth) { require(lo <= k); require(k <= hi); while (lo < hi) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { int256 ignore; (kth, ignore) = shortSelectTwo(list, lo, hi, k, k); return kth; } uint256 pivotIndex = partition(list, lo, hi); if (k <= pivotIndex) { // since pivotIndex < (original hi passed to partition), // termination is guaranteed in this case hi = pivotIndex; } else { // since (original lo passed to partition) <= pivotIndex, // termination is guaranteed in this case lo = pivotIndex + 1; } } return list[lo]; } /** * @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between * lo and hi (inclusive). Modifies list in-place. */ function quickselectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) internal // for testing pure returns (int256 k1th, int256 k2th) { require(k1 < k2); require(lo <= k1 && k1 <= hi); require(lo <= k2 && k2 <= hi); while (true) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { return shortSelectTwo(list, lo, hi, k1, k2); } uint256 pivotIdx = partition(list, lo, hi); if (k2 <= pivotIdx) { hi = pivotIdx; } else if (pivotIdx < k1) { lo = pivotIdx + 1; } else { assert(k1 <= pivotIdx && pivotIdx < k2); k1th = quickselect(list, lo, pivotIdx, k1); k2th = quickselect(list, pivotIdx + 1, hi, k2); return (k1th, k2th); } } } /** * @notice Partitions list in-place using Hoare's partitioning scheme. * Only elements of list between indices lo and hi (inclusive) will be modified. * Returns an index i, such that: * - lo <= i < hi * - forall j in [lo, i]. list[j] <= list[i] * - forall j in [i, hi]. list[i] <= list[j] */ function partition(int256[] memory list, uint256 lo, uint256 hi) private pure returns (uint256) { // We don't care about overflow of the addition, because it would require a list // larger than any feasible computer's memory. int256 pivot = list[(lo + hi) / 2]; lo -= 1; // this can underflow. that's intentional. hi += 1; while (true) { do { lo += 1; } while (list[lo] < pivot); do { hi -= 1; } while (list[hi] > pivot); if (lo < hi) { (list[lo], list[hi]) = (list[hi], list[lo]); } else { // Let orig_lo and orig_hi be the original values of lo and hi passed to partition. // Then, hi < orig_hi, because hi decreases *strictly* monotonically // in each loop iteration and // - either list[orig_hi] > pivot, in which case the first loop iteration // will achieve hi < orig_hi; // - or list[orig_hi] <= pivot, in which case at least two loop iterations are // needed: // - lo will have to stop at least once in the interval // [orig_lo, (orig_lo + orig_hi)/2] // - (orig_lo + orig_hi)/2 < orig_hi return hi; } } } /** * @notice Makes an in-memory copy of the array passed in * @param list Reference to the array to be copied */ function copy(int256[] memory list) private pure returns(int256[] memory) { int256[] memory list2 = new int256[](list.length); for (uint256 i = 0; i < list.length; i++) { list2[i] = list[i]; } return list2; } } pragma solidity ^0.6.0; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 128 bit integers. */ library SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a, "SafeMath: subtraction overflow"); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 32 bit integers. */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { require(b <= a, "SafeMath: subtraction overflow"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // 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; } uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 64 bit integers. */ library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } pragma solidity ^0.6.0; interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); } pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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 Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } /** * @notice Computes average of two signed integers, ensuring that the computation * doesn't overflow. * @dev If the result is not an integer, it is rounded towards zero. For example, * avg(-3, -4) = -3 */ function avg(int256 _a, int256 _b) internal pure returns (int256) { if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) { return add(_a, _b) / 2; } int256 remainder = (_a % 2 + _b % 2) / 2; return add(add(_a / 2, _b / 2), remainder); } } pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {IChainlinkRegistry} from "./IChainlinkRegistry.sol"; import {IAssetAllocationRegistry} from "./IAssetAllocationRegistry.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; import {ImmutableAssetAllocation} from "./ImmutableAssetAllocation.sol"; import {Erc20AllocationConstants} from "./Erc20Allocation.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IReservePool} from "contracts/pool/Imports.sol"; /** * @notice Facilitate lending liquidity to the LP Account from pools */ interface ILpAccountFunder { /** * @notice Log when liquidity is lent to the LP Account * @param poolIds An array of address registry IDs for pools that lent * @param amounts An array of the amount each pool lent */ event FundLpAccount(bytes32[] poolIds, uint256[] amounts); /** * @notice Log when liquidity is repaid to the pools * @param poolIds An array of address registry IDs for pools were repaid * @param amounts An array of the amount each pool was repaid */ event WithdrawFromLpAccount(bytes32[] poolIds, uint256[] amounts); /** * @notice Log when liquidity is lent to the LP Account * @param pools An array of address registry IDs for pools that lent * @param amounts An array of the amount each pool lent */ event EmergencyFundLpAccount(IReservePool[] pools, uint256[] amounts); /** * @notice Log when liquidity is repaid to the pools * @param pools An array of address registry IDs for pools were repaid * @param amounts An array of the amount each pool was repaid */ event EmergencyWithdrawFromLpAccount( IReservePool[] pools, uint256[] amounts ); /** * @notice Lend liquidity to the LP Account from pools * @dev Should calculate excess liquidity that can be lent * @param pools An array of address registry IDs for pools that lent */ function fundLpAccount(bytes32[] calldata pools) external; /** * @notice Lend liquidity to the LP Account from pools * @notice Only used in emergencies * @dev Should only be callable by the Admin Safe * @dev Can lend any arbitrary amount of liquidity * @param pools An array of address registry IDs for pools that lent * @param amounts An array of amounts to borrow from each pool */ function emergencyFundLpAccount( IReservePool[] calldata pools, uint256[] calldata amounts ) external; /** * @notice Repay liquidity borrowed by the LP Account * @dev Should repay enough to fill up the pools' reserves * @param pools An array of address registry IDs for pools that were repaid */ function withdrawFromLpAccount(bytes32[] calldata pools) external; /** * @notice Repay liquidity borrowed by the LP Account * @notice Only used in emergencies * @dev Should only be callable by the Admin Safe * @dev Can repay any arbitrary amount of liquidity * @param pools An array of address registry IDs for pools that were repaid * @param amounts An array of amounts to repay to each pool */ function emergencyWithdrawFromLpAccount( IReservePool[] calldata pools, uint256[] calldata amounts ) external; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {ILiquidityPoolV2} from "./ILiquidityPoolV2.sol"; /** * @notice For pools that keep a separate reserve of tokens */ interface IReservePool is ILiquidityPoolV2 { /** * @notice Log when the percent held in reserve is changed * @param reservePercentage The new percent held in reserve */ event ReservePercentageChanged(uint256 reservePercentage); /** * @notice Set a new percent of tokens to hold in reserve * @param reservePercentage_ The new percent */ function setReservePercentage(uint256 reservePercentage_) external; /** * @notice Transfer an amount of tokens to the LP Account * @dev This should only be callable by the `MetaPoolToken` * @param amount The amount of tokens */ function transferToLpAccount(uint256 amount) external; /** * @notice Get the amount of tokens missing from the reserve * @dev A negative value indicates extra tokens not needed for the reserve * @return The amount of missing tokens */ function getReserveTopUpValue() external view returns (int256); /** * @notice Get the current percentage of tokens held in reserve * @return The percent */ function reservePercentage() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice For pools that can charge an early withdrawal fee */ interface IWithdrawFeePool { /** * @notice Log when the fee period changes * @param feePeriod The new fee period */ event FeePeriodChanged(uint256 feePeriod); /** * @notice Log when the fee percentage changes * @param feePercentage The new percentage */ event FeePercentageChanged(uint256 feePercentage); /** * @notice Set the new fee period * @param feePeriod_ The new fee period */ function setFeePeriod(uint256 feePeriod_) external; /** * @notice Set the new fee percentage * @param feePercentage_ The new percentage */ function setFeePercentage(uint256 feePercentage_) external; /** * @notice Get the period of time that a withdrawal will be considered early * @notice An early withdrawal gets charged a fee * @notice The period starts from the time of the last deposit for an account * @return The time in seconds */ function feePeriod() external view returns (uint256); /** * @notice Get the percentage of a withdrawal that is charged as a fee * @return The percentage */ function feePercentage() external view returns (uint256); /** * @notice Check if caller will be charged early withdrawal fee * @return `true` when fee will apply, `false` when it won't */ function isEarlyRedeem() external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice For pools that can be locked and unlocked in emergencies */ interface ILockingPool { /** @notice Log when deposits are locked */ event AddLiquidityLocked(); /** @notice Log when deposits are unlocked */ event AddLiquidityUnlocked(); /** @notice Log when withdrawals are locked */ event RedeemLocked(); /** @notice Log when withdrawals are unlocked */ event RedeemUnlocked(); /** @notice Lock deposits and withdrawals */ function emergencyLock() external; /** @notice Unlock deposits and withdrawals */ function emergencyUnlock() external; /** @notice Lock deposits */ function emergencyLockAddLiquidity() external; /** @notice Unlock deposits */ function emergencyUnlockAddLiquidity() external; /** @notice Lock withdrawals */ function emergencyLockRedeem() external; /** @notice Unlock withdrawals */ function emergencyUnlockRedeem() external; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IDetailedERC20} from "contracts/common/Imports.sol"; /** * @notice For pools that locked value between accounts * @dev Shares are accounted for using the `APT` token */ interface IPoolToken { /** * @notice Log a token deposit * @param sender Address of the depositor account * @param token Token deposited * @param tokenAmount The amount of tokens deposited * @param aptMintAmount Number of shares received * @param tokenEthValue Total value of the deposit * @param totalEthValueLocked Total value of the pool */ event DepositedAPT( address indexed sender, IDetailedERC20 token, uint256 tokenAmount, uint256 aptMintAmount, uint256 tokenEthValue, uint256 totalEthValueLocked ); /** * @notice Log a token withdrawal * @param sender Address of the withdrawal account * @param token Token withdrawn * @param redeemedTokenAmount The amount of tokens withdrawn * @param aptRedeemAmount Number of shares redeemed * @param tokenEthValue Total value of the withdrawal * @param totalEthValueLocked Total value of the pool */ event RedeemedAPT( address indexed sender, IDetailedERC20 token, uint256 redeemedTokenAmount, uint256 aptRedeemAmount, uint256 tokenEthValue, uint256 totalEthValueLocked ); /** * @notice Add liquidity for a share of the pool * @param amount Amount to deposit of the underlying stablecoin */ function addLiquidity(uint256 amount) external; /** * @notice Redeem shares of the pool to withdraw liquidity * @param tokenAmount The amount of shares to redeem */ function redeem(uint256 tokenAmount) external; /** * @notice Determine the share received for a deposit * @param depositAmount The size of the deposit * @return The number of shares */ function calculateMintAmount(uint256 depositAmount) external view returns (uint256); /** * @notice How many tokens can be withdrawn with an amount of shares * @notice Accounts for early withdrawal fee * @param aptAmount The amount of shares * @return The amount of tokens */ function getUnderlyerAmountWithFee(uint256 aptAmount) external view returns (uint256); /** * @notice How many tokens can be withdrawn with an amount of shares * @param aptAmount The amount of shares * @return The amount of tokens */ function getUnderlyerAmount(uint256 aptAmount) external view returns (uint256); /** * @notice Get the total USD value of an amount of shares * @param aptAmount The amount of shares * @return The total USD value of the shares */ function getAPTValue(uint256 aptAmount) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IDetailedERC20} from "contracts/common/Imports.sol"; /** * @notice For contracts that hold tokens and track the value locked */ interface ILiquidityPoolV2 { /** * @notice The token held by the pool * @return The token address */ function underlyer() external view returns (IDetailedERC20); /** * @notice Get the total USD value locked in the pool * @return The total USD value */ function getPoolTotalValue() external view returns (uint256); /** * @notice Get the total USD value of an amount of tokens * @param underlyerAmount The amount of tokens * @return The total USD value */ function getValueFromUnderlyerAmount(uint256 underlyerAmount) external view returns (uint256); /** * @notice Get the USD price of the token held by the pool * @return The price */ function getUnderlyerPrice() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20, IDetailedERC20} from "contracts/common/Imports.sol"; /** * @notice An asset allocation for tokens not stored in a protocol * @dev `IZap`s and `ISwap`s register these separate from other allocations * @dev Unlike other asset allocations, new tokens can be added or removed * @dev Registration can override `symbol` and `decimals` manually because * they are optional in the ERC20 standard. */ interface IErc20Allocation { /** @notice Log when an ERC20 allocation is registered */ event Erc20TokenRegistered(IERC20 token, string symbol, uint8 decimals); /** @notice Log when an ERC20 allocation is removed */ event Erc20TokenRemoved(IERC20 token); /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token */ function registerErc20Token(IDetailedERC20 token) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol */ function registerErc20Token(IDetailedERC20 token, string calldata symbol) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol * @param decimals Override the token decimals */ function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external; /** * @notice Remove an ERC20 token from the asset allocation * @param token The token to remove */ function removeErc20Token(IERC20 token) external; /** * @notice Check if an ERC20 token is registered * @param token The token to check * @return `true` if the token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20 token) external view returns (bool); /** * @notice Check if multiple ERC20 tokens are ALL registered * @param tokens An array of tokens to check * @return `true` if every token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20[] calldata tokens) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface used by Chainlink to aggregate allocations and compute TVL */ interface IChainlinkRegistry { /** * @notice Get all IDs from registered asset allocations * @notice Each ID is a unique asset allocation and token index pair * @dev Should contain no duplicate IDs * @return list of all IDs */ function getAssetAllocationIds() external view returns (bytes32[] memory); /** * @notice Get the LP Account's balance for an asset allocation ID * @param allocationId The ID to fetch the balance for * @return The balance for the LP Account */ function balanceOf(bytes32 allocationId) external view returns (uint256); /** * @notice Get the symbol for an allocation ID's underlying token * @param allocationId The ID to fetch the symbol for * @return The underlying token symbol */ function symbolOf(bytes32 allocationId) external view returns (string memory); /** * @notice Get the decimals for an allocation ID's underlying token * @param allocationId The ID to fetch the decimals for * @return The underlying token decimals */ function decimalsOf(bytes32 allocationId) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; /** * @notice For managing a collection of `IAssetAllocation` contracts */ interface IAssetAllocationRegistry { /** @notice Log when an asset allocation is registered */ event AssetAllocationRegistered(IAssetAllocation assetAllocation); /** @notice Log when an asset allocation is removed */ event AssetAllocationRemoved(string name); /** * @notice Add a new asset allocation to the registry * @dev Should not allow duplicate asset allocations * @param assetAllocation The new asset allocation */ function registerAssetAllocation(IAssetAllocation assetAllocation) external; /** * @notice Remove an asset allocation from the registry * @param name The name of the asset allocation (see `INameIdentifier`) */ function removeAssetAllocation(string memory name) external; /** * @notice Check if multiple asset allocations are ALL registered * @param allocationNames An array of asset allocation names * @return `true` if every allocation is registered, otherwise `false` */ function isAssetAllocationRegistered(string[] calldata allocationNames) external view returns (bool); /** * @notice Get the registered asset allocation with a given name * @param name The asset allocation name * @return The asset allocation */ function getAssetAllocation(string calldata name) external view returns (IAssetAllocation); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; abstract contract AssetAllocationBase is IAssetAllocation { function numberOfTokens() external view override returns (uint256) { return tokens().length; } function symbolOf(uint8 tokenIndex) public view override returns (string memory) { return tokens()[tokenIndex].symbol; } function decimalsOf(uint8 tokenIndex) public view override returns (uint8) { return tokens()[tokenIndex].decimals; } function addressOf(uint8 tokenIndex) public view returns (address) { return tokens()[tokenIndex].token; } function tokens() public view virtual override returns (TokenData[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {Address} from "contracts/libraries/Imports.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; /** * @notice Asset allocation with underlying tokens that cannot be added/removed */ abstract contract ImmutableAssetAllocation is AssetAllocationBase { using Address for address; constructor() public { _validateTokens(_getTokenData()); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory tokens_ = _getTokenData(); return tokens_; } /** * @notice Get the immutable array of underlying `TokenData` * @dev Should be implemented in child contracts with a hardcoded array * @return The array of `TokenData` */ function _getTokenData() internal pure virtual returns (TokenData[] memory); /** * @notice Verifies that a `TokenData` array works with the `TvlManager` * @dev Reverts when there is invalid `TokenData` * @param tokens_ The array of `TokenData` */ function _validateTokens(TokenData[] memory tokens_) internal view virtual { // length restriction due to encoding logic for allocation IDs require(tokens_.length < type(uint8).max, "TOO_MANY_TOKENS"); for (uint256 i = 0; i < tokens_.length; i++) { address token = tokens_[i].token; _validateTokenAddress(token); string memory symbol = tokens_[i].symbol; require(bytes(symbol).length != 0, "INVALID_SYMBOL"); } // TODO: check for duplicate tokens } /** * @notice Verify that a token is a contract * @param token The token to verify */ function _validateTokenAddress(address token) internal view virtual { require(token.isContract(), "INVALID_ADDRESS"); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IERC20, IDetailedERC20, AccessControl, INameIdentifier } from "contracts/common/Imports.sol"; import {Address, EnumerableSet} from "contracts/libraries/Imports.sol"; import {IAddressRegistryV2} from "contracts/registry/Imports.sol"; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; abstract contract Erc20AllocationConstants is INameIdentifier { string public constant override NAME = "erc20Allocation"; } contract Erc20Allocation is IErc20Allocation, AssetAllocationBase, Erc20AllocationConstants, AccessControl { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _tokenAddresses; mapping(address => TokenData) private _tokenToData; constructor(address addressRegistry_) public { require(addressRegistry_.isContract(), "INVALID_ADDRESS_REGISTRY"); IAddressRegistryV2 addressRegistry = IAddressRegistryV2(addressRegistry_); _setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress()); _setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress()); } function registerErc20Token(IDetailedERC20 token) external override onlyAdminOrContractRole { string memory symbol = token.symbol(); uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token(IDetailedERC20 token, string calldata symbol) external override onlyAdminRole { uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external override onlyAdminRole { _registerErc20Token(token, symbol, decimals); } function removeErc20Token(IERC20 token) external override onlyAdminRole { _tokenAddresses.remove(address(token)); delete _tokenToData[address(token)]; emit Erc20TokenRemoved(token); } function isErc20TokenRegistered(IERC20 token) external view override returns (bool) { return _tokenAddresses.contains(address(token)); } function isErc20TokenRegistered(IERC20[] calldata tokens) external view override returns (bool) { uint256 length = tokens.length; for (uint256 i = 0; i < length; i++) { if (!_tokenAddresses.contains(address(tokens[i]))) { return false; } } return true; } function balanceOf(address account, uint8 tokenIndex) external view override returns (uint256) { address token = addressOf(tokenIndex); return IERC20(token).balanceOf(account); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory _tokens = new TokenData[](_tokenAddresses.length()); for (uint256 i = 0; i < _tokens.length; i++) { address tokenAddress = _tokenAddresses.at(i); _tokens[i] = _tokenToData[tokenAddress]; } return _tokens; } function _registerErc20Token( IERC20 token, string memory symbol, uint8 decimals ) internal { require(address(token).isContract(), "INVALID_ADDRESS"); require(bytes(symbol).length != 0, "INVALID_SYMBOL"); _tokenAddresses.add(address(token)); _tokenToData[address(token)] = TokenData( address(token), symbol, decimals ); emit Erc20TokenRegistered(token, symbol, decimals); } }
Since the proxy delegate calls to this "logic" contract, any storage set by the logic contract's constructor during deploy is disregarded and this function is needed to initialize the proxy contract's storage according to this contract's layout. Since storage is not set yet, there is no simple way to protect calling this function with owner modifiers. Thus the OpenZeppelin `initializer` modifier protects this function from being called repeatedly. It should be called during the deployment so that it cannot be called by someone else later. NOTE: this function is copied from the V1 contract and has already been called during V1 deployment. It is included here for clarity./ initialize ancestor storage __Ownable_init_unchained(); <-- Comment-out for compiler; replaced by AccessControl initialize impl-specific storage setPriceAggregator(priceAgg); <-- deprecated in V2.
function initialize( address adminAddress, IDetailedERC20 underlyer_, AggregatorV3Interface priceAgg ) external initializer { require(adminAddress != address(0), "INVALID_ADMIN"); require(address(underlyer_) != address(0), "INVALID_TOKEN"); require(address(priceAgg) != address(0), "INVALID_AGG"); __Context_init_unchained(); __ReentrancyGuard_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("APY Pool Token", "APT"); _setAdminAddress(adminAddress); addLiquidityLock = false; redeemLock = false; underlyer = underlyer_; }
280,824
./full_match/4/0xaC9573a215CCBfABACF8485c8F2B147873Ae72dB/sources/docs.chain.link/samples/VRF/RaffleVRF.sol
Callback function used by VRF Coordinator to return the random number to this contract. Some action on the contract state should be taken here, like storing the result. WARNING: take care to avoid having multiple VRF requests in flight if their order of arrival would result in contract states with different outcomes. Otherwise miners or the VRF operator would could take advantage by controlling the order. The VRF Coordinator will only send this function verified responses, and the parent VRFConsumerBaseV2 contract ensures that this method only receives randomness from the designated VRFCoordinator. requestId uint256 randomWords uint256[] The random result returned by the oracle./
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override { for (uint256 i; i < randomWords.length; i++) { randomSeeds.push(randomWords[i]); } }
710,854
// Sources flattened with hardhat v2.6.5 https://hardhat.org // File @animoca/ethereum-contracts-core-1.1.2/contracts/metatx/ManagedIdentity.sol@v1.1.2 // SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.8.0; /* * 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. */ abstract contract ManagedIdentity { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/access/IERC173.sol@v1.1.2 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC-173 Contract Ownership Standard * Note: the ERC-165 identifier for this interface is 0x7f5828d0 */ interface IERC173 { /** * Event emited when ownership of a contract changes. * @param previousOwner the previous owner. * @param newOwner the new owner. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * Get the address of the owner * @return The address of the owner. */ function owner() external view returns (address); /** * Set the address of the new owner of the contract * Set newOwner to address(0) to renounce any ownership. * @dev Emits an {OwnershipTransferred} event. * @param newOwner The address of the new owner of the contract. Using the zero address means renouncing ownership. */ function transferOwnership(address newOwner) external; } // File @animoca/ethereum-contracts-core-1.1.2/contracts/access/Ownable.sol@v1.1.2 pragma solidity >=0.7.6 <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 ManagedIdentity, IERC173 { address internal _owner; /** * Initializes the contract, setting the deployer as the initial owner. * @dev Emits an {IERC173-OwnershipTransferred(address,address)} event. */ constructor(address owner_) { _owner = owner_; emit OwnershipTransferred(address(0), owner_); } /** * Gets the address of the current contract owner. */ function owner() public view virtual override returns (address) { return _owner; } /** * See {IERC173-transferOwnership(address)} * @dev Reverts if the sender is not the current contract owner. * @param newOwner the address of the new owner. Use the zero address to renounce the ownership. */ function transferOwnership(address newOwner) public virtual override { _requireOwnership(_msgSender()); _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } /** * @dev Reverts if `account` is not the contract owner. * @param account the account to test. */ function _requireOwnership(address account) internal virtual { require(account == this.owner(), "Ownable: not the owner"); } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/utils/types/AddressIsContract.sol@v1.1.2 // Partially derived from OpenZeppelin: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/406c83649bd6169fc1b578e08506d78f0873b276/contracts/utils/Address.sol pragma solidity >=0.7.6 <0.8.0; /** * @dev Upgrades the address type to check if it is a contract. */ library AddressIsContract { /** * @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; } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/utils/ERC20Wrapper.sol@v1.1.2 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC20Wrapper * Wraps ERC20 functions to support non-standard implementations which do not return a bool value. * Calls to the wrapped functions revert only if they throw or if they return false. */ library ERC20Wrapper { using AddressIsContract for address; function wrappedTransfer( IWrappedERC20 token, address to, uint256 value ) internal { _callWithOptionalReturnData(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function wrappedTransferFrom( IWrappedERC20 token, address from, address to, uint256 value ) internal { _callWithOptionalReturnData(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function wrappedApprove( IWrappedERC20 token, address spender, uint256 value ) internal { _callWithOptionalReturnData(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function _callWithOptionalReturnData(IWrappedERC20 token, bytes memory callData) internal { address target = address(token); require(target.isContract(), "ERC20Wrapper: non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = target.call(callData); if (success) { if (data.length != 0) { require(abi.decode(data, (bool)), "ERC20Wrapper: operation failed"); } } else { // revert using a standard revert message if (data.length == 0) { revert("ERC20Wrapper: operation failed"); } // revert using the revert message coming from the call assembly { let size := mload(data) revert(add(32, data), size) } } } } interface IWrappedERC20 { function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function approve(address spender, uint256 value) external returns (bool); } // File @animoca/ethereum-contracts-core-1.1.2/contracts/utils/Recoverable.sol@v1.1.2 pragma solidity >=0.7.6 <0.8.0; abstract contract Recoverable is ManagedIdentity, Ownable { using ERC20Wrapper for IWrappedERC20; /** * Extract ERC20 tokens which were accidentally sent to the contract to a list of accounts. * Warning: this function should be overriden for contracts which are supposed to hold ERC20 tokens * so that the extraction is limited to only amounts sent accidentally. * @dev Reverts if the sender is not the contract owner. * @dev Reverts if `accounts`, `tokens` and `amounts` do not have the same length. * @dev Reverts if one of `tokens` is does not implement the ERC20 transfer function. * @dev Reverts if one of the ERC20 transfers fail for any reason. * @param accounts the list of accounts to transfer the tokens to. * @param tokens the list of ERC20 token addresses. * @param amounts the list of token amounts to transfer. */ function recoverERC20s( address[] calldata accounts, address[] calldata tokens, uint256[] calldata amounts ) external virtual { _requireOwnership(_msgSender()); uint256 length = accounts.length; require(length == tokens.length && length == amounts.length, "Recov: inconsistent arrays"); for (uint256 i = 0; i != length; ++i) { IWrappedERC20(tokens[i]).wrappedTransfer(accounts[i], amounts[i]); } } /** * Extract ERC721 tokens which were accidentally sent to the contract to a list of accounts. * Warning: this function should be overriden for contracts which are supposed to hold ERC721 tokens * so that the extraction is limited to only tokens sent accidentally. * @dev Reverts if the sender is not the contract owner. * @dev Reverts if `accounts`, `contracts` and `amounts` do not have the same length. * @dev Reverts if one of `contracts` is does not implement the ERC721 transferFrom function. * @dev Reverts if one of the ERC721 transfers fail for any reason. * @param accounts the list of accounts to transfer the tokens to. * @param contracts the list of ERC721 contract addresses. * @param tokenIds the list of token ids to transfer. */ function recoverERC721s( address[] calldata accounts, address[] calldata contracts, uint256[] calldata tokenIds ) external virtual { _requireOwnership(_msgSender()); uint256 length = accounts.length; require(length == contracts.length && length == tokenIds.length, "Recov: inconsistent arrays"); for (uint256 i = 0; i != length; ++i) { IRecoverableERC721(contracts[i]).transferFrom(address(this), accounts[i], tokenIds[i]); } } } interface IRecoverableERC721 { /// See {IERC721-transferFrom(address,address,uint256)} function transferFrom( address from, address to, uint256 tokenId ) external; } // File ethereum-universal-forwarder-1.0.0/src/solc_0.7/ERC2771/UsingAppendedCallData.sol@v1.0.0 pragma solidity ^0.7.0; abstract contract UsingAppendedCallData { function _lastAppendedDataAsSender() internal pure virtual returns (address payable sender) { // Copied from openzeppelin : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/9d5f77db9da0604ce0b25148898a94ae2c20d70f/contracts/metatx/ERC2771Context.sol1 // The assembly code is more direct than the Solidity version using `abi.decode`. // solhint-disable-next-line no-inline-assembly assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } function _msgDataAssuming20BytesAppendedData() internal pure virtual returns (bytes calldata) { return msg.data[:msg.data.length - 20]; } } // File ethereum-universal-forwarder-1.0.0/src/solc_0.7/ERC2771/IERC2771.sol@v1.0.0 pragma solidity ^0.7.0; interface IERC2771 { function isTrustedForwarder(address forwarder) external view returns (bool); } // File ethereum-universal-forwarder-1.0.0/src/solc_0.7/ERC2771/IForwarderRegistry.sol@v1.0.0 pragma solidity ^0.7.0; interface IForwarderRegistry { function isForwarderFor(address, address) external view returns (bool); } // File ethereum-universal-forwarder-1.0.0/src/solc_0.7/ERC2771/UsingUniversalForwarding.sol@v1.0.0 pragma solidity ^0.7.0; abstract contract UsingUniversalForwarding is UsingAppendedCallData, IERC2771 { IForwarderRegistry internal immutable _forwarderRegistry; address internal immutable _universalForwarder; constructor(IForwarderRegistry forwarderRegistry, address universalForwarder) { _universalForwarder = universalForwarder; _forwarderRegistry = forwarderRegistry; } function isTrustedForwarder(address forwarder) external view virtual override returns (bool) { return forwarder == _universalForwarder || forwarder == address(_forwarderRegistry); } function _msgSender() internal view virtual returns (address payable) { address payable msgSender = msg.sender; address payable sender = _lastAppendedDataAsSender(); if (msgSender == address(_forwarderRegistry) || msgSender == _universalForwarder) { // if forwarder use appended data return sender; } // if msg.sender is neither the registry nor the universal forwarder, // we have to check the last 20bytes of the call data intepreted as an address // and check if the msg.sender was registered as forewarder for that address // we check tx.origin to save gas in case where msg.sender == tx.origin // solhint-disable-next-line avoid-tx-origin if (msgSender != tx.origin && _forwarderRegistry.isForwarderFor(sender, msgSender)) { return sender; } return msgSender; } function _msgData() internal view virtual returns (bytes calldata) { address payable msgSender = msg.sender; if (msgSender == address(_forwarderRegistry) || msgSender == _universalForwarder) { // if forwarder use appended data return _msgDataAssuming20BytesAppendedData(); } // we check tx.origin to save gas in case where msg.sender == tx.origin // solhint-disable-next-line avoid-tx-origin if (msgSender != tx.origin && _forwarderRegistry.isForwarderFor(_lastAppendedDataAsSender(), msgSender)) { return _msgDataAssuming20BytesAppendedData(); } return msg.data; } } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155InventoryBurnable.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Inventory. optional extension: Burnable. * @dev See https://eips.ethereum.org/EIPS/eip-1155 * @dev Note: The ERC-165 identifier for this interface is 0x921ed8d1. */ interface IERC1155InventoryBurnable { /** * Burns some token. * @dev Reverts if the sender is not approved. * @dev Reverts if `id` does not represent a token. * @dev Reverts if `id` represents a Fungible Token and `value` is 0. * @dev Reverts if `id` represents a Fungible Token and `value` is higher than `from`'s balance. * @dev Reverts if `id` represents a Non-Fungible Token and `value` is not 1. * @dev Reverts if `id` represents a Non-Fungible Token which is not owned by `from`. * @dev Emits an {IERC1155-TransferSingle} event. * @param from Address of the current token owner. * @param id Identifier of the token to burn. * @param value Amount of token to burn. */ function burnFrom( address from, uint256 id, uint256 value ) external; /** * Burns multiple tokens. * @dev Reverts if `ids` and `values` have different lengths. * @dev Reverts if the sender is not approved. * @dev Reverts if one of `ids` does not represent a token. * @dev Reverts if one of `ids` represents a Fungible Token and `value` is 0. * @dev Reverts if one of `ids` represents a Fungible Token and `value` is higher than `from`'s balance. * @dev Reverts if one of `ids` represents a Non-Fungible Token and `value` is not 1. * @dev Reverts if one of `ids` represents a Non-Fungible Token which is not owned by `from`. * @dev Emits an {IERC1155-TransferBatch} event. * @param from Address of the current tokens owner. * @param ids Identifiers of the tokens to burn. * @param values Amounts of tokens to burn. */ function batchBurnFrom( address from, uint256[] calldata ids, uint256[] calldata values ) external; } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/ERC1155InventoryIdentifiersLib.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155InventoryIdentifiersLib, a library to introspect inventory identifiers. * @dev With N=32, representing the Non-Fungible Collection mask length, identifiers are represented as follow: * (a) a Fungible Token: * - most significant bit == 0 * (b) a Non-Fungible Collection: * - most significant bit == 1 * - (256-N) least significant bits == 0 * (c) a Non-Fungible Token: * - most significant bit == 1 * - (256-N) least significant bits != 0 */ library ERC1155InventoryIdentifiersLib { // Non-Fungible bit. If an id has this bit set, it is a Non-Fungible (either Collection or Token) uint256 internal constant _NF_BIT = 1 << 255; // Mask for Non-Fungible Collection (including the nf bit) uint256 internal constant _NF_COLLECTION_MASK = uint256(type(uint32).max) << 224; uint256 internal constant _NF_TOKEN_MASK = ~_NF_COLLECTION_MASK; function isFungibleToken(uint256 id) internal pure returns (bool) { return id & _NF_BIT == 0; } function isNonFungibleToken(uint256 id) internal pure returns (bool) { return id & _NF_BIT != 0 && id & _NF_TOKEN_MASK != 0; } function getNonFungibleCollection(uint256 nftId) internal pure returns (uint256) { return nftId & _NF_COLLECTION_MASK; } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/introspection/IERC165.sol@v1.1.2 pragma solidity >=0.7.6 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165. */ 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 @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Multi Token Standard, basic interface. * @dev See https://eips.ethereum.org/EIPS/eip-1155 * @dev Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface IERC1155 { event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _value, uint256 indexed _id); /** * Safely transfers some token. * @dev Reverts if `to` is the zero address. * @dev Reverts if the sender is not approved. * @dev Reverts if `from` has an insufficient balance. * @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused. * @dev Emits a `TransferSingle` event. * @param from Current token owner. * @param to Address of the new token owner. * @param id Identifier of the token to transfer. * @param value Amount of token to transfer. * @param data Optional data to send along to a receiver contract. */ function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external; /** * Safely transfers a batch of tokens. * @dev Reverts if `to` is the zero address. * @dev Reverts if `ids` and `values` have different lengths. * @dev Reverts if the sender is not approved. * @dev Reverts if `from` has an insufficient balance for any of `ids`. * @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused. * @dev Emits a `TransferBatch` event. * @param from Current token owner. * @param to Address of the new token owner. * @param ids Identifiers of the tokens to transfer. * @param values Amounts of tokens to transfer. * @param data Optional data to send along to a receiver contract. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; /** * Retrieves the balance of `id` owned by account `owner`. * @param owner The account to retrieve the balance of. * @param id The identifier to retrieve the balance of. * @return The balance of `id` owned by account `owner`. */ function balanceOf(address owner, uint256 id) external view returns (uint256); /** * Retrieves the balances of `ids` owned by accounts `owners`. For each pair: * @dev Reverts if `owners` and `ids` have different lengths. * @param owners The addresses of the token holders * @param ids The identifiers to retrieve the balance of. * @return The balances of `ids` owned by accounts `owners`. */ function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory); /** * Enables or disables an operator's approval. * @dev Emits an `ApprovalForAll` event. * @param operator Address of the operator. * @param approved True to approve the operator, false to revoke an approval. */ function setApprovalForAll(address operator, bool approved) external; /** * Retrieves the approval status of an operator for a given owner. * @param owner Address of the authorisation giver. * @param operator Address of the operator. * @return True if the operator is approved, false if not. */ function isApprovedForAll(address owner, address operator) external view returns (bool); } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155InventoryFunctions.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Multi Token Standard, optional extension: Inventory. * Interface for Fungible/Non-Fungible Tokens management on an ERC1155 contract. * @dev See https://eips.ethereum.org/EIPS/eip-xxxx * @dev Note: The ERC-165 identifier for this interface is 0x09ce5c46. */ interface IERC1155InventoryFunctions { function ownerOf(uint256 nftId) external view returns (address); function isFungible(uint256 id) external view returns (bool); function collectionOf(uint256 nftId) external view returns (uint256); } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155Inventory.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Multi Token Standard, optional extension: Inventory. * Interface for Fungible/Non-Fungible Tokens management on an ERC1155 contract. * * This interface rationalizes the co-existence of Fungible and Non-Fungible Tokens * within the same contract. As several kinds of Fungible Tokens can be managed under * the Multi-Token standard, we consider that Non-Fungible Tokens can be classified * under their own specific type. We introduce the concept of Non-Fungible Collection * and consider the usage of 3 types of identifiers: * (a) Fungible Token identifiers, each representing a set of Fungible Tokens, * (b) Non-Fungible Collection identifiers, each representing a set of Non-Fungible Tokens (this is not a token), * (c) Non-Fungible Token identifiers. * * Identifiers nature * | Type | isFungible | isCollection | isToken | * | Fungible Token | true | true | true | * | Non-Fungible Collection | false | true | false | * | Non-Fungible Token | false | false | true | * * Identifiers compatibilities * | Type | transfer | balance | supply | owner | * | Fungible Token | OK | OK | OK | NOK | * | Non-Fungible Collection | NOK | OK | OK | NOK | * | Non-Fungible Token | OK | 0 or 1 | 0 or 1 | OK | * * @dev See https://eips.ethereum.org/EIPS/eip-xxxx * @dev Note: The ERC-165 identifier for this interface is 0x09ce5c46. */ interface IERC1155Inventory is IERC1155, IERC1155InventoryFunctions { //================================================== ERC1155Inventory ===================================================// /** * Optional event emitted when a collection (Fungible Token or Non-Fungible Collection) is created. * This event can be used by a client application to determine which identifiers are meaningful * to track through the functions `balanceOf`, `balanceOfBatch` and `totalSupply`. * @dev This event MUST NOT be emitted twice for the same `collectionId`. */ event CollectionCreated(uint256 indexed collectionId, bool indexed fungible); /** * Retrieves the owner of a Non-Fungible Token (ERC721-compatible). * @dev Reverts if `nftId` is owned by the zero address. * @param nftId Identifier of the token to query. * @return Address of the current owner of the token. */ function ownerOf(uint256 nftId) external view override returns (address); /** * Introspects whether or not `id` represents a Fungible Token. * This function MUST return true even for a Fungible Token which is not-yet created. * @param id The identifier to query. * @return bool True if `id` represents aFungible Token, false otherwise. */ function isFungible(uint256 id) external view override returns (bool); /** * Introspects the Non-Fungible Collection to which `nftId` belongs. * @dev This function MUST return a value representing a Non-Fungible Collection. * @dev This function MUST return a value for a non-existing token, and SHOULD NOT be used to check the existence of a Non-Fungible Token. * @dev Reverts if `nftId` does not represent a Non-Fungible Token. * @param nftId The token identifier to query the collection of. * @return The Non-Fungible Collection identifier to which `nftId` belongs. */ function collectionOf(uint256 nftId) external view override returns (uint256); //======================================================= ERC1155 =======================================================// /** * Retrieves the balance of `id` owned by account `owner`. * @param owner The account to retrieve the balance of. * @param id The identifier to retrieve the balance of. * @return * If `id` represents a collection (Fungible Token or Non-Fungible Collection), the balance for this collection. * If `id` represents a Non-Fungible Token, 1 if the token is owned by `owner`, else 0. */ function balanceOf(address owner, uint256 id) external view override returns (uint256); /** * Retrieves the balances of `ids` owned by accounts `owners`. * @dev Reverts if `owners` and `ids` have different lengths. * @param owners The accounts to retrieve the balances of. * @param ids The identifiers to retrieve the balances of. * @return An array of elements such as for each pair `id`/`owner`: * If `id` represents a collection (Fungible Token or Non-Fungible Collection), the balance for this collection. * If `id` represents a Non-Fungible Token, 1 if the token is owned by `owner`, else 0. */ function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view override returns (uint256[] memory); /** * Safely transfers some token. * @dev Reverts if `to` is the zero address. * @dev Reverts if the sender is not approved. * @dev Reverts if `id` does not represent a token. * @dev Reverts if `id` represents a Non-Fungible Token and `value` is not 1. * @dev Reverts if `id` represents a Non-Fungible Token and is not owned by `from`. * @dev Reverts if `id` represents a Fungible Token and `value` is 0. * @dev Reverts if `id` represents a Fungible Token and `from` has an insufficient balance. * @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused. * @dev Emits an {IERC1155-TransferSingle} event. * @param from Current token owner. * @param to Address of the new token owner. * @param id Identifier of the token to transfer. * @param value Amount of token to transfer. * @param data Optional data to pass to the receiver contract. */ function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external override; /** * @notice this documentation overrides its {IERC1155-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}. * Safely transfers a batch of tokens. * @dev Reverts if `to` is the zero address. * @dev Reverts if the sender is not approved. * @dev Reverts if one of `ids` does not represent a token. * @dev Reverts if one of `ids` represents a Non-Fungible Token and `value` is not 1. * @dev Reverts if one of `ids` represents a Non-Fungible Token and is not owned by `from`. * @dev Reverts if one of `ids` represents a Fungible Token and `value` is 0. * @dev Reverts if one of `ids` represents a Fungible Token and `from` has an insufficient balance. * @dev Reverts if one of `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused. * @dev Emits an {IERC1155-TransferBatch} event. * @param from Current tokens owner. * @param to Address of the new tokens owner. * @param ids Identifiers of the tokens to transfer. * @param values Amounts of tokens to transfer. * @param data Optional data to pass to the receiver contract. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override; } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155MetadataURI.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Multi Token Standard, optional extension: Metadata URI. * @dev See https://eips.ethereum.org/EIPS/eip-1155 * @dev Note: The ERC-165 identifier for this interface is 0x0e89341c. */ interface IERC1155MetadataURI { /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * @dev The URI MUST point to a JSON file that conforms to the "ERC1155 Metadata URI JSON Schema". * @dev The uri function SHOULD be used to retrieve values if no event was emitted. * @dev The uri function MUST return the same value as the latest event for an _id if it was emitted. * @dev The uri function MUST NOT be used to check for the existence of a token as it is possible for * an implementation to return a valid string even if the token does not exist. * @return URI string */ function uri(uint256 id) external view returns (string memory); } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155InventoryTotalSupply.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Inventory, optional extension: Total Supply. * @dev See https://eips.ethereum.org/EIPS/eip-xxxx * @dev Note: The ERC-165 identifier for this interface is 0xbd85b039. */ interface IERC1155InventoryTotalSupply { /** * Retrieves the total supply of `id`. * @param id The identifier for which to retrieve the supply of. * @return * If `id` represents a collection (Fungible Token or Non-Fungible Collection), the total supply for this collection. * If `id` represents a Non-Fungible Token, 1 if the token exists, else 0. */ function totalSupply(uint256 id) external view returns (uint256); } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155TokenReceiver.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Multi Token Standard, Tokens Receiver. * Interface for any contract that wants to support transfers from ERC1155 asset contracts. * @dev See https://eips.ethereum.org/EIPS/eip-1155 * @dev Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type. * An ERC1155 contract MUST call this function on a recipient contract, at the end of a `safeTransferFrom` after the balance update. * This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61) to accept the transfer. * Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. * @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 `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types. * An ERC1155 contract MUST call this function on a recipient contract, at the end of a `safeBatchTransferFrom` after the balance updates. * This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81) if to accept the transfer(s). * Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. * @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)"))` */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/ERC1155InventoryBase.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Inventory Base. * @dev The functions `safeTransferFrom(address,address,uint256,uint256,bytes)` * and `safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)` need to be implemented by a child contract. * @dev The function `uri(uint256)` needs to be implemented by a child contract, for example with the help of `BaseMetadataURI`. */ abstract contract ERC1155InventoryBase is ManagedIdentity, IERC165, IERC1155Inventory, IERC1155MetadataURI, IERC1155InventoryTotalSupply { using ERC1155InventoryIdentifiersLib for uint256; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) bytes4 internal constant _ERC1155_RECEIVED = 0xf23a6e61; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) bytes4 internal constant _ERC1155_BATCH_RECEIVED = 0xbc197c81; // Burnt Non-Fungible Token owner's magic value uint256 internal constant _BURNT_NFT_OWNER = 0xdead000000000000000000000000000000000000000000000000000000000000; /* owner => operator => approved */ mapping(address => mapping(address => bool)) internal _operators; /* collection ID => owner => balance */ mapping(uint256 => mapping(address => uint256)) internal _balances; /* collection ID => supply */ mapping(uint256 => uint256) internal _supplies; /* NFT ID => owner */ mapping(uint256 => uint256) internal _owners; /* collection ID => creator */ mapping(uint256 => address) internal _creators; //======================================================= ERC165 ========================================================// /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || interfaceId == type(IERC1155InventoryFunctions).interfaceId || interfaceId == type(IERC1155InventoryTotalSupply).interfaceId; } //======================================================= ERC1155 =======================================================// /// @inheritdoc IERC1155Inventory function balanceOf(address owner, uint256 id) public view virtual override returns (uint256) { require(owner != address(0), "Inventory: zero address"); if (id.isNonFungibleToken()) { return address(uint160(_owners[id])) == owner ? 1 : 0; } return _balances[id][owner]; } /// @inheritdoc IERC1155Inventory function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view virtual override returns (uint256[] memory) { require(owners.length == ids.length, "Inventory: inconsistent arrays"); uint256[] memory balances = new uint256[](owners.length); for (uint256 i = 0; i != owners.length; ++i) { balances[i] = balanceOf(owners[i], ids[i]); } return balances; } /// @inheritdoc IERC1155 function setApprovalForAll(address operator, bool approved) public virtual override { address sender = _msgSender(); require(operator != sender, "Inventory: self-approval"); _operators[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /// @inheritdoc IERC1155 function isApprovedForAll(address tokenOwner, address operator) public view virtual override returns (bool) { return _operators[tokenOwner][operator]; } //================================================== ERC1155Inventory ===================================================// /// @inheritdoc IERC1155Inventory function isFungible(uint256 id) external pure virtual override returns (bool) { return id.isFungibleToken(); } /// @inheritdoc IERC1155Inventory function collectionOf(uint256 nftId) external pure virtual override returns (uint256) { require(nftId.isNonFungibleToken(), "Inventory: not an NFT"); return nftId.getNonFungibleCollection(); } /// @inheritdoc IERC1155Inventory function ownerOf(uint256 nftId) public view virtual override returns (address) { address owner = address(uint160(_owners[nftId])); require(owner != address(0), "Inventory: non-existing NFT"); return owner; } //============================================= ERC1155InventoryTotalSupply =============================================// /// @inheritdoc IERC1155InventoryTotalSupply function totalSupply(uint256 id) external view virtual override returns (uint256) { if (id.isNonFungibleToken()) { return address(uint160(_owners[id])) == address(0) ? 0 : 1; } else { return _supplies[id]; } } //============================================ High-level Internal Functions ============================================// /** * Creates a collection (optional). * @dev Reverts if `collectionId` does not represent a collection. * @dev Reverts if `collectionId` has already been created. * @dev Emits a {IERC1155Inventory-CollectionCreated} event. * @param collectionId Identifier of the collection. */ function _createCollection(uint256 collectionId) internal virtual { require(!collectionId.isNonFungibleToken(), "Inventory: not a collection"); require(_creators[collectionId] == address(0), "Inventory: existing collection"); _creators[collectionId] = _msgSender(); emit CollectionCreated(collectionId, collectionId.isFungibleToken()); } function _creator(uint256 collectionId) internal view virtual returns (address) { require(!collectionId.isNonFungibleToken(), "Inventory: not a collection"); return _creators[collectionId]; } //============================================== Helper Internal Functions ==============================================// /** * Returns whether `sender` is authorised to make a transfer on behalf of `from`. * @param from The address to check operatibility upon. * @param sender The sender address. * @return True if sender is `from` or an operator for `from`, false otherwise. */ function _isOperatable(address from, address sender) internal view virtual returns (bool) { return (from == sender) || _operators[from][sender]; } /** * Calls {IERC1155TokenReceiver-onERC1155Received} on a target contract. * @dev Reverts if `to` is not a contract. * @dev Reverts if the call to the target fails or is refused. * @param from Previous token owner. * @param to New token owner. * @param id Identifier of the token transferred. * @param value Amount of token transferred. * @param data Optional data to send along with the receiver contract call. */ function _callOnERC1155Received( address from, address to, uint256 id, uint256 value, bytes memory data ) internal { require(IERC1155TokenReceiver(to).onERC1155Received(_msgSender(), from, id, value, data) == _ERC1155_RECEIVED, "Inventory: transfer refused"); } /** * Calls {IERC1155TokenReceiver-onERC1155batchReceived} on a target contract. * @dev Reverts if `to` is not a contract. * @dev Reverts if the call to the target fails or is refused. * @param from Previous tokens owner. * @param to New tokens owner. * @param ids Identifiers of the tokens to transfer. * @param values Amounts of tokens to transfer. * @param data Optional data to send along with the receiver contract call. */ function _callOnERC1155BatchReceived( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { require( IERC1155TokenReceiver(to).onERC1155BatchReceived(_msgSender(), from, ids, values, data) == _ERC1155_BATCH_RECEIVED, "Inventory: transfer refused" ); } } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/ERC1155Inventory.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; // solhint-disable-next-line max-line-length /** * @title ERC1155Inventory, a contract which manages up to multiple Collections of Fungible and Non-Fungible Tokens. * @dev The function `uri(uint256)` needs to be implemented by a child contract, for example with the help of `BaseMetadataURI`. */ abstract contract ERC1155Inventory is ERC1155InventoryBase { using AddressIsContract for address; using ERC1155InventoryIdentifiersLib for uint256; //======================================================= ERC1155 =======================================================// /// @inheritdoc IERC1155Inventory function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes memory data ) public virtual override { address sender = _msgSender(); require(to != address(0), "Inventory: transfer to zero"); require(_isOperatable(from, sender), "Inventory: non-approved sender"); if (id.isFungibleToken()) { _transferFungible(from, to, id, value); } else if (id.isNonFungibleToken()) { _transferNFT(from, to, id, value, false); } else { revert("Inventory: not a token id"); } emit TransferSingle(sender, from, to, id, value); if (to.isContract()) { _callOnERC1155Received(from, to, id, value, data); } } /// @inheritdoc IERC1155Inventory function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) public virtual override { // internal function to avoid stack too deep error _safeBatchTransferFrom(from, to, ids, values, data); } //============================================ High-level Internal Functions ============================================// function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal { require(to != address(0), "Inventory: transfer to zero"); uint256 length = ids.length; require(length == values.length, "Inventory: inconsistent arrays"); address sender = _msgSender(); require(_isOperatable(from, sender), "Inventory: non-approved sender"); uint256 nfCollectionId; uint256 nfCollectionCount; for (uint256 i; i != length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (id.isFungibleToken()) { _transferFungible(from, to, id, value); } else if (id.isNonFungibleToken()) { _transferNFT(from, to, id, value, true); uint256 nextCollectionId = id.getNonFungibleCollection(); if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { if (nextCollectionId != nfCollectionId) { _transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount); nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { ++nfCollectionCount; } } } else { revert("Inventory: not a token id"); } } if (nfCollectionId != 0) { _transferNFTUpdateCollection(from, to, nfCollectionId, nfCollectionCount); } emit TransferBatch(sender, from, to, ids, values); if (to.isContract()) { _callOnERC1155BatchReceived(from, to, ids, values, data); } } function _safeMint( address to, uint256 id, uint256 value, bytes memory data ) internal { require(to != address(0), "Inventory: mint to zero"); if (id.isFungibleToken()) { _mintFungible(to, id, value); } else if (id.isNonFungibleToken()) { _mintNFT(to, id, value, false); } else { revert("Inventory: not a token id"); } emit TransferSingle(_msgSender(), address(0), to, id, value); if (to.isContract()) { _callOnERC1155Received(address(0), to, id, value, data); } } function _safeBatchMint( address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) internal virtual { require(to != address(0), "Inventory: mint to zero"); uint256 length = ids.length; require(length == values.length, "Inventory: inconsistent arrays"); uint256 nfCollectionId; uint256 nfCollectionCount; for (uint256 i; i != length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (id.isFungibleToken()) { _mintFungible(to, id, value); } else if (id.isNonFungibleToken()) { _mintNFT(to, id, value, true); uint256 nextCollectionId = id.getNonFungibleCollection(); if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { if (nextCollectionId != nfCollectionId) { _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { ++nfCollectionCount; } } } else { revert("Inventory: not a token id"); } } if (nfCollectionId != 0) { _balances[nfCollectionId][to] += nfCollectionCount; _supplies[nfCollectionId] += nfCollectionCount; } emit TransferBatch(_msgSender(), address(0), to, ids, values); if (to.isContract()) { _callOnERC1155BatchReceived(address(0), to, ids, values, data); } } //============================================== Helper Internal Functions ==============================================// function _mintFungible( address to, uint256 id, uint256 value ) internal { require(value != 0, "Inventory: zero value"); uint256 supply = _supplies[id]; uint256 newSupply = supply + value; require(newSupply > supply, "Inventory: supply overflow"); _supplies[id] = newSupply; // cannot overflow as any balance is bounded up by the supply which cannot overflow _balances[id][to] += value; } function _mintNFT( address to, uint256 id, uint256 value, bool isBatch ) internal { require(value == 1, "Inventory: wrong NFT value"); require(_owners[id] == 0, "Inventory: existing/burnt NFT"); _owners[id] = uint256(uint160(to)); if (!isBatch) { uint256 collectionId = id.getNonFungibleCollection(); // it is virtually impossible that a Non-Fungible Collection supply // overflows due to the cost of minting individual tokens ++_supplies[collectionId]; // cannot overflow as supply cannot overflow ++_balances[collectionId][to]; } } function _transferFungible( address from, address to, uint256 id, uint256 value ) internal { require(value != 0, "Inventory: zero value"); uint256 balance = _balances[id][from]; require(balance >= value, "Inventory: not enough balance"); if (from != to) { _balances[id][from] = balance - value; // cannot overflow as supply cannot overflow _balances[id][to] += value; } } function _transferNFT( address from, address to, uint256 id, uint256 value, bool isBatch ) internal { require(value == 1, "Inventory: wrong NFT value"); require(from == address(uint160(_owners[id])), "Inventory: non-owned NFT"); _owners[id] = uint256(uint160(to)); if (!isBatch) { uint256 collectionId = id.getNonFungibleCollection(); // cannot underflow as balance is verified through ownership _balances[collectionId][from] -= 1; // cannot overflow as supply cannot overflow _balances[collectionId][to] += 1; } } function _transferNFTUpdateCollection( address from, address to, uint256 collectionId, uint256 amount ) internal virtual { if (from != to) { // cannot underflow as balance is verified through ownership _balances[collectionId][from] -= amount; // cannot overflow as supply cannot overflow _balances[collectionId][to] += amount; } } } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/ERC1155InventoryBurnable.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155Inventory, burnable version. * @dev The function `uri(uint256)` needs to be implemented by a child contract, for example with the help of `BaseMetadataURI`. */ abstract contract ERC1155InventoryBurnable is IERC1155InventoryBurnable, ERC1155Inventory { using ERC1155InventoryIdentifiersLib for uint256; //======================================================= ERC165 ========================================================// /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC1155InventoryBurnable).interfaceId || super.supportsInterface(interfaceId); } //============================================== ERC1155InventoryBurnable ===============================================// /// @inheritdoc IERC1155InventoryBurnable function burnFrom( address from, uint256 id, uint256 value ) public virtual override { address sender = _msgSender(); require(_isOperatable(from, sender), "Inventory: non-approved sender"); if (id.isFungibleToken()) { _burnFungible(from, id, value); } else if (id.isNonFungibleToken()) { _burnNFT(from, id, value, false); } else { revert("Inventory: not a token id"); } emit TransferSingle(sender, from, address(0), id, value); } /// @inheritdoc IERC1155InventoryBurnable function batchBurnFrom( address from, uint256[] memory ids, uint256[] memory values ) public virtual override { uint256 length = ids.length; require(length == values.length, "Inventory: inconsistent arrays"); address sender = _msgSender(); require(_isOperatable(from, sender), "Inventory: non-approved sender"); uint256 nfCollectionId; uint256 nfCollectionCount; for (uint256 i; i != length; ++i) { uint256 id = ids[i]; uint256 value = values[i]; if (id.isFungibleToken()) { _burnFungible(from, id, value); } else if (id.isNonFungibleToken()) { _burnNFT(from, id, value, true); uint256 nextCollectionId = id.getNonFungibleCollection(); if (nfCollectionId == 0) { nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { if (nextCollectionId != nfCollectionId) { _balances[nfCollectionId][from] -= nfCollectionCount; _supplies[nfCollectionId] -= nfCollectionCount; nfCollectionId = nextCollectionId; nfCollectionCount = 1; } else { ++nfCollectionCount; } } } else { revert("Inventory: not a token id"); } } if (nfCollectionId != 0) { _balances[nfCollectionId][from] -= nfCollectionCount; _supplies[nfCollectionId] -= nfCollectionCount; } emit TransferBatch(sender, from, address(0), ids, values); } //============================================== Helper Internal Functions ==============================================// function _burnFungible( address from, uint256 id, uint256 value ) internal { require(value != 0, "Inventory: zero value"); uint256 balance = _balances[id][from]; require(balance >= value, "Inventory: not enough balance"); _balances[id][from] = balance - value; // Cannot underflow _supplies[id] -= value; } function _burnNFT( address from, uint256 id, uint256 value, bool isBatch ) internal { require(value == 1, "Inventory: wrong NFT value"); require(from == address(uint160(_owners[id])), "Inventory: non-owned NFT"); _owners[id] = _BURNT_NFT_OWNER; if (!isBatch) { uint256 collectionId = id.getNonFungibleCollection(); // cannot underflow as balance is confirmed through ownership --_balances[collectionId][from]; // Cannot underflow --_supplies[collectionId]; } } } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155InventoryMintable.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Inventory, optional extension: Mintable. * @dev See https://eips.ethereum.org/EIPS/eip-1155 */ interface IERC1155InventoryMintable { /** * Safely mints some token. * @dev Reverts if `to` is the zero address. * @dev Reverts if `id` is not a token. * @dev Reverts if `id` represents a Non-Fungible Token and `value` is not 1. * @dev Reverts if `id` represents a Non-Fungible Token which has already been minted. * @dev Reverts if `id` represents a Fungible Token and `value` is 0. * @dev Reverts if `id` represents a Fungible Token and there is an overflow of supply. * @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155Received} fails or is refused. * @dev Emits an {IERC1155-TransferSingle} event. * @param to Address of the new token owner. * @param id Identifier of the token to mint. * @param value Amount of token to mint. * @param data Optional data to send along to a receiver contract. */ function safeMint( address to, uint256 id, uint256 value, bytes calldata data ) external; /** * Safely mints a batch of tokens. * @dev Reverts if `ids` and `values` have different lengths. * @dev Reverts if `to` is the zero address. * @dev Reverts if one of `ids` is not a token. * @dev Reverts if one of `ids` represents a Non-Fungible Token and its paired value is not 1. * @dev Reverts if one of `ids` represents a Non-Fungible Token which has already been minted. * @dev Reverts if one of `ids` represents a Fungible Token and its paired value is 0. * @dev Reverts if one of `ids` represents a Fungible Token and there is an overflow of supply. * @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused. * @dev Emits an {IERC1155-TransferBatch} event. * @param to Address of the new tokens owner. * @param ids Identifiers of the tokens to mint. * @param values Amounts of tokens to mint. * @param data Optional data to send along to a receiver contract. */ function safeBatchMint( address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/token/ERC1155/IERC1155InventoryCreator.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; /** * @title ERC1155 Inventory, optional extension: Creator. * @dev See https://eips.ethereum.org/EIPS/eip-1155 * @dev Note: The ERC-165 identifier for this interface is 0x510b5158. */ interface IERC1155InventoryCreator { /** * Returns the creator of a collection, or the zero address if the collection has not been created. * @dev Reverts if `collectionId` does not represent a collection. * @param collectionId Identifier of the collection. * @return The creator of a collection, or the zero address if the collection has not been created. */ function creator(uint256 collectionId) external view returns (address); } // File @animoca/ethereum-contracts-core-1.1.2/contracts/utils/types/UInt256ToDecimalString.sol@v1.1.2 // Partially derived from OpenZeppelin: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/8b10cb38d8fedf34f2d89b0ed604f2dceb76d6a9/contracts/utils/Strings.sol pragma solidity >=0.7.6 <0.8.0; library UInt256ToDecimalString { function toDecimalString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } // File @animoca/ethereum-contracts-assets-2.0.0/contracts/metadata/BaseMetadataURI.sol@v2.0.0 pragma solidity >=0.7.6 <0.8.0; abstract contract BaseMetadataURI is ManagedIdentity, Ownable { using UInt256ToDecimalString for uint256; event BaseMetadataURISet(string baseMetadataURI); string public baseMetadataURI; function setBaseMetadataURI(string calldata baseMetadataURI_) external { _requireOwnership(_msgSender()); baseMetadataURI = baseMetadataURI_; emit BaseMetadataURISet(baseMetadataURI_); } function _uri(uint256 id) internal view virtual returns (string memory) { return string(abi.encodePacked(baseMetadataURI, id.toDecimalString())); } } // File @animoca/ethereum-contracts-core-1.1.2/contracts/access/MinterRole.sol@v1.1.2 pragma solidity >=0.7.6 <0.8.0; /** * Contract which allows derived contracts access control over token minting operations. */ contract MinterRole is Ownable { event MinterAdded(address indexed account); event MinterRemoved(address indexed account); mapping(address => bool) public isMinter; /** * Constructor. */ constructor(address owner_) Ownable(owner_) { _addMinter(owner_); } /** * Grants the minter role to a non-minter. * @dev reverts if the sender is not the contract owner. * @param account The account to grant the minter role to. */ function addMinter(address account) public { _requireOwnership(_msgSender()); _addMinter(account); } /** * Renounces the granted minter role. * @dev reverts if the sender is not a minter. */ function renounceMinter() public { address account = _msgSender(); _requireMinter(account); isMinter[account] = false; emit MinterRemoved(account); } function _requireMinter(address account) internal view { require(isMinter[account], "MinterRole: not a Minter"); } function _addMinter(address account) internal { isMinter[account] = true; emit MinterAdded(account); } } // File contracts/token/ERC1155/TokenLaunchpadVouchers.sol pragma solidity >=0.7.6 <0.8.0; // solhint-disable-next-line max-line-length /** * @title TokenLaunchpadVouchers */ contract TokenLaunchpadVouchers is Recoverable, UsingUniversalForwarding, ERC1155InventoryBurnable, IERC1155InventoryMintable, IERC1155InventoryCreator, BaseMetadataURI, MinterRole { constructor(IForwarderRegistry forwarderRegistry, address universalForwarder) UsingUniversalForwarding(forwarderRegistry, universalForwarder) MinterRole(msg.sender) {} //======================================================= ERC165 ========================================================// /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC1155InventoryCreator).interfaceId || super.supportsInterface(interfaceId); } //================================================= ERC1155MetadataURI ==================================================// /// @inheritdoc IERC1155MetadataURI function uri(uint256 id) external view virtual override returns (string memory) { return _uri(id); } //=============================================== ERC1155InventoryCreator ===============================================// /// @inheritdoc IERC1155InventoryCreator function creator(uint256 collectionId) external view override returns (address) { return _creator(collectionId); } //=========================================== ERC1155InventoryCreator (admin) ===========================================// /** * Creates a collection. * @dev Reverts if the sender is not the contract owner. * @dev Reverts if `collectionId` does not represent a collection. * @dev Reverts if `collectionId` has already been created. * @dev Emits a {IERC1155Inventory-CollectionCreated} event. * @param collectionId Identifier of the collection. */ function createCollection(uint256 collectionId) external { _requireOwnership(_msgSender()); _createCollection(collectionId); } //============================================== ERC1155InventoryMintable ===============================================// /// @inheritdoc IERC1155InventoryMintable /// @dev Reverts if the sender is not a minter. function safeMint( address to, uint256 id, uint256 value, bytes memory data ) public virtual override { _requireMinter(_msgSender()); _safeMint(to, id, value, data); } /// @inheritdoc IERC1155InventoryMintable /// @dev Reverts if the sender is not a minter. function safeBatchMint( address to, uint256[] memory ids, uint256[] memory values, bytes memory data ) public virtual override { _requireMinter(_msgSender()); _safeBatchMint(to, ids, values, data); } //======================================== Meta Transactions Internal Functions =========================================// function _msgSender() internal view virtual override(ManagedIdentity, UsingUniversalForwarding) returns (address payable) { return UsingUniversalForwarding._msgSender(); } function _msgData() internal view virtual override(ManagedIdentity, UsingUniversalForwarding) returns (bytes memory ret) { return UsingUniversalForwarding._msgData(); } }
@inheritdoc IERC1155InventoryTotalSupply
function totalSupply(uint256 id) external view virtual override returns (uint256) { if (id.isNonFungibleToken()) { return address(uint160(_owners[id])) == address(0) ? 0 : 1; return _supplies[id]; } }
13,005,269
pragma solidity ^0.4.15; interface TokenInterface { function mint(address _to, uint256 _amount) public returns (bool); function finishMinting() public returns (bool); function totalSupply() public constant returns (uint); function balanceOf(address _address) public constant returns (uint); function burn(address burner); function hold(address addr, uint duration) external; function transfer(address _to, uint _amount) external; function contributeTo(address _to, uint256 _amount) public; } interface VotingFactoryInterface { function createRegular(address _creator, string _name, string _description, uint _duration, bytes32[] _options) external returns (address); function createWithdrawal(address _creator, string _name, string _description, uint _duration, uint _sum, address withdrawalWallet, bool _dxc) external returns (address); function createRefund(address _creator, string _name, string _description, uint _duration) external returns (address); function createModule(address _creator, string _name, string _description, uint _duration, uint _module, address _newAddress) external returns (address); function setDaoFactory(address _dao) external; } library DAOLib { event VotingCreated( address voting, string votingType, address dao, string name, string description, uint duration, address sender ); /* * @dev Receives parameters from crowdsale module in case of successful crowdsale and processes them * @param token Instance of token contract * @param commissionRaised Amount of funds which were sent via commission contract * @param serviceContract Address of contract which receives commission * @param teamBonuses Array of percents which indicates the number of token for every team member * @param team Array of team members' addresses * @param teamHold Array of timestamp until which the tokens will be held for every team member * @return uint Amount of tokens minted for team */ function handleFinishedCrowdsale(TokenInterface token, uint commissionRaised, address serviceContract, uint[] teamBonuses, address[] team, uint[] teamHold) returns (uint) { uint commission = (commissionRaised / 100) * 4; serviceContract.call.gas(200000).value(commission)(); uint totalSupply = token.totalSupply() / 100; uint teamTokensAmount = 0; for (uint i = 0; i < team.length; i++) { uint teamMemberTokensAmount = SafeMath.mul(totalSupply, teamBonuses[i]); teamTokensAmount += teamMemberTokensAmount; token.mint(team[i], teamMemberTokensAmount); token.hold(team[i], teamHold[i]); } return teamTokensAmount; } function delegatedCreateRegular(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, bytes32[] _options, address _dao) returns (address) { address _votingAddress = _votingFactory.createRegular(msg.sender, _name, _description, _duration, _options); VotingCreated(_votingAddress, "Regular", _dao, _name, _description, _duration, msg.sender); return _votingAddress; } function delegatedCreateWithdrawal(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, uint _sum, address withdrawalWallet, bool _dxc, address _dao) returns (address) { address _votingAddress = _votingFactory.createWithdrawal(msg.sender, _name, _description, _duration, _sum, withdrawalWallet, _dxc); VotingCreated(_votingAddress, "Withdrawal", _dao, _name, _description, _duration, msg.sender); return _votingAddress; } function delegatedCreateRefund(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, address _dao) returns (address) { address _votingAddress = _votingFactory.createRefund(msg.sender, _name, _description, _duration); VotingCreated(_votingAddress, "Refund", _dao, _name, _description, _duration, msg.sender); return _votingAddress; } function delegatedCreateModule(VotingFactoryInterface _votingFactory, string _name, string _description, uint _duration, uint _module, address _newAddress, address _dao) returns (address) { address _votingAddress = _votingFactory.createModule(msg.sender, _name, _description, _duration, _module, _newAddress); VotingCreated(_votingAddress, "Module", _dao, _name, _description, _duration, msg.sender); return _votingAddress; } /* * @dev Counts the number of tokens that should be minted according to amount of sent funds and current rate * @param value Amount of sent funds * @param bonusPeriods Array of timestamps indicating bonus periods * @param bonusRates Array of rates for every bonus period * @param rate Default rate * @return uint Amount of tokens that should be minted */ function countTokens(uint value, uint[] bonusPeriods, uint[] bonusRates, uint rate) constant returns (uint) { if (bonusRates.length == 0) return value * rate; // DXC bonus rates could be empty for (uint i = 0; i < bonusPeriods.length; i++) { if (now < bonusPeriods[i]) { rate = bonusRates[i]; break; } } uint tokensAmount = SafeMath.mul(value, rate); return tokensAmount; } /* * @dev Counts the amount of funds that must be returned to participant * @param tokensAmount Amount of tokens on participant's balance * @param etherRate Rate for ether during the crowdsale * @param newRate Current rate according to left funds and total supply of tokens * @param multiplier Multiplier that was used in previous calculations to avoid issues with float numbers * @return uint Amount of funds that must be returned to participant */ function countRefundSum(uint tokensAmount, uint etherRate, uint newRate, uint multiplier) constant returns (uint) { uint fromPercentDivider = 100; return (tokensAmount / fromPercentDivider * newRate) / (multiplier * etherRate); } } contract CrowdsaleDAOFields { uint public etherRate; uint public DXCRate; uint public softCap; uint public hardCap; uint public startTime; uint public endTime; bool public canInitCrowdsaleParameters = true; bool public canInitStateParameters = true; bool public canInitBonuses = true; bool public canSetWhiteList = true; uint public commissionRaised = 0; // Funds which were provided via commission contract uint public weiRaised = 0; uint public DXCRaised = 0; uint public fundsRaised = 0; mapping(address => uint) public depositedWei; // Used for refund in case of not reached soft cap mapping(address => uint) public depositedDXC; // Used for refund in case of not reached soft cap bool public crowdsaleFinished; bool public refundableSoftCap = false; uint public newEtherRate = 0; // Used for refund after accept of Refund proposal uint public newDXCRate = 0; // Used for refund after accept of Refund proposal address public serviceContract; //Contract which gets commission funds if soft cap was reached during the crowdsale uint[] public teamBonusesArr; address[] public team; mapping(address => bool) public teamMap; uint[] public teamHold; bool[] public teamServiceMember; TokenInterface public token; VotingFactoryInterface public votingFactory; address public commissionContract; //Contract that is used to mark funds which were provided through daox.org platform string public name; string public description; uint public created_at = now; // UNIX time mapping(address => bool) public votings; bool public refundable = false; uint public lastWithdrawalTimestamp = 0; address[] public whiteListArr; mapping(address => bool) public whiteList; mapping(address => uint) public teamBonuses; uint[] public bonusPeriods; uint[] public bonusEtherRates; uint[] public bonusDXCRates; uint public teamTokensAmount; uint constant internal withdrawalPeriod = 120 * 24 * 60 * 60; TokenInterface public DXC; uint public tokensMintedByEther; uint public tokensMintedByDXC; bool public dxcPayments; //Flag indicating whether it is possible to invest via DXC token or not uint internal constant multiplier = 100000; uint internal constant percentMultiplier = 100; } contract Owned { address public owner; function Owned(address _owner) { owner = _owner; } function transferOwnership(address newOwner) onlyOwner(msg.sender) { owner = newOwner; } modifier onlyOwner(address _sender) { require(_sender == owner); _; } } interface IDAOPayable { function handleCommissionPayment(address _sender) payable; } contract Commission { IDAOPayable dao; function Commission(address _dao) { dao = IDAOPayable(_dao); } function() payable { dao.handleCommissionPayment.value(msg.value)(msg.sender); } } contract State is CrowdsaleDAOFields { address public owner; event State(address _comission); /* * @dev Sets addresses of token which will be minted during the crowdsale and address of DXC token contract so that * DAO will be able to handle investments via DXC. Also function creates instance of Commission contract for this DAO * @param value Amount of sent funds */ function initState(address _tokenAddress, address _DXC) external onlyOwner(msg.sender) canInit crowdsaleNotStarted { require(_tokenAddress != 0x0 && _DXC != 0x0); token = TokenInterface(_tokenAddress); DXC = TokenInterface(_DXC); created_at = block.timestamp; commissionContract = new Commission(this); canInitStateParameters = false; State(commissionContract); } modifier canInit() { require(canInitStateParameters); _; } modifier crowdsaleNotStarted() { require(startTime == 0 || block.timestamp < startTime); _; } modifier onlyOwner(address _sender) { require(_sender == owner); _; } } contract Crowdsale is CrowdsaleDAOFields { address public owner; /* * @dev Receives info about ether payment from CrowdsaleDAO contract then mints tokens for sender and saves info about * sent funds to either return it in case of refund or get commission from them in case of successful crowdsale * @param _sender Address of sender * @param _commission Boolean indicating whether it is needed to take commission from sent funds or not */ function handlePayment(address _sender, bool _commission) external payable CrowdsaleIsOngoing validEtherPurchase(msg.value) { require(_sender != 0x0); uint weiAmount = msg.value; if (_commission) { commissionRaised = commissionRaised + weiAmount; } weiRaised += weiAmount; depositedWei[_sender] += weiAmount; uint tokensAmount = DAOLib.countTokens(weiAmount, bonusPeriods, bonusEtherRates, etherRate); tokensMintedByEther = SafeMath.add(tokensMintedByEther, tokensAmount); token.mint(_sender, tokensAmount); } /* * @dev Receives info about DXC payment from CrowdsaleDAO contract then mints tokens for sender and saves info about * sent funds to return it in case of refund * @param _from Address of sender * @param _dxcAmount Amount of DXC token which were sent to DAO */ function handleDXCPayment(address _from, uint _dxcAmount) external CrowdsaleIsOngoing validDXCPurchase(_dxcAmount) onlyDXC { DXCRaised += _dxcAmount; depositedDXC[_from] += _dxcAmount; uint tokensAmount = DAOLib.countTokens(_dxcAmount, bonusPeriods, bonusDXCRates, DXCRate); tokensMintedByDXC = SafeMath.add(tokensMintedByDXC, tokensAmount); token.mint(_from, tokensAmount); } /* * @dev Sets main parameters for upcoming crowdsale * @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful * @param _hardCap The maximal amount of funds that can be raised during the crowdsale * @param _etherRate Amount of tokens that will be minted per one ether * @param _DXCRate Amount of tokens that will be minted per one DXC * @param _startTime Unix timestamp that indicates the moment when crowdsale will start * @param _endTime Unix timestamp which indicates the moment when crowdsale will end * @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not */ function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments) external onlyOwner(msg.sender) canInit { require(_softCap != 0 && _hardCap != 0 && _etherRate != 0 && _DXCRate != 0 && _startTime != 0 && _endTime != 0); require(_softCap < _hardCap && _startTime > block.timestamp); softCap = _softCap * 1 ether; hardCap = _hardCap * 1 ether; (startTime, endTime) = (_startTime, _endTime); (dxcPayments, etherRate, DXCRate) = (_dxcPayments, _etherRate, _DXCRate); canInitCrowdsaleParameters = false; } /* * @dev Finishes the crowdsale and analyzes whether it is successful or not. If it is not then DAO goes to refundableSoftCap * state otherwise it counts and mints tokens for team members and holds them for certain period of time according to * parameters which were set for every member via initBonuses function. In addition function sends commission to service contract */ function finish() external { fundsRaised = DXCRate != 0 ? weiRaised + (DXC.balanceOf(this)) / (etherRate / DXCRate) : weiRaised; require((block.timestamp >= endTime || fundsRaised == hardCap) && !crowdsaleFinished); crowdsaleFinished = true; if (fundsRaised >= softCap) { teamTokensAmount = DAOLib.handleFinishedCrowdsale(token, commissionRaised, serviceContract, teamBonusesArr, team, teamHold); } else { refundableSoftCap = true; } token.finishMinting(); } modifier canInit() { require(canInitCrowdsaleParameters); _; } modifier onlyCommission() { require(commissionContract == msg.sender); _; } modifier CrowdsaleIsOngoing() { require(block.timestamp >= startTime && block.timestamp < endTime && !crowdsaleFinished); _; } modifier validEtherPurchase(uint value) { require(DXCRate != 0 ? hardCap - DXCRaised / (etherRate / DXCRate) >= weiRaised + value : hardCap >= weiRaised + value); _; } modifier validDXCPurchase(uint value) { require(dxcPayments && (hardCap - weiRaised >= (value + DXCRaised) / (etherRate / DXCRate))); _; } modifier onlyDXC() { require(msg.sender == address(DXC)); _; } modifier onlyOwner(address _sender) { require(_sender == owner); _; } } contract Payment is CrowdsaleDAOFields { /* * @dev Returns funds to participant according to amount of funds that left in DAO and amount of tokens for this participant */ function refund() whenRefundable notTeamMember { uint tokensMintedSum = SafeMath.add(tokensMintedByEther, tokensMintedByDXC); uint etherPerDXCRate = SafeMath.mul(tokensMintedByEther, percentMultiplier) / tokensMintedSum; uint dxcPerEtherRate = SafeMath.mul(tokensMintedByDXC, percentMultiplier) / tokensMintedSum; uint tokensAmount = token.balanceOf(msg.sender); token.burn(msg.sender); if (etherPerDXCRate != 0) msg.sender.transfer(DAOLib.countRefundSum(etherPerDXCRate * tokensAmount, etherRate, newEtherRate, multiplier)); if (dxcPerEtherRate != 0) DXC.transfer(msg.sender, DAOLib.countRefundSum(dxcPerEtherRate * tokensAmount, DXCRate, newDXCRate, multiplier)); } /* * @dev Returns funds which were sent to crowdsale contract back to backer and burns tokens that were minted for him */ function refundSoftCap() whenRefundableSoftCap { require(depositedWei[msg.sender] != 0 || depositedDXC[msg.sender] != 0); token.burn(msg.sender); uint weiAmount = depositedWei[msg.sender]; uint tokensAmount = depositedDXC[msg.sender]; delete depositedWei[msg.sender]; delete depositedDXC[msg.sender]; DXC.transfer(msg.sender, tokensAmount); msg.sender.transfer(weiAmount); } modifier whenRefundable() { require(refundable); _; } modifier whenRefundableSoftCap() { require(refundableSoftCap); _; } modifier onlyParticipant { require(token.balanceOf(msg.sender) > 0); _; } modifier notTeamMember() { require(!teamMap[msg.sender]); _; } } contract VotingDecisions is CrowdsaleDAOFields { /* * @dev Transfers withdrawal sum in ether or DXC tokens to the whitelisted address. Calls from Withdrawal proposal * @param _address Whitelisted address * @param _withdrawalSum Amount of ether/DXC to be sent * @param _dxc Should withdrawal be in DXC tokens */ function withdrawal(address _address, uint _withdrawalSum, bool _dxc) notInRefundableState onlyVoting external { lastWithdrawalTimestamp = block.timestamp; _dxc ? DXC.transfer(_address, _withdrawalSum) : _address.transfer(_withdrawalSum); } /* * @dev Change DAO's mode to `refundable`. Can be called by any tokenholder */ function makeRefundableByUser() external { require(lastWithdrawalTimestamp == 0 && block.timestamp >= created_at + withdrawalPeriod || lastWithdrawalTimestamp != 0 && block.timestamp >= lastWithdrawalTimestamp + withdrawalPeriod); makeRefundable(); } /* * @dev Change DAO's mode to `refundable`. Calls from Refund proposal */ function makeRefundableByVotingDecision() external onlyVoting { makeRefundable(); } /* * @dev Change DAO's mode to `refundable`. Calls from this contract `makeRefundableByUser` or `makeRefundableByVotingDecision` functions */ function makeRefundable() notInRefundableState private { refundable = true; newEtherRate = SafeMath.mul(this.balance * etherRate, multiplier) / tokensMintedByEther; newDXCRate = tokensMintedByDXC != 0 ? SafeMath.mul(DXC.balanceOf(this) * DXCRate, multiplier) / tokensMintedByDXC : 0; } /* * @dev Make tokens of passed address non-transferable for passed period * @param _address Address of tokenholder * @param _duration Hold's duration in seconds */ function holdTokens(address _address, uint _duration) onlyVoting external { token.hold(_address, _duration); } /* * @dev Throws if called not by any voting contract */ modifier onlyVoting() { require(votings[msg.sender]); _; } /* * @dev Throws if DAO is in refundable state */ modifier notInRefundableState { require(!refundable && !refundableSoftCap); _; } } interface DAOFactoryInterface { function exists(address _address) external constant returns (bool); } library DAODeployer { function deployCrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress) returns(CrowdsaleDAO dao) { dao = new CrowdsaleDAO(_name, _description, _serviceContractAddress, _votingFactoryContractAddress); } function transferOwnership(address _dao, address _newOwner) { CrowdsaleDAO(_dao).transferOwnership(_newOwner); } } library DAOProxy { function delegatedInitState(address stateModule, address _tokenAddress, address _DXC) { require(stateModule.delegatecall(bytes4(keccak256("initState(address,address)")), _tokenAddress, _DXC)); } function delegatedHoldState(address stateModule, uint _tokenHoldTime) { require(stateModule.delegatecall(bytes4(keccak256("initHold(uint256)")), _tokenHoldTime)); } function delegatedGetCommissionTokens(address paymentModule) { require(paymentModule.delegatecall(bytes4(keccak256("getCommissionTokens()")))); } function delegatedRefund(address paymentModule) { require(paymentModule.delegatecall(bytes4(keccak256("refund()")))); } function delegatedRefundSoftCap(address paymentModule) { require(paymentModule.delegatecall(bytes4(keccak256("refundSoftCap()")))); } function delegatedWithdrawal(address votingDecisionModule, address _address, uint withdrawalSum, bool dxc) { require(votingDecisionModule.delegatecall(bytes4(keccak256("withdrawal(address,uint256,bool)")), _address, withdrawalSum, dxc)); } function delegatedMakeRefundableByUser(address votingDecisionModule) { require(votingDecisionModule.delegatecall(bytes4(keccak256("makeRefundableByUser()")))); } function delegatedMakeRefundableByVotingDecision(address votingDecisionModule) { require(votingDecisionModule.delegatecall(bytes4(keccak256("makeRefundableByVotingDecision()")))); } function delegatedHoldTokens(address votingDecisionModule, address _address, uint duration) { require(votingDecisionModule.delegatecall(bytes4(keccak256("holdTokens(address,uint256)")), _address, duration)); } function delegatedInitCrowdsaleParameters( address crowdsaleModule, uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments ) { require(crowdsaleModule.delegatecall(bytes4(keccak256("initCrowdsaleParameters(uint256,uint256,uint256,uint256,uint256,uint256,bool)")) , _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments)); } function delegatedFinish(address crowdsaleModule) { require(crowdsaleModule.delegatecall(bytes4(keccak256("finish()")))); } function delegatedHandlePayment(address crowdsaleModule, address _sender, bool _commission) { require(crowdsaleModule.delegatecall(bytes4(keccak256("handlePayment(address,bool)")), _sender, _commission)); } function delegatedHandleDXCPayment(address crowdsaleModule, address _from, uint _amount) { require(crowdsaleModule.delegatecall(bytes4(keccak256("handleDXCPayment(address,uint256)")), _from, _amount)); } } library Common { function stringToBytes32(string memory source) constant returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } function percent(uint numerator, uint denominator, uint precision) constant returns(uint quotient) { uint _numerator = numerator * 10 ** (precision+1); quotient = ((_numerator / denominator) + 5) / 10; } function toString(bytes32 _bytes) internal constant returns(string) { bytes memory arrayTemp = new bytes(32); uint currentLength = 0; for (uint i = 0; i < 32; i++) { arrayTemp[i] = _bytes[i]; if (arrayTemp[i] != 0) currentLength+=1; } bytes memory arrayRes = new bytes(currentLength); for (i = 0; i < currentLength; i++) { arrayRes[i] = arrayTemp[i]; } return string(arrayRes); } } contract CrowdsaleDAO is CrowdsaleDAOFields, Owned { address public stateModule; address public paymentModule; address public votingDecisionModule; address public crowdsaleModule; function CrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress) Owned(msg.sender) { (name, description, serviceContract, votingFactory) = (_name, _description, _serviceContractAddress, VotingFactoryInterface(_votingFactoryContractAddress)); } /* * @dev Receives ether and forwards to the crowdsale module via a delegatecall with commission flag equal to false */ function() payable { DAOProxy.delegatedHandlePayment(crowdsaleModule, msg.sender, false); } /* * @dev Receives ether from commission contract and forwards to the crowdsale module * via a delegatecall with commission flag equal to true * @param _sender Address which sent ether to commission contract */ function handleCommissionPayment(address _sender) payable { DAOProxy.delegatedHandlePayment(crowdsaleModule, _sender, true); } /* * @dev Receives info about address which sent DXC tokens to current contract and about amount of sent tokens from * DXC token contract and then forwards this data to the crowdsale module * @param _from Address which sent DXC tokens * @param _amount Amount of tokens which were sent */ function handleDXCPayment(address _from, uint _amount) { DAOProxy.delegatedHandleDXCPayment(crowdsaleModule, _from, _amount); } /* * @dev Receives decision from withdrawal voting and forwards it to the voting decisions module * @param _address Address for withdrawal * @param _withdrawalSum Amount of ether/DXC tokens which must be sent to withdrawal address * @param _dxc boolean indicating whether withdrawal should be made through DXC tokens or not */ function withdrawal(address _address, uint _withdrawalSum, bool _dxc) external { DAOProxy.delegatedWithdrawal(votingDecisionModule, _address, _withdrawalSum, _dxc); } /* * @dev Receives decision from refund voting and forwards it to the voting decisions module */ function makeRefundableByVotingDecision() external { DAOProxy.delegatedMakeRefundableByVotingDecision(votingDecisionModule); } /* * @dev Called by voting contract to hold tokens of voted address. * It is needed to prevent multiple votes with same tokens * @param _address Voted address * @param _duration Amount of time left for voting to be finished */ function holdTokens(address _address, uint _duration) external { DAOProxy.delegatedHoldTokens(votingDecisionModule, _address, _duration); } function setStateModule(address _stateModule) external canSetAddress(stateModule) { stateModule = _stateModule; } function setPaymentModule(address _paymentModule) external canSetAddress(paymentModule) { paymentModule = _paymentModule; } function setVotingDecisionModule(address _votingDecisionModule) external canSetAddress(votingDecisionModule) { votingDecisionModule = _votingDecisionModule; } function setCrowdsaleModule(address _crowdsaleModule) external canSetAddress(crowdsaleModule) { crowdsaleModule = _crowdsaleModule; } function setVotingFactoryAddress(address _votingFactory) external canSetAddress(votingFactory) { votingFactory = VotingFactoryInterface(_votingFactory); } /* * @dev Checks if provided address has tokens of current DAO * @param _participantAddress Address of potential participant * @return boolean indicating if the address has at least one token */ function isParticipant(address _participantAddress) external constant returns (bool) { return token.balanceOf(_participantAddress) > 0; } /* * @dev Function which is used to set address of token which will be distributed by DAO during the crowdsale and * address of DXC token contract to use it for handling payment operations with DXC. Delegates call to state module * @param _tokenAddress Address of token which will be distributed during the crowdsale * @param _DXC Address of DXC contract */ function initState(address _tokenAddress, address _DXC) public { DAOProxy.delegatedInitState(stateModule, _tokenAddress, _DXC); } /* * @dev Delegates parameters which describe conditions of crowdsale to the crowdsale module. * @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful * @param _hardCap The maximal amount of funds that can be raised during the crowdsale * @param _etherRate Amount of tokens that will be minted per one ether * @param _DXCRate Amount of tokens that will be minted per one DXC * @param _startTime Unix timestamp that indicates the moment when crowdsale will start * @param _endTime Unix timestamp that indicates the moment when crowdsale will end * @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not */ function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments) public { DAOProxy.delegatedInitCrowdsaleParameters(crowdsaleModule, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments); } /* * @dev Delegates request of creating "regular" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished * @param _options List of options */ function addRegular(string _name, string _description, uint _duration, bytes32[] _options) public { votings[DAOLib.delegatedCreateRegular(votingFactory, _name, _description, _duration, _options, this)] = true; } /* * @dev Delegates request of creating "withdrawal" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished * @param _sum Amount of funds that is supposed to be withdrawn * @param _withdrawalWallet Address for withdrawal * @param _dxc Boolean indicating whether withdrawal must be in DXC tokens or in ether */ function addWithdrawal(string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) public { votings[DAOLib.delegatedCreateWithdrawal(votingFactory, _name, _description, _duration, _sum, _withdrawalWallet, _dxc, this)] = true; } /* * @dev Delegates request of creating "refund" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished */ function addRefund(string _name, string _description, uint _duration) public { votings[DAOLib.delegatedCreateRefund(votingFactory, _name, _description, _duration, this)] = true; } /* * @dev Delegates request of creating "module" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished * @param _module Number of module which must be replaced * @param _newAddress Address of new module */ function addModule(string _name, string _description, uint _duration, uint _module, address _newAddress) public { votings[DAOLib.delegatedCreateModule(votingFactory, _name, _description, _duration, _module, _newAddress, this)] = true; } /* * @dev Delegates request for going into refundable state to voting decisions module */ function makeRefundableByUser() public { DAOProxy.delegatedMakeRefundableByUser(votingDecisionModule); } /* * @dev Delegates request for refund to payment module */ function refund() public { DAOProxy.delegatedRefund(paymentModule); } /* * @dev Delegates request for refund of soft cap to payment module */ function refundSoftCap() public { DAOProxy.delegatedRefundSoftCap(paymentModule); } /* * @dev Delegates request for finish of crowdsale to crowdsale module */ function finish() public { DAOProxy.delegatedFinish(crowdsaleModule); } /* * @dev Sets team addresses and bonuses for crowdsale * @param _team The addresses that will be defined as team members * @param _tokenPercents Array of bonuses in percents which will go te every member in case of successful crowdsale * @param _bonusPeriods Array of timestamps which show when tokens will be minted with higher rate * @param _bonusEtherRates Array of ether rates for every bonus period * @param _bonusDXCRates Array of DXC rates for every bonus period * @param _teamHold Array of timestamps which show the hold duration of tokens for every team member * @param service Array of booleans which show whether member is a service address or not */ function initBonuses(address[] _team, uint[] _tokenPercents, uint[] _bonusPeriods, uint[] _bonusEtherRates, uint[] _bonusDXCRates, uint[] _teamHold, bool[] _service) public onlyOwner(msg.sender) { require( _team.length == _tokenPercents.length && _team.length == _teamHold.length && _team.length == _service.length && _bonusPeriods.length == _bonusEtherRates.length && (_bonusDXCRates.length == 0 || _bonusPeriods.length == _bonusDXCRates.length) && canInitBonuses && (block.timestamp < startTime || canInitCrowdsaleParameters) ); team = _team; teamHold = _teamHold; teamBonusesArr = _tokenPercents; teamServiceMember = _service; for(uint i = 0; i < _team.length; i++) { teamMap[_team[i]] = true; teamBonuses[_team[i]] = _tokenPercents[i]; } bonusPeriods = _bonusPeriods; bonusEtherRates = _bonusEtherRates; bonusDXCRates = _bonusDXCRates; canInitBonuses = false; } /* * @dev Sets addresses which can be used to get funds via withdrawal votings * @param _addresses Array of addresses which will be used for withdrawals */ function setWhiteList(address[] _addresses) public onlyOwner(msg.sender) { require(canSetWhiteList); whiteListArr = _addresses; for(uint i = 0; i < _addresses.length; i++) { whiteList[_addresses[i]] = true; } canSetWhiteList = false; } /* Modifiers */ modifier canSetAddress(address module) { require(votings[msg.sender] || (module == 0x0 && msg.sender == owner)); _; } } 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; } } library VotingLib { struct Option { uint votes; bytes32 description; } function delegatecallCreate(address _v, address _dao, string _name, string _description, uint _duration, uint _quorum) { require(_v.delegatecall(bytes4(keccak256("create(address,bytes32,bytes32,uint256,uint256)")), _dao, Common.stringToBytes32(_name), Common.stringToBytes32(_description), _duration, _quorum) ); } function delegatecallAddVote(address _v, uint optionID) { require(_v.delegatecall(bytes4(keccak256("addVote(uint256)")), optionID)); } function delegatecallFinish(address _v) { require(_v.delegatecall(bytes4(keccak256("finish()")))); } function isValidWithdrawal(address _dao, uint _sum, bool _dxc) constant returns(bool) { return !_dxc ? _dao.balance >= _sum : ICrowdsaleDAO(_dao).DXC().balanceOf(_dao) >= _sum; } } contract IDAO { function isParticipant(address _participantAddress) external constant returns (bool); function teamMap(address _address) external constant returns (bool); function whiteList(address _address) constant returns (bool); } contract ICrowdsaleDAO is IDAO { bool public crowdsaleFinished; uint public teamTokensAmount; uint public endTime; uint public weiRaised; uint public softCap; uint public fundsRaised; function addRegular(string _description, uint _duration, bytes32[] _options) external; function addWithdrawal(string _description, uint _duration, uint _sum) external; function addRefund(string _description, uint _duration) external; function addModule(string _description, uint _duration, uint _module, address _newAddress) external; function holdTokens(address _address, uint duration) external; function makeRefundableByVotingDecision(); function withdrawal(address _address, uint withdrawalSum, bool dxc); function setStateModule(address _stateModule); function setPaymentModule(address _paymentModule); function setVotingDecisionModule(address _votingDecisionModule); function setCrowdsaleModule(address _crowdsaleModule); function setVotingFactoryAddress(address _votingFactory); function teamBonuses(address _address) constant returns (uint); function token() constant returns (TokenInterface); function DXC() constant returns(TokenInterface); } contract VotingFields { ICrowdsaleDAO dao; string public name; string public description; VotingLib.Option[11] public options; mapping (address => uint) public voted; VotingLib.Option public result; uint public votesCount; uint public duration; // UNIX uint public created_at = now; bool public finished = false; uint public quorum; string public votingType; uint public minimalDuration = 60 * 60 * 24 * 7; // 7 days } interface VotingInterface { function addVote(uint optionID) external; function finish() external; function getOptions() external constant returns(uint[2] result); function finished() external constant returns(bool); function voted(address _address) external constant returns (uint); } contract BaseProposal is VotingFields { address baseVoting; /* * @dev Returns amount of votes for `yes` and `no` options */ function getOptions() public constant returns(uint[2]) { return [options[1].votes, options[2].votes]; } /* * @dev Delegates request of adding vote to the Voting base contract * @param _optionID ID of option which will be added as vote */ function addVote(uint _optionID) public { VotingLib.delegatecallAddVote(baseVoting, _optionID); } /* * @dev Initiates options `yes` and `no` */ function createOptions() internal { options[1] = VotingLib.Option(0, "yes"); options[2] = VotingLib.Option(0, "no"); } } contract Regular is VotingFields { address baseVoting; function Regular(address _baseVoting, address _dao, string _name, string _description, uint _duration, bytes32[] _options){ require(_options.length >= 2 && _options.length <= 10); baseVoting = _baseVoting; votingType = "Regular"; VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 0); createOptions(_options); } /* * @dev Returns amount of votes for all regular proposal's options * @return Array[10] of int */ function getOptions() external constant returns(uint[10]) { return [options[1].votes, options[2].votes, options[3].votes, options[4].votes, options[5].votes, options[6].votes, options[7].votes, options[8].votes, options[9].votes, options[10].votes]; } /* * @dev Delegates request of adding vote to the Voting base contract * @param _optionID ID of option which will be added as vote */ function addVote(uint _optionID) public { VotingLib.delegatecallAddVote(baseVoting, _optionID); } /* * @dev Delegates request of finishing to the Voting base contract */ function finish() public { VotingLib.delegatecallFinish(baseVoting); } /* * @dev Creates up to 10 options of votes * @param _options Array of votes options */ function createOptions(bytes32[] _options) private { for (uint i = 0; i < _options.length; i++) { options[i + 1] = VotingLib.Option(0, _options[i]); } } } contract Withdrawal is BaseProposal { uint public withdrawalSum; address public withdrawalWallet; bool public dxc; function Withdrawal(address _baseVoting, address _dao, string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) { require(_sum > 0 && VotingLib.isValidWithdrawal(_dao, _sum, _dxc)); baseVoting = _baseVoting; votingType = "Withdrawal"; VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 0); withdrawalSum = _sum; withdrawalWallet = _withdrawalWallet; dxc = _dxc; createOptions(); } /* * @dev Delegates request of finishing to the Voting base contract */ function finish() public { VotingLib.delegatecallFinish(baseVoting); if(result.description == "yes") dao.withdrawal(withdrawalWallet, withdrawalSum, dxc); } } contract Refund is BaseProposal { function Refund(address _baseVoting, address _dao, string _name, string _description, uint _duration) { baseVoting = _baseVoting; votingType = "Refund"; VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 90); createOptions(); } function finish() public { VotingLib.delegatecallFinish(baseVoting); if(result.description == "yes") dao.makeRefundableByVotingDecision(); } } contract Voting is VotingFields { /* * @dev Initiate storage variables for caller contract via `delegatecall` * @param _dao Address of dao where voting is creating * @param _name Voting name * @param _description Voting description * @param _duration Voting duration * @param _quorum Minimal percentage of token holders who must to take part in voting */ function create(address _dao, bytes32 _name, bytes32 _description, uint _duration, uint _quorum) succeededCrowdsale(ICrowdsaleDAO(_dao)) correctDuration(_duration) external { dao = ICrowdsaleDAO(_dao); name = Common.toString(_name); description = Common.toString(_description); duration = _duration; quorum = _quorum; } /* * @dev Add vote with passed optionID for the caller voting via `delegatecall` * @param _optionID ID of option */ function addVote(uint _optionID) external notFinished canVote correctOption(_optionID) { require(block.timestamp - duration < created_at); uint tokensAmount = dao.token().balanceOf(msg.sender); options[_optionID].votes += tokensAmount; voted[msg.sender] = _optionID; votesCount += tokensAmount; dao.holdTokens(msg.sender, (duration + created_at) - now); } /* * @dev Finish voting for the caller voting contract via `delegatecall` * @param _optionID ID of option */ function finish() external notFinished { require(block.timestamp - duration >= created_at); finished = true; if (keccak256(votingType) == keccak256("Withdrawal")) return finishNotRegular(); if (keccak256(votingType) == keccak256("Regular")) return finishRegular(); //Other two cases of votings (`Module` and `Refund`) requires quorum if (Common.percent(options[1].votes, dao.token().totalSupply() - dao.teamTokensAmount(), 2) >= quorum) { result = options[1]; return; } result = options[2]; } /* * @dev Finish regular voting. Calls from `finish` function */ function finishRegular() private { VotingLib.Option memory _result = options[1]; bool equal = false; for (uint i = 2; i < options.length; i++) { if (_result.votes == options[i].votes) equal = true; else if (_result.votes < options[i].votes) { _result = options[i]; equal = false; } } if (!equal) result = _result; } /* * @dev Finish non-regular voting. Calls from `finish` function */ function finishNotRegular() private { if (options[1].votes > options[2].votes) result = options[1]; else result = options[2]; } /* * @dev Throws if caller is team member, not participant or has voted already */ modifier canVote() { require(!dao.teamMap(msg.sender) && dao.isParticipant(msg.sender) && voted[msg.sender] == 0); _; } /* * @dev Throws if voting is finished already */ modifier notFinished() { require(!finished); _; } /* * @dev Throws if crowdsale is not finished or if soft cap is not achieved */ modifier succeededCrowdsale(ICrowdsaleDAO dao) { require(dao.crowdsaleFinished() && dao.fundsRaised() >= dao.softCap()); _; } /* * @dev Throws if description of provided option ID is empty */ modifier correctOption(uint optionID) { require(options[optionID].description != 0x0); _; } /* * @dev Throws if passed voting duration is not greater than minimal */ modifier correctDuration(uint _duration) { require(_duration >= minimalDuration || keccak256(votingType) == keccak256("Module")); _; } } contract Module is BaseProposal { enum Modules{State, Payment, VotingDecisions, Crowdsale, VotingFactory} Modules public module; address public newModuleAddress; function Module(address _baseVoting, address _dao, string _name, string _description, uint _duration, uint _module, address _newAddress) { require(_module >= 0 && _module <= 4); baseVoting = _baseVoting; votingType = "Module"; module = Modules(_module); newModuleAddress = _newAddress; VotingLib.delegatecallCreate(baseVoting, _dao, _name, _description, _duration, 80); createOptions(); } /* * @dev Delegates request of finishing to the Voting base contract */ function finish() public { VotingLib.delegatecallFinish(baseVoting); if(result.description == "no") return; //Sorry but solidity doesn't support `switch` keyword if (uint(module) == uint(Modules.State)) dao.setStateModule(newModuleAddress); if (uint(module) == uint(Modules.Payment)) dao.setPaymentModule(newModuleAddress); if (uint(module) == uint(Modules.VotingDecisions)) dao.setVotingDecisionModule(newModuleAddress); if (uint(module) == uint(Modules.Crowdsale)) dao.setCrowdsaleModule(newModuleAddress); if (uint(module) == uint(Modules.VotingFactory)) dao.setVotingFactoryAddress(newModuleAddress); } } contract VotingFactory is VotingFactoryInterface { address baseVoting; DAOFactoryInterface public daoFactory; function VotingFactory(address _baseVoting) { baseVoting = _baseVoting; } /* * @dev Create regular proposal with passed parameters. Calls from DAO contract * @param _creator Address of caller of DAO's respectively function * @param _name Voting's name * @param _description Voting's description * @param _duration Voting's duration * @param _options Voting's options */ function createRegular(address _creator, string _name, string _description, uint _duration, bytes32[] _options) external onlyDAO onlyParticipant(_creator) returns (address) { return new Regular(baseVoting, msg.sender, _name, _description, _duration, _options); } /* * @dev Create withdrawal proposal with passed parameters. Calls from DAO contract * @param _creator Address of caller of DAO's respectively function * @param _name Voting's name * @param _description Voting's description * @param _duration Voting's duration * @param _sum Sum to withdraw from DAO * @param _withdrawalWallet Address to send withdrawal sum * @param _dxc Should withdrawal sum be interpret as amount of DXC tokens */ function createWithdrawal(address _creator, string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) external onlyTeamMember(_creator) onlyDAO onlyWhiteList(_withdrawalWallet) returns (address) { return new Withdrawal(baseVoting, msg.sender, _name, _description, _duration, _sum, _withdrawalWallet, _dxc); } /* * @dev Create refund proposal with passed parameters. Calls from DAO contract * @param _creator Address of caller of DAO's respectively function * @param _name Voting's name * @param _description Voting's description * @param _duration Voting's duration */ function createRefund(address _creator, string _name, string _description, uint _duration) external onlyDAO onlyParticipant(_creator) returns (address) { return new Refund(baseVoting, msg.sender, _name, _description, _duration); } /* * @dev Create module proposal with passed parameters. Calls from DAO contract * @param _creator Address of caller of DAO's respectively function * @param _name Voting's name * @param _description Voting's description * @param _duration Voting's duration * @param _module Which module should be changed * @param _newAddress Address of new module */ function createModule(address _creator, string _name, string _description, uint _duration, uint _module, address _newAddress) external onlyDAO onlyParticipant(_creator) returns (address) { return new Module(baseVoting, msg.sender, _name, _description, _duration, _module, _newAddress); } /* * @dev Set dao factory address. Calls ones from just deployed DAO * @param _dao Address of dao factory */ function setDaoFactory(address _dao) external { require(address(daoFactory) == 0x0 && _dao != 0x0); daoFactory = DAOFactoryInterface(_dao); } /* * @dev Throws if caller is not correct DAO */ modifier onlyDAO() { require(daoFactory.exists(msg.sender)); _; } /* * @dev Throws if creator is not participant of passed DAO */ modifier onlyParticipant(address creator) { require(IDAO(msg.sender).isParticipant(creator)); _; } /* * @dev Throws if creator is not team member of passed DAO */ modifier onlyTeamMember(address creator) { require(IDAO(msg.sender).teamMap(creator)); _; } /* * @dev Throws if creator is not member of white list in specified DAO */ modifier onlyWhiteList(address creator) { require(IDAO(msg.sender).whiteList(creator)); _; } } 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); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } 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); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } 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; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract Token is MintableToken { event TokenCreation(address _address); string public name; string public symbol; uint constant public decimals = 18; mapping(address => uint) public held; function Token(string _name, string _symbol) { name = _name; symbol = _symbol; TokenCreation(this); } function hold(address addr, uint duration) external onlyOwner { uint holdTime = now + duration; if (held[addr] == 0 || holdTime > held[addr]) held[addr] = holdTime; } function burn(address _burner) external onlyOwner { require(_burner != 0x0); uint balance = balanceOf(_burner); balances[_burner] = balances[_burner].sub(balance); totalSupply = totalSupply.sub(balance); } function transfer(address to, uint256 value) public notHolded(msg.sender) returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public notHolded(from) returns (bool) { return super.transferFrom(from, to, value); } modifier notHolded(address _address) { require(held[_address] == 0 || now >= held[_address]); _; } } contract DAOx is Ownable { uint public balance; DAOFactoryInterface public daoFactory; function DAOx() { } function() payable onlyDAO { balance += msg.value; } function setDaoFactory(address _dao) external { require(address(daoFactory) == 0x0 && _dao != 0x0); daoFactory = DAOFactoryInterface(_dao); } function withdraw(uint _weiToWithdraw) public onlyOwner { balance -= _weiToWithdraw; msg.sender.transfer(_weiToWithdraw); } modifier onlyDAO() { require(daoFactory.exists(msg.sender)); _; } } contract CrowdsaleDAOFactory is DAOFactoryInterface { event CrowdsaleDAOCreated( address _address, string _name ); address public serviceContractAddress; address public votingFactoryContractAddress; // DAOs created by factory mapping(address => string) DAOs; // Functional modules which will be used by DAOs to delegate calls address[4] modules; function CrowdsaleDAOFactory(address _serviceContractAddress, address _votingFactoryAddress, address[4] _modules) { require(_serviceContractAddress != 0x0 && _votingFactoryAddress != 0x0); serviceContractAddress = _serviceContractAddress; votingFactoryContractAddress = _votingFactoryAddress; modules = _modules; require(votingFactoryContractAddress.call(bytes4(keccak256("setDaoFactory(address)")), this)); require(serviceContractAddress.call(bytes4(keccak256("setDaoFactory(address)")), this)); } /* * @dev Checks if provided address is an address of some DAO contract created by this factory * @param _address Address of contract * @return boolean indicating whether the contract was created by this factory or not */ function exists(address _address) external constant returns (bool) { return keccak256(DAOs[_address]) != keccak256(""); } /* * @dev Creates new CrowdsaleDAO contract, provides it with addresses of modules, transfers ownership to tx sender * and saves address of created contract to DAOs mapping * @param _name Name of the DAO * @param _name Description for the DAO */ function createCrowdsaleDAO(string _name, string _description) public { address dao = DAODeployer.deployCrowdsaleDAO(_name, _description, serviceContractAddress, votingFactoryContractAddress); require(dao.call(bytes4(keccak256("setStateModule(address)")), modules[0])); require(dao.call(bytes4(keccak256("setPaymentModule(address)")), modules[1])); require(dao.call(bytes4(keccak256("setVotingDecisionModule(address)")), modules[2])); require(dao.call(bytes4(keccak256("setCrowdsaleModule(address)")), modules[3])); DAODeployer.transferOwnership(dao, msg.sender); DAOs[dao] = _name; CrowdsaleDAOCreated(dao, _name); } } contract DXC is MintableToken { address[] public additionalOwnersList; // List of addresses which are able to call `mint` function mapping(address => bool) public additionalOwners; // Mapping of addresses which are able to call `mint` function uint public maximumSupply = 300000000 * 10**18; // Maximum supply of DXC tokens equals 300 millions event TokenCreation(address _address); event SetAdditionalOwners(address[] oldOwners, address[] newOwners); string public constant name = "Daox Coin"; string public constant symbol = "DXC"; uint public constant decimals = 18; /** * @dev Transfer specified amount of tokens to the specified address and call * standard `handleDXCPayment` method of Crowdsale DAO * @param _to The address of Crowdsale DAO * @param _amount The amount of tokens to send */ function contributeTo(address _to, uint256 _amount) public { super.transfer(_to, _amount); require(_to.call(bytes4(keccak256("handleDXCPayment(address,uint256)")), msg.sender, _amount)); } /** * @dev Overrides function to mint tokens from `MintableToken` contract with new modifier * @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) isOwnerOrAdditionalOwner canMint maximumSupplyWasNotReached(_amount) public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Define array and mapping of addresses that will be additional owners * @param _owners The addresses that will be defined as additional owners */ function setAdditionalOwners(address[] _owners) onlyOwner { SetAdditionalOwners(additionalOwnersList, _owners); for (uint i = 0; i < additionalOwnersList.length; i++) { additionalOwners[additionalOwnersList[i]] = false; } for (i = 0; i < _owners.length; i++) { additionalOwners[_owners[i]] = true; } additionalOwnersList = _owners; } /** * @dev Throws an exception if called not by owner or additional owner */ modifier isOwnerOrAdditionalOwner() { require(msg.sender == owner || additionalOwners[msg.sender]); _; } /** * @dev Throws an exception if maximumSupply will be exceeded after minting * @param _amount The amount of tokens to mint */ modifier maximumSupplyWasNotReached(uint256 _amount) { require(totalSupply.add(_amount) <= maximumSupply); _; } }
Create refund proposal with passed parameters. Calls from DAO contract _creator Address of caller of DAO's respectively function _name Voting's name _description Voting's description _duration Voting's duration/
function createRefund(address _creator, string _name, string _description, uint _duration) external onlyDAO onlyParticipant(_creator) returns (address) { return new Refund(baseVoting, msg.sender, _name, _description, _duration); }
12,948,352
pragma solidity ^0.4.24; /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } library BMKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } library BMDatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address uint256 win; // winnings vault uint256 gen; // general vault uint256 lrnd; // last round played } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round } } contract BMEvents { // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, uint256 compressedData, uint256 compressedIDs, address winnerAddr, uint256 amountWon, uint256 newPot, uint256 genAmount ); } contract BMGame is BMEvents { using SafeMath for *; using BMKeysCalcLong for uint256; address public Banker_Address; //============================================================================== // game settings //============================================================================== uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO uint256 private rndGap_ = 30; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 24 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // data used to store game info that changes //============================================================================== uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop //**************** // PLAYER DATA //**************** uint256 public pID_ = 0; // total number of players mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping(uint256 => BMDatasets.Player) public plyr_; // (pID => data) player data mapping(uint256 => mapping(uint256 => BMDatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id //**************** // ROUND DATA //**************** uint256 public rID_; // round id number / total rounds that have happened mapping(uint256 => BMDatasets.Round) public round_; // (rID => data) round data mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping(uint256 => BMDatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping(uint256 => BMDatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team address public owner; //============================================================================== // (initial data setup upon contract deploy) //============================================================================== constructor() public { owner = msg.sender; // Team allocation structures // 0 = whales 2 // 1 = bears 3 // 2 = sneks 0 // 3 = bulls 1 // Team allocation percentages fees_[0] = BMDatasets.TeamFee(70); //20% to pot, 5% to com, 5% to air drop pot fees_[1] = BMDatasets.TeamFee(55); //35% to pot, 5% to com, 5% to air drop pot fees_[2] = BMDatasets.TeamFee(40); //50% to pot, 5% to com, 5% to air drop pot fees_[3] = BMDatasets.TeamFee(30); //60% to pot, 5% to com, 5% to air drop pot // how to split up the final pot based on which team was picked potSplit_[0] = BMDatasets.PotSplit(50); //48% to winner, 0% to next round, 2% to com potSplit_[1] = BMDatasets.PotSplit(40); //48% to winner, 10% to next round, 2% to com potSplit_[2] = BMDatasets.PotSplit(25); //48% to winner, 25% to next round, 2% to com potSplit_[3] = BMDatasets.PotSplit(10); //48% to winner, 40% to next round, 2% to com } //============================================================================== // (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet."); _; } /** * @dev prevents contracts from interacting with bmg */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // (use these to interact with contract) //============================================================================== /** * @dev emergency buy uses team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not BMDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * @param _team what team is the player playing for? */ function buyKey(uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not BMDatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadKey(uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data BMDatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data BMDatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit BMEvents.onWithdrawAndDistribute ( msg.sender, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit BMEvents.onWithdraw(_pID, msg.sender, _eth, _now); } } //============================================================================== // (for UI & viewing things on etherscan) //============================================================================== /** * @dev return the price buyer will pay for next 1 individual key. * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns (uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); else // rounds over. need price for new round return (75000000000000); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * @return time left in seconds */ function getTimeLeft() public view returns (uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return ((round_[_rID].end).sub(_now)); else return ((round_[_rID].strt + rndGap_).sub(_now)); else return (0); } /** * @dev returns player earnings per vaults * @return winnings vault * @return general vault */ function getPlayerVaults(uint256 _pID) public view returns (uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100), (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)) ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)) ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)) ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns (uint256) { return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000)); } /** * @dev returns all current round info needed for front end * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, address, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( _rID, //0 round_[_rID].keys, //1 round_[_rID].end, //2 round_[_rID].strt, //3 round_[_rID].pot, //4 (round_[_rID].team + (round_[_rID].plyr * 10)), //5 plyr_[round_[_rID].plyr].addr, //6 rndTmEth_[_rID][0], //7 rndTmEth_[_rID][1], //8 rndTmEth_[_rID][2], //9 rndTmEth_[_rID][3], //10 airDropTracker_ + (airDropPot_ * 1000) //11 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns (uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyrRnds_[_pID][_rID].keys, //1 plyr_[_pID].win, //2 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //3 plyrRnds_[_pID][_rID].eth //4 ); } //============================================================================== // (this + tools + calcs + modules = our softwares engine) //============================================================================== /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _team, BMDatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit BMEvents.onBuyAndDistribute ( msg.sender, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } core(rID_, _pID, msg.value, _team, _eventData_); // put eth in players vault //plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _team, uint256 _eth, BMDatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit BMEvents.onReLoadAndDistribute ( msg.sender, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(rID_, _pID, _eth, _team, _eventData_); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, BMDatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distribute(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // (calculates) //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns (uint256) { return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns (uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ((round_[_rID].eth).keysRec(_eth)); else // rounds over. need keys for new round return ((_eth).keys()); } /** * @dev returns current eth price for X keys. * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns (uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); else // rounds over. need price for new round return ((_keys).eth()); } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(BMDatasets.EventReturns memory _eventData_) private returns (BMDatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of bmg if (_pID == 0) { pID_++; // set up player account pIDxAddr_[msg.sender] = pID_; plyr_[pID_].addr = msg.sender; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return (2); else return (_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, BMDatasets.EventReturns memory _eventData_) private returns (BMDatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return (_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(BMDatasets.EventReturns memory _eventData_) private returns (BMDatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(Banker_Address).send(_com)) { //if failed add to pot _res = _res.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return (_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns (bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if ((seed - ((seed / 1000) * 1000)) < airDropTracker_) return (true); else return (false); } /** * @dev distributes eth based on fees to gen and pot */ function distribute(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, BMDatasets.EventReturns memory _eventData_) private returns (BMDatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth / 20; if (!address(Banker_Address).send(_com)) { _com = 0; } // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot uint256 _pot = _eth.sub(_com).sub(_air).sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return (_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns (uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns (uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; } return (_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, BMDatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit BMEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (activate) //============================================================================== /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // can only be ran once require(msg.sender == owner, 'only dev!'); require(activated_ == false, "BiMoney Game already activated"); // activate the contract activated_ = true; Banker_Address = msg.sender; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } }
withdraws all of your earnings./ setup local rID grab time fetch player ID setup temp var for player eth check to see if round has ended and no one has run round end yet set up our tx event data end the round (distributes pot) get their earnings gib moni build event data fire withdraw and distribute event in any other situation get their earnings gib moni fire withdraw event
function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { BMDatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit BMEvents.onWithdrawAndDistribute ( msg.sender, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit BMEvents.onWithdraw(_pID, msg.sender, _eth, _now); } }
2,539,781
/** * @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; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of 'user permissions'. */ /// @title Ownable /// @author Applicature /// @notice helper mixed to other contracts to link contract on an owner /// @dev Base class contract Ownable { //Variables address public owner; address public newOwner; // Modifiers /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @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)); newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } } /** * @title TokenVesting * @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 TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; 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; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @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(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic 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); } } } /// @title OpenZeppelinERC20 /// @author Applicature /// @notice Open Zeppelin implementation of standart ERC20 /// @dev Base class contract OpenZeppelinERC20 is StandardToken, Ownable { using SafeMath for uint256; uint8 public decimals; string public name; string public symbol; string public standard; constructor( uint256 _totalSupply, string _tokenName, uint8 _decimals, string _tokenSymbol, bool _transferAllSupplyToOwner ) public { standard = 'ERC20 0.1'; totalSupply_ = _totalSupply; if (_transferAllSupplyToOwner) { balances[msg.sender] = _totalSupply; } else { balances[this] = _totalSupply; } name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimals; } } /// @title MintableToken /// @author Applicature /// @notice allow to mint tokens /// @dev Base class contract MintableToken is BasicToken, Ownable { using SafeMath for uint256; uint256 public maxSupply; bool public allowedMinting; mapping(address => bool) public mintingAgents; mapping(address => bool) public stateChangeAgents; event Mint(address indexed holder, uint256 tokens); modifier onlyMintingAgents () { require(mintingAgents[msg.sender]); _; } modifier onlyStateChangeAgents () { require(stateChangeAgents[msg.sender]); _; } constructor(uint256 _maxSupply, uint256 _mintedSupply, bool _allowedMinting) public { maxSupply = _maxSupply; totalSupply_ = totalSupply_.add(_mintedSupply); allowedMinting = _allowedMinting; mintingAgents[msg.sender] = true; } /// @notice allow to mint tokens function mint(address _holder, uint256 _tokens) public onlyMintingAgents() { require(allowedMinting == true && totalSupply_.add(_tokens) <= maxSupply); totalSupply_ = totalSupply_.add(_tokens); balances[_holder] = balances[_holder].add(_tokens); if (totalSupply_ == maxSupply) { allowedMinting = false; } emit Transfer(address(0), _holder, _tokens); emit Mint(_holder, _tokens); } /// @notice update allowedMinting flat function disableMinting() public onlyStateChangeAgents() { allowedMinting = false; } /// @notice update minting agent function updateMintingAgent(address _agent, bool _status) public onlyOwner { mintingAgents[_agent] = _status; } /// @notice update state change agent function updateStateChangeAgent(address _agent, bool _status) public onlyOwner { stateChangeAgents[_agent] = _status; } /// @return available tokens function availableTokens() public view returns (uint256 tokens) { return maxSupply.sub(totalSupply_); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /// @title MintableBurnableToken /// @author Applicature /// @notice helper mixed to other contracts to burn tokens /// @dev implementation contract MintableBurnableToken is MintableToken, BurnableToken { mapping (address => bool) public burnAgents; modifier onlyBurnAgents () { require(burnAgents[msg.sender]); _; } constructor( uint256 _maxSupply, uint256 _mintedSupply, bool _allowedMinting ) public MintableToken( _maxSupply, _mintedSupply, _allowedMinting ) { } /// @notice update burn agent function updateBurnAgent(address _agent, bool _status) public onlyOwner { burnAgents[_agent] = _status; } function burnByAgent(address _holder, uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) { if (_tokensToBurn == 0) { _tokensToBurn = balances[_holder]; } _burn(_holder, _tokensToBurn); return _tokensToBurn; } function _burn(address _who, uint256 _value) internal { super._burn(_who, _value); maxSupply = maxSupply.sub(_value); } } /// @title TimeLocked /// @author Applicature /// @notice helper mixed to other contracts to lock contract on a timestamp /// @dev Base class contract TimeLocked { uint256 public time; mapping(address => bool) public excludedAddresses; modifier isTimeLocked(address _holder, bool _timeLocked) { bool locked = (block.timestamp < time); require(excludedAddresses[_holder] == true || locked == _timeLocked); _; } constructor(uint256 _time) public { time = _time; } function updateExcludedAddress(address _address, bool _status) public; } /// @title TimeLockedToken /// @author Applicature /// @notice helper mixed to other contracts to lock contract on a timestamp /// @dev Base class contract TimeLockedToken is TimeLocked, StandardToken { constructor(uint256 _time) public TimeLocked(_time) {} function transfer(address _to, uint256 _tokens) public isTimeLocked(msg.sender, false) returns (bool) { return super.transfer(_to, _tokens); } function transferFrom(address _holder, address _to, uint256 _tokens) public isTimeLocked(_holder, false) returns (bool) { return super.transferFrom(_holder, _to, _tokens); } } contract ICUToken is OpenZeppelinERC20, MintableBurnableToken, TimeLockedToken { ICUCrowdsale public crowdsale; bool public isSoftCapAchieved; constructor(uint256 _unlockTokensTime) public OpenZeppelinERC20(0, 'iCumulate', 18, 'ICU', false) MintableBurnableToken(4700000000e18, 0, true) TimeLockedToken(_unlockTokensTime) {} function setUnlockTime(uint256 _unlockTokensTime) public onlyStateChangeAgents { time = _unlockTokensTime; } function setIsSoftCapAchieved() public onlyStateChangeAgents { isSoftCapAchieved = true; } function setCrowdSale(address _crowdsale) public onlyOwner { require(_crowdsale != address(0)); crowdsale = ICUCrowdsale(_crowdsale); } function updateExcludedAddress(address _address, bool _status) public onlyOwner { excludedAddresses[_address] = _status; } function transfer(address _to, uint256 _tokens) public returns (bool) { require(true == isTransferAllowed(msg.sender)); return super.transfer(_to, _tokens); } function transferFrom(address _holder, address _to, uint256 _tokens) public returns (bool) { require(true == isTransferAllowed(_holder)); return super.transferFrom(_holder, _to, _tokens); } function isTransferAllowed(address _address) public view returns (bool) { if (excludedAddresses[_address] == true) { return true; } if (!isSoftCapAchieved && (address(crowdsale) == address(0) || false == crowdsale.isSoftCapAchieved(0))) { return false; } return true; } function burnUnsoldTokens(uint256 _tokensToBurn) public onlyBurnAgents() returns (uint256) { require(maxSupply.sub(_tokensToBurn) >= totalSupply_); maxSupply = maxSupply.sub(_tokensToBurn); emit Burn(address(0), _tokensToBurn); return _tokensToBurn; } } /// @title Agent /// @author Applicature /// @notice Contract which takes actions on state change and contribution /// @dev Base class contract Agent { using SafeMath for uint256; function isInitialized() public view returns (bool) { return false; } } /// @title CrowdsaleAgent /// @author Applicature /// @notice Contract which takes actions on state change and contribution /// @dev Base class contract CrowdsaleAgent is Agent { Crowdsale public crowdsale; bool public _isInitialized; modifier onlyCrowdsale() { require(msg.sender == address(crowdsale)); _; } constructor(Crowdsale _crowdsale) public { crowdsale = _crowdsale; if (address(0) != address(_crowdsale)) { _isInitialized = true; } else { _isInitialized = false; } } function isInitialized() public view returns (bool) { return _isInitialized; } function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus) public onlyCrowdsale(); function onStateChange(Crowdsale.State _state) public onlyCrowdsale(); function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned); } /// @title MintableCrowdsaleOnSuccessAgent /// @author Applicature /// @notice Contract which takes actions on state change and contribution /// un-pause tokens and disable minting on Crowdsale success /// @dev implementation contract MintableCrowdsaleOnSuccessAgent is CrowdsaleAgent { MintableToken public token; bool public _isInitialized; constructor(Crowdsale _crowdsale, MintableToken _token) public CrowdsaleAgent(_crowdsale) { token = _token; if (address(0) != address(_token) && address(0) != address(_crowdsale)) { _isInitialized = true; } else { _isInitialized = false; } } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public view returns (bool) { return _isInitialized; } /// @notice Takes actions on contribution function onContribution(address _contributor, uint256 _weiAmount, uint256 _tokens, uint256 _bonus) public onlyCrowdsale; /// @notice Takes actions on state change, /// un-pause tokens and disable minting on Crowdsale success /// @param _state Crowdsale.State function onStateChange(Crowdsale.State _state) public onlyCrowdsale; } contract ICUAgent is MintableCrowdsaleOnSuccessAgent { ICUStrategy public strategy; ICUCrowdsale public crowdsale; bool public burnStatus; constructor( ICUCrowdsale _crowdsale, ICUToken _token, ICUStrategy _strategy ) public MintableCrowdsaleOnSuccessAgent(_crowdsale, _token) { require(address(_strategy) != address(0) && address(_crowdsale) != address(0)); strategy = _strategy; crowdsale = _crowdsale; } /// @notice Takes actions on contribution function onContribution( address, uint256 _tierIndex, uint256 _tokens, uint256 _bonus ) public onlyCrowdsale() { strategy.updateTierState(_tierIndex, _tokens, _bonus); } function onStateChange(Crowdsale.State _state) public onlyCrowdsale() { ICUToken icuToken = ICUToken(token); if ( icuToken.isSoftCapAchieved() == false && (_state == Crowdsale.State.Success || _state == Crowdsale.State.Finalized) && crowdsale.isSoftCapAchieved(0) ) { icuToken.setIsSoftCapAchieved(); } if (_state > Crowdsale.State.InCrowdsale && burnStatus == false) { uint256 unsoldTokensAmount = strategy.getUnsoldTokens(); burnStatus = true; icuToken.burnUnsoldTokens(unsoldTokensAmount); } } function onRefund(address _contributor, uint256 _tokens) public onlyCrowdsale() returns (uint256 burned) { burned = ICUToken(token).burnByAgent(_contributor, _tokens); } function updateLockPeriod(uint256 _time) public { require(msg.sender == address(strategy)); ICUToken(token).setUnlockTime(_time); } } /// @title TokenAllocator /// @author Applicature /// @notice Contract responsible for defining distribution logic of tokens. /// @dev Base class contract TokenAllocator is Ownable { mapping(address => bool) public crowdsales; modifier onlyCrowdsale() { require(crowdsales[msg.sender]); _; } function addCrowdsales(address _address) public onlyOwner { crowdsales[_address] = true; } function removeCrowdsales(address _address) public onlyOwner { crowdsales[_address] = false; } function isInitialized() public view returns (bool) { return false; } function allocate(address _holder, uint256 _tokens) public onlyCrowdsale() { internalAllocate(_holder, _tokens); } function tokensAvailable() public view returns (uint256); function internalAllocate(address _holder, uint256 _tokens) internal onlyCrowdsale(); } /// @title MintableTokenAllocator /// @author Applicature /// @notice Contract responsible for defining distribution logic of tokens. /// @dev implementation contract MintableTokenAllocator is TokenAllocator { using SafeMath for uint256; MintableToken public token; constructor(MintableToken _token) public { require(address(0) != address(_token)); token = _token; } /// @notice update instance of MintableToken function setToken(MintableToken _token) public onlyOwner { token = _token; } function internalAllocate(address _holder, uint256 _tokens) internal { token.mint(_holder, _tokens); } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public view returns (bool) { return token.mintingAgents(this); } /// @return available tokens function tokensAvailable() public view returns (uint256) { return token.availableTokens(); } } /// @title ContributionForwarder /// @author Applicature /// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale. /// @dev Base class contract ContributionForwarder { using SafeMath for uint256; uint256 public weiCollected; uint256 public weiForwarded; event ContributionForwarded(address receiver, uint256 weiAmount); function isInitialized() public view returns (bool) { return false; } /// @notice transfer wei to receiver function forward() public payable { require(msg.value > 0); weiCollected += msg.value; internalForward(); } function internalForward() internal; } /// @title DistributedDirectContributionForwarder /// @author Applicature /// @notice Contract is responsible for distributing collected ethers, that are received from CrowdSale. /// @dev implementation contract DistributedDirectContributionForwarder is ContributionForwarder { Receiver[] public receivers; uint256 public proportionAbsMax; bool public isInitialized_; struct Receiver { address receiver; uint256 proportion; // abslolute value in range of 0 - proportionAbsMax uint256 forwardedWei; } constructor(uint256 _proportionAbsMax, address[] _receivers, uint256[] _proportions) public { proportionAbsMax = _proportionAbsMax; require(_receivers.length == _proportions.length); require(_receivers.length > 0); uint256 totalProportion; for (uint256 i = 0; i < _receivers.length; i++) { uint256 proportion = _proportions[i]; totalProportion = totalProportion.add(proportion); receivers.push(Receiver(_receivers[i], proportion, 0)); } require(totalProportion == proportionAbsMax); isInitialized_ = true; } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public view returns (bool) { return isInitialized_; } function internalForward() internal { uint256 transferred; for (uint256 i = 0; i < receivers.length; i++) { Receiver storage receiver = receivers[i]; uint256 value = msg.value.mul(receiver.proportion).div(proportionAbsMax); if (i == receivers.length - 1) { value = msg.value.sub(transferred); } transferred = transferred.add(value); receiver.receiver.transfer(value); emit ContributionForwarded(receiver.receiver, value); } weiForwarded = weiForwarded.add(transferred); } } contract Crowdsale { uint256 public tokensSold; enum State {Unknown, Initializing, BeforeCrowdsale, InCrowdsale, Success, Finalized, Refunding} function externalContribution(address _contributor, uint256 _wei) public payable; function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable; function getState() public view returns (State); function updateState() public; function internalContribution(address _contributor, uint256 _wei) internal; } /// @title Crowdsale /// @author Applicature /// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale. contract CrowdsaleImpl is Crowdsale, Ownable { using SafeMath for uint256; State public currentState; TokenAllocator public allocator; ContributionForwarder public contributionForwarder; PricingStrategy public pricingStrategy; CrowdsaleAgent public crowdsaleAgent; bool public finalized; uint256 public startDate; uint256 public endDate; bool public allowWhitelisted; bool public allowSigned; bool public allowAnonymous; mapping(address => bool) public whitelisted; mapping(address => bool) public signers; mapping(address => bool) public externalContributionAgents; event Contribution(address _contributor, uint256 _wei, uint256 _tokensExcludingBonus, uint256 _bonus); constructor( TokenAllocator _allocator, ContributionForwarder _contributionForwarder, PricingStrategy _pricingStrategy, uint256 _startDate, uint256 _endDate, bool _allowWhitelisted, bool _allowSigned, bool _allowAnonymous ) public { allocator = _allocator; contributionForwarder = _contributionForwarder; pricingStrategy = _pricingStrategy; startDate = _startDate; endDate = _endDate; allowWhitelisted = _allowWhitelisted; allowSigned = _allowSigned; allowAnonymous = _allowAnonymous; currentState = State.Unknown; } /// @notice default payable function function() public payable { require(allowWhitelisted || allowAnonymous); if (!allowAnonymous) { if (allowWhitelisted) { require(whitelisted[msg.sender]); } } internalContribution(msg.sender, msg.value); } /// @notice update crowdsale agent function setCrowdsaleAgent(CrowdsaleAgent _crowdsaleAgent) public onlyOwner { require(address(_crowdsaleAgent) != address(0)); crowdsaleAgent = _crowdsaleAgent; } /// @notice allows external user to do contribution function externalContribution(address _contributor, uint256 _wei) public payable { require(externalContributionAgents[msg.sender]); internalContribution(_contributor, _wei); } /// @notice update external contributor function addExternalContributor(address _contributor) public onlyOwner { externalContributionAgents[_contributor] = true; } /// @notice update external contributor function removeExternalContributor(address _contributor) public onlyOwner { externalContributionAgents[_contributor] = false; } /// @notice update whitelisting address function updateWhitelist(address _address, bool _status) public onlyOwner { whitelisted[_address] = _status; } /// @notice update signer function addSigner(address _signer) public onlyOwner { signers[_signer] = true; } /// @notice update signer function removeSigner(address _signer) public onlyOwner { signers[_signer] = false; } /// @notice allows to do signed contributions function contribute(uint8 _v, bytes32 _r, bytes32 _s) public payable { address recoveredAddress = verify(msg.sender, _v, _r, _s); require(signers[recoveredAddress]); internalContribution(msg.sender, msg.value); } /// @notice check sign function verify(address _sender, uint8 _v, bytes32 _r, bytes32 _s) public view returns (address) { bytes32 hash = keccak256(abi.encodePacked(this, _sender)); bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s); } /// @return Crowdsale state function getState() public view returns (State) { if (finalized) { return State.Finalized; } else if (allocator.isInitialized() == false) { return State.Initializing; } else if (contributionForwarder.isInitialized() == false) { return State.Initializing; } else if (pricingStrategy.isInitialized() == false) { return State.Initializing; } else if (block.timestamp < startDate) { return State.BeforeCrowdsale; } else if (block.timestamp >= startDate && block.timestamp <= endDate) { return State.InCrowdsale; } else if (block.timestamp > endDate) { return State.Success; } return State.Unknown; } /// @notice Crowdsale state function updateState() public { State state = getState(); if (currentState != state) { if (crowdsaleAgent != address(0)) { crowdsaleAgent.onStateChange(state); } currentState = state; } } function internalContribution(address _contributor, uint256 _wei) internal { require(getState() == State.InCrowdsale); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens( _contributor, tokensAvailable, tokensSold, _wei, collectedWei); require(tokens > 0 && tokens <= tokensAvailable); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokens); if (msg.value > 0) { contributionForwarder.forward.value(msg.value)(); } emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus); } } /// @title HardCappedCrowdsale /// @author Applicature /// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale. /// with hard limit contract HardCappedCrowdsale is CrowdsaleImpl { using SafeMath for uint256; uint256 public hardCap; constructor( TokenAllocator _allocator, ContributionForwarder _contributionForwarder, PricingStrategy _pricingStrategy, uint256 _startDate, uint256 _endDate, bool _allowWhitelisted, bool _allowSigned, bool _allowAnonymous, uint256 _hardCap ) public CrowdsaleImpl( _allocator, _contributionForwarder, _pricingStrategy, _startDate, _endDate, _allowWhitelisted, _allowSigned, _allowAnonymous ) { hardCap = _hardCap; } /// @return Crowdsale state function getState() public view returns (State) { State state = super.getState(); if (state == State.InCrowdsale) { if (isHardCapAchieved(0)) { return State.Success; } } return state; } function isHardCapAchieved(uint256 _value) public view returns (bool) { if (hardCap <= tokensSold.add(_value)) { return true; } return false; } function internalContribution(address _contributor, uint256 _wei) internal { require(getState() == State.InCrowdsale); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens( _contributor, tokensAvailable, tokensSold, _wei, collectedWei); require(tokens <= tokensAvailable && tokens > 0 && false == isHardCapAchieved(tokens.sub(1))); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokens); if (msg.value > 0) { contributionForwarder.forward.value(msg.value)(); } crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus); emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus); } } /// @title RefundableCrowdsale /// @author Applicature /// @notice Contract is responsible for collecting, refunding, allocating tokens during different stages of Crowdsale. /// with hard and soft limits contract RefundableCrowdsale is HardCappedCrowdsale { using SafeMath for uint256; uint256 public softCap; mapping(address => uint256) public contributorsWei; address[] public contributors; event Refund(address _holder, uint256 _wei, uint256 _tokens); constructor( TokenAllocator _allocator, ContributionForwarder _contributionForwarder, PricingStrategy _pricingStrategy, uint256 _startDate, uint256 _endDate, bool _allowWhitelisted, bool _allowSigned, bool _allowAnonymous, uint256 _softCap, uint256 _hardCap ) public HardCappedCrowdsale( _allocator, _contributionForwarder, _pricingStrategy, _startDate, _endDate, _allowWhitelisted, _allowSigned, _allowAnonymous, _hardCap ) { softCap = _softCap; } /// @return Crowdsale state function getState() public view returns (State) { State state = super.getState(); if (state == State.Success) { if (!isSoftCapAchieved(0)) { return State.Refunding; } } return state; } function isSoftCapAchieved(uint256 _value) public view returns (bool) { if (softCap <= tokensSold.add(_value)) { return true; } return false; } /// @notice refund ethers to contributor function refund() public { internalRefund(msg.sender); } /// @notice refund ethers to delegate function delegatedRefund(address _address) public { internalRefund(_address); } function internalContribution(address _contributor, uint256 _wei) internal { require(block.timestamp >= startDate && block.timestamp <= endDate); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricingStrategy.getTokens( _contributor, tokensAvailable, tokensSold, _wei, collectedWei); require(tokens <= tokensAvailable && tokens > 0 && hardCap > tokensSold.add(tokens)); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokens); // transfer only if softcap is reached if (isSoftCapAchieved(0)) { if (msg.value > 0) { contributionForwarder.forward.value(address(this).balance)(); } } else { // store contributor if it is not stored before if (contributorsWei[_contributor] == 0) { contributors.push(_contributor); } contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value); } crowdsaleAgent.onContribution(_contributor, _wei, tokensExcludingBonus, bonus); emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus); } function internalRefund(address _holder) internal { updateState(); require(block.timestamp > endDate); require(!isSoftCapAchieved(0)); require(crowdsaleAgent != address(0)); uint256 value = contributorsWei[_holder]; require(value > 0); contributorsWei[_holder] = 0; uint256 burnedTokens = crowdsaleAgent.onRefund(_holder, 0); _holder.transfer(value); emit Refund(_holder, value, burnedTokens); } } contract ICUCrowdsale is RefundableCrowdsale { uint256 public maxSaleSupply = 2350000000e18; uint256 public availableBonusAmount = 447500000e18; uint256 public usdCollected; mapping(address => uint256) public contributorBonuses; constructor( MintableTokenAllocator _allocator, DistributedDirectContributionForwarder _contributionForwarder, ICUStrategy _pricingStrategy, uint256 _startTime, uint256 _endTime ) public RefundableCrowdsale( _allocator, _contributionForwarder, _pricingStrategy, _startTime, _endTime, true, true, false, 2500000e5, //softCap 23500000e5//hardCap ) {} function updateState() public { (startDate, endDate) = ICUStrategy(pricingStrategy).getActualDates(); super.updateState(); } function claimBonuses() public { require(isSoftCapAchieved(0) && contributorBonuses[msg.sender] > 0); uint256 bonus = contributorBonuses[msg.sender]; contributorBonuses[msg.sender] = 0; allocator.allocate(msg.sender, bonus); } function addExternalContributor(address) public onlyOwner { require(false); } function isHardCapAchieved(uint256 _value) public view returns (bool) { if (hardCap <= usdCollected.add(_value)) { return true; } return false; } function isSoftCapAchieved(uint256 _value) public view returns (bool) { if (softCap <= usdCollected.add(_value)) { return true; } return false; } function internalContribution(address _contributor, uint256 _wei) internal { updateState(); require(currentState == State.InCrowdsale); ICUStrategy pricing = ICUStrategy(pricingStrategy); uint256 usdAmount = pricing.getUSDAmount(_wei); require(!isHardCapAchieved(usdAmount.sub(1))); uint256 tokensAvailable = allocator.tokensAvailable(); uint256 collectedWei = contributionForwarder.weiCollected(); uint256 tierIndex = pricing.getTierIndex(); uint256 tokens; uint256 tokensExcludingBonus; uint256 bonus; (tokens, tokensExcludingBonus, bonus) = pricing.getTokens( _contributor, tokensAvailable, tokensSold, _wei, collectedWei ); require(tokens > 0); tokensSold = tokensSold.add(tokens); allocator.allocate(_contributor, tokensExcludingBonus); if (isSoftCapAchieved(usdAmount)) { if (msg.value > 0) { contributionForwarder.forward.value(address(this).balance)(); } } else { // store contributor if it is not stored before if (contributorsWei[_contributor] == 0) { contributors.push(_contributor); } contributorsWei[_contributor] = contributorsWei[_contributor].add(msg.value); } usdCollected = usdCollected.add(usdAmount); if (availableBonusAmount > 0) { if (availableBonusAmount >= bonus) { availableBonusAmount -= bonus; } else { bonus = availableBonusAmount; availableBonusAmount = 0; } contributorBonuses[_contributor] = contributorBonuses[_contributor].add(bonus); } else { bonus = 0; } crowdsaleAgent.onContribution(pricing, tierIndex, tokensExcludingBonus, bonus); emit Contribution(_contributor, _wei, tokensExcludingBonus, bonus); } } /// @title PricingStrategy /// @author Applicature /// @notice Contract is responsible for calculating tokens amount depending on different criterias /// @dev Base class contract PricingStrategy { function isInitialized() public view returns (bool); function getTokens( address _contributor, uint256 _tokensAvailable, uint256 _tokensSold, uint256 _weiAmount, uint256 _collectedWei ) public view returns (uint256 tokens, uint256 tokensExludingBonus, uint256 bonus); function getWeis( uint256 _collectedWei, uint256 _tokensSold, uint256 _tokens ) public view returns (uint256 weiAmount, uint256 tokensBonus); } /// @title TokenDateCappedTiersPricingStrategy /// @author Applicature /// @notice Contract is responsible for calculating tokens amount depending on price in USD /// @dev implementation contract TokenDateCappedTiersPricingStrategy is PricingStrategy, Ownable { using SafeMath for uint256; uint256 public etherPriceInUSD; uint256 public capsAmount; struct Tier { uint256 tokenInUSD; uint256 maxTokensCollected; uint256 soldTierTokens; uint256 bonusTierTokens; uint256 discountPercents; uint256 minInvestInUSD; uint256 startDate; uint256 endDate; bool unsoldProcessed; uint256[] capsData; } Tier[] public tiers; uint256 public decimals; constructor( uint256[] _tiers, uint256[] _capsData, uint256 _decimals, uint256 _etherPriceInUSD ) public { decimals = _decimals; require(_etherPriceInUSD > 0); etherPriceInUSD = _etherPriceInUSD; require(_tiers.length % 6 == 0); uint256 length = _tiers.length / 6; require(_capsData.length % 2 == 0); uint256 lengthCaps = _capsData.length / 2; uint256[] memory emptyArray; for (uint256 i = 0; i < length; i++) { tiers.push( Tier( _tiers[i * 6],//tokenInUSD _tiers[i * 6 + 1],//maxTokensCollected 0,//soldTierTokens 0,//bonusTierTokens _tiers[i * 6 + 2],//discountPercents _tiers[i * 6 + 3],//minInvestInUSD _tiers[i * 6 + 4],//startDate _tiers[i * 6 + 5],//endDate false, emptyArray//capsData ) ); for (uint256 j = 0; j < lengthCaps; j++) { tiers[i].capsData.push(_capsData[i * lengthCaps + j]); } } } /// @return tier index function getTierIndex() public view returns (uint256) { for (uint256 i = 0; i < tiers.length; i++) { if ( block.timestamp >= tiers[i].startDate && block.timestamp < tiers[i].endDate && tiers[i].maxTokensCollected > tiers[i].soldTierTokens ) { return i; } } return tiers.length; } function getActualTierIndex() public view returns (uint256) { for (uint256 i = 0; i < tiers.length; i++) { if ( block.timestamp >= tiers[i].startDate && block.timestamp < tiers[i].endDate && tiers[i].maxTokensCollected > tiers[i].soldTierTokens || block.timestamp < tiers[i].startDate ) { return i; } } return tiers.length.sub(1); } /// @return actual dates function getActualDates() public view returns (uint256 startDate, uint256 endDate) { uint256 tierIndex = getActualTierIndex(); startDate = tiers[tierIndex].startDate; endDate = tiers[tierIndex].endDate; } function getTokensWithoutRestrictions(uint256 _weiAmount) public view returns ( uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus ) { if (_weiAmount == 0) { return (0, 0, 0); } uint256 tierIndex = getActualTierIndex(); tokensExcludingBonus = _weiAmount.mul(etherPriceInUSD).div(getTokensInUSD(tierIndex)); bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus); tokens = tokensExcludingBonus.add(bonus); } /// @return tokens based on sold tokens and wei amount function getTokens( address, uint256 _tokensAvailable, uint256, uint256 _weiAmount, uint256 ) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) { if (_weiAmount == 0) { return (0, 0, 0); } uint256 tierIndex = getTierIndex(); if (tierIndex == tiers.length || _weiAmount.mul(etherPriceInUSD).div(1e18) < tiers[tierIndex].minInvestInUSD) { return (0, 0, 0); } tokensExcludingBonus = _weiAmount.mul(etherPriceInUSD).div(getTokensInUSD(tierIndex)); if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(tokensExcludingBonus)) { return (0, 0, 0); } bonus = calculateBonusAmount(tierIndex, tokensExcludingBonus); tokens = tokensExcludingBonus.add(bonus); if (tokens > _tokensAvailable) { return (0, 0, 0); } } /// @return weis based on sold and required tokens function getWeis( uint256, uint256, uint256 _tokens ) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) { if (_tokens == 0) { return (0, 0); } uint256 tierIndex = getTierIndex(); if (tierIndex == tiers.length) { return (0, 0); } if (tiers[tierIndex].maxTokensCollected < tiers[tierIndex].soldTierTokens.add(_tokens)) { return (0, 0); } uint256 usdAmount = _tokens.mul(getTokensInUSD(tierIndex)).div(1e18); totalWeiAmount = usdAmount.mul(1e18).div(etherPriceInUSD); if (totalWeiAmount < uint256(1 ether).mul(tiers[tierIndex].minInvestInUSD).div(etherPriceInUSD)) { return (0, 0); } tokensBonus = calculateBonusAmount(tierIndex, _tokens); } function calculateBonusAmount(uint256 _tierIndex, uint256 _tokens) public view returns (uint256 bonus) { uint256 length = tiers[_tierIndex].capsData.length.div(2); uint256 remainingTokens = _tokens; uint256 newSoldTokens = tiers[_tierIndex].soldTierTokens; for (uint256 i = 0; i < length; i++) { if (tiers[_tierIndex].capsData[i.mul(2)] == 0) { break; } if (newSoldTokens.add(remainingTokens) <= tiers[_tierIndex].capsData[i.mul(2)]) { bonus += remainingTokens.mul(tiers[_tierIndex].capsData[i.mul(2).add(1)]).div(100); break; } else { uint256 diff = tiers[_tierIndex].capsData[i.mul(2)].sub(newSoldTokens); remainingTokens -= diff; newSoldTokens += diff; bonus += diff.mul(tiers[_tierIndex].capsData[i.mul(2).add(1)]).div(100); } } } function getTokensInUSD(uint256 _tierIndex) public view returns (uint256) { if (_tierIndex < uint256(tiers.length)) { return tiers[_tierIndex].tokenInUSD; } } function getDiscount(uint256 _tierIndex) public view returns (uint256) { if (_tierIndex < uint256(tiers.length)) { return tiers[_tierIndex].discountPercents; } } function getMinEtherInvest(uint256 _tierIndex) public view returns (uint256) { if (_tierIndex < uint256(tiers.length)) { return tiers[_tierIndex].minInvestInUSD.mul(1 ether).div(etherPriceInUSD); } } function getUSDAmount(uint256 _weiAmount) public view returns (uint256) { return _weiAmount.mul(etherPriceInUSD).div(1 ether); } /// @notice Check whether contract is initialised /// @return true if initialized function isInitialized() public view returns (bool) { return true; } /// @notice updates tier start/end dates by id function updateDates(uint8 _tierId, uint256 _start, uint256 _end) public onlyOwner() { if (_start != 0 && _start < _end && _tierId < tiers.length) { Tier storage tier = tiers[_tierId]; tier.startDate = _start; tier.endDate = _end; } } } contract ICUStrategy is TokenDateCappedTiersPricingStrategy { ICUAgent public agent; event UnsoldTokensProcessed(uint256 fromTier, uint256 toTier, uint256 tokensAmount); constructor( uint256[] _emptyArray, uint256 _etherPriceInUSD ) public TokenDateCappedTiersPricingStrategy( _emptyArray, _emptyArray, 18, _etherPriceInUSD ) { //Pre-ICO tiers.push( Tier( 0.01e5,//tokenInUSD 1000000000e18,//maxTokensCollected 0,//soldTierTokens 0,//bonusTierTokens 0,//discountPercents uint256(20).mul(_etherPriceInUSD),//minInvestInUSD | 20 ethers 1543579200,//startDate | 2018/11/30 12:00:00 PM UTC 1544184000,//endDate | 2018/12/07 12:00:00 PM UTC false, _emptyArray ) ); //ICO tiers.push( Tier( 0.01e5,//tokenInUSD 1350000000e18,//maxTokensCollected 0,//soldTierTokens 0,//bonusTierTokens 0,//discountPercents uint256(_etherPriceInUSD).div(10),//minInvestInUSD | 0.1 ether 1544443200,//startDate | 2018/12/10 12:00:00 PM UTC 1546257600,//endDate | 2018/12/31 12:00:00 PM UTC false, _emptyArray ) ); //Pre-ICO caps data tiers[0].capsData.push(1000000000e18);//cap $10,000,000 in tokens tiers[0].capsData.push(30);//bonus percents //ICO caps data tiers[1].capsData.push(400000000e18);//cap $4,000,000 in tokens tiers[1].capsData.push(20);//bonus percents tiers[1].capsData.push(800000000e18);//cap $4,000,000 in tokens tiers[1].capsData.push(10);//bonus percents tiers[1].capsData.push(1350000000e18);//cap $5,500,000 in tokens tiers[1].capsData.push(5);//bonus percents } function getArrayOfTiers() public view returns (uint256[14] tiersData) { uint256 j = 0; for (uint256 i = 0; i < tiers.length; i++) { tiersData[j++] = uint256(tiers[i].tokenInUSD); tiersData[j++] = uint256(tiers[i].maxTokensCollected); tiersData[j++] = uint256(tiers[i].soldTierTokens); tiersData[j++] = uint256(tiers[i].discountPercents); tiersData[j++] = uint256(tiers[i].minInvestInUSD); tiersData[j++] = uint256(tiers[i].startDate); tiersData[j++] = uint256(tiers[i].endDate); } } function updateTier( uint256 _tierId, uint256 _start, uint256 _end, uint256 _minInvest, uint256 _price, uint256 _discount, uint256[] _capsData, bool updateLockNeeded ) public onlyOwner() { require( _start != 0 && _price != 0 && _start < _end && _tierId < tiers.length && _capsData.length > 0 && _capsData.length % 2 == 0 ); if (updateLockNeeded) { agent.updateLockPeriod(_end); } Tier storage tier = tiers[_tierId]; tier.tokenInUSD = _price; tier.discountPercents = _discount; tier.minInvestInUSD = _minInvest; tier.startDate = _start; tier.endDate = _end; tier.capsData = _capsData; } function setCrowdsaleAgent(ICUAgent _crowdsaleAgent) public onlyOwner { agent = _crowdsaleAgent; } function updateTierState(uint256 _tierId, uint256 _soldTokens, uint256 _bonusTokens) public { require( msg.sender == address(agent) && _tierId < tiers.length && _soldTokens > 0 ); Tier storage tier = tiers[_tierId]; if (_tierId > 0 && !tiers[_tierId.sub(1)].unsoldProcessed) { Tier storage prevTier = tiers[_tierId.sub(1)]; prevTier.unsoldProcessed = true; uint256 unsold = prevTier.maxTokensCollected.sub(prevTier.soldTierTokens); tier.maxTokensCollected = tier.maxTokensCollected.add(unsold); tier.capsData[0] = tier.capsData[0].add(unsold); emit UnsoldTokensProcessed(_tierId.sub(1), _tierId, unsold); } tier.soldTierTokens = tier.soldTierTokens.add(_soldTokens); tier.bonusTierTokens = tier.bonusTierTokens.add(_bonusTokens); } function getTierUnsoldTokens(uint256 _tierId) public view returns (uint256) { if (_tierId >= tiers.length || tiers[_tierId].unsoldProcessed) { return 0; } return tiers[_tierId].maxTokensCollected.sub(tiers[_tierId].soldTierTokens); } function getUnsoldTokens() public view returns (uint256 unsoldTokens) { for (uint256 i = 0; i < tiers.length; i++) { unsoldTokens += getTierUnsoldTokens(i); } } function getCapsData(uint256 _tierId) public view returns (uint256[]) { if (_tierId < tiers.length) { return tiers[_tierId].capsData; } } } contract Referral is Ownable { using SafeMath for uint256; MintableTokenAllocator public allocator; CrowdsaleImpl public crowdsale; uint256 public constant DECIMALS = 18; uint256 public totalSupply; bool public unLimited; bool public sentOnce; mapping(address => bool) public claimed; mapping(address => uint256) public claimedBalances; constructor( uint256 _totalSupply, address _allocator, address _crowdsale, bool _sentOnce ) public { require(_allocator != address(0) && _crowdsale != address(0)); totalSupply = _totalSupply; if (totalSupply == 0) { unLimited = true; } allocator = MintableTokenAllocator(_allocator); crowdsale = CrowdsaleImpl(_crowdsale); sentOnce = _sentOnce; } function setAllocator(address _allocator) public onlyOwner { require(_allocator != address(0)); allocator = MintableTokenAllocator(_allocator); } function setCrowdsale(address _crowdsale) public onlyOwner { require(_crowdsale != address(0)); crowdsale = CrowdsaleImpl(_crowdsale); } function multivestMint( address _address, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s ) public { require(true == crowdsale.signers(verify(msg.sender, _amount, _v, _r, _s))); if (true == sentOnce) { require(claimed[_address] == false); claimed[_address] = true; } require( _address == msg.sender && _amount > 0 && (true == unLimited || _amount <= totalSupply) ); claimedBalances[_address] = claimedBalances[_address].add(_amount); if (false == unLimited) { totalSupply = totalSupply.sub(_amount); } allocator.allocate(_address, _amount); } /// @notice check sign function verify(address _sender, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(_sender, _amount)); bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(abi.encodePacked(prefix, hash)), _v, _r, _s); } } contract ICUReferral is Referral { constructor( address _allocator, address _crowdsale ) public Referral(35000000e18, _allocator, _crowdsale, true) {} function multivestMint( address _address, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s ) public { ICUCrowdsale icuCrowdsale = ICUCrowdsale(crowdsale); icuCrowdsale.updateState(); require(icuCrowdsale.isSoftCapAchieved(0) && block.timestamp > icuCrowdsale.endDate()); super.multivestMint(_address, _amount, _v, _r, _s); } } contract Stats { using SafeMath for uint256; MintableToken public token; MintableTokenAllocator public allocator; ICUCrowdsale public crowdsale; ICUStrategy public pricing; constructor( MintableToken _token, MintableTokenAllocator _allocator, ICUCrowdsale _crowdsale, ICUStrategy _pricing ) public { token = _token; allocator = _allocator; crowdsale = _crowdsale; pricing = _pricing; } function getTokens( uint256, uint256 _weiAmount ) public view returns (uint256 tokens, uint256 tokensExcludingBonus, uint256 bonus) { return pricing.getTokensWithoutRestrictions(_weiAmount); } function getWeis( uint256, uint256 _tokenAmount ) public view returns (uint256 totalWeiAmount, uint256 tokensBonus) { return pricing.getWeis(0, 0, _tokenAmount); } function getStats(uint256 _userType, uint256[7] _ethPerCurrency) public view returns ( uint256[8] stats, uint256[26] tiersData, uint256[21] currencyContr //tokensPerEachCurrency, ) { stats = getStatsData(_userType); tiersData = getTiersData(_userType); currencyContr = getCurrencyContrData(_userType, _ethPerCurrency); } function getTiersData(uint256) public view returns ( uint256[26] tiersData ) { uint256[14] memory tiers = pricing.getArrayOfTiers(); uint256 tierElements = tiers.length.div(2); uint256 j = 0; for (uint256 i = 0; i <= tierElements; i += tierElements) { tiersData[j++] = uint256(1e23).div(tiers[i]);// tokenInUSD; tiersData[j++] = 0;// tokenInWei; tiersData[j++] = uint256(tiers[i.add(1)]);// maxTokensCollected; tiersData[j++] = uint256(tiers[i.add(2)]);// soldTierTokens; tiersData[j++] = 0;// discountPercents; tiersData[j++] = 0;// bonusPercents; tiersData[j++] = uint256(tiers[i.add(4)]);// minInvestInUSD; tiersData[j++] = 0;// minInvestInWei; tiersData[j++] = 0;// maxInvestInUSD; tiersData[j++] = 0;// maxInvestInWei; tiersData[j++] = uint256(tiers[i.add(5)]);// startDate; tiersData[j++] = uint256(tiers[i.add(6)]);// endDate; tiersData[j++] = 1; } tiersData[25] = 2; } function getStatsData(uint256 _type) public view returns ( uint256[8] stats ) { _type = _type; stats[0] = token.maxSupply(); stats[1] = token.totalSupply(); stats[2] = crowdsale.maxSaleSupply(); stats[3] = crowdsale.tokensSold(); stats[4] = uint256(crowdsale.currentState()); stats[5] = pricing.getActualTierIndex(); stats[6] = pricing.getTierUnsoldTokens(stats[5]); stats[7] = pricing.getMinEtherInvest(stats[5]); } function getCurrencyContrData(uint256 _type, uint256[7] _ethPerCurrency) public view returns ( uint256[21] currencyContr ) { _type = _type; uint256 j = 0; for (uint256 i = 0; i < _ethPerCurrency.length; i++) { (currencyContr[j++], currencyContr[j++], currencyContr[j++]) = pricing.getTokensWithoutRestrictions( _ethPerCurrency[i] ); } } } contract PeriodicTokenVesting is TokenVesting { address public unreleasedHolder; uint256 public periods; constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable, address _unreleasedHolder ) public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) { require(_revocable == false || _unreleasedHolder != address(0)); periods = _periods; unreleasedHolder = _unreleasedHolder; } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration * periods) || revoked[token]) { return totalBalance; } else { uint256 periodTokens = totalBalance.div(periods); uint256 periodsOver = now.sub(start).div(duration); if (periodsOver >= periods) { return totalBalance; } return periodTokens.mul(periodsOver); } } /** * @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(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(unreleasedHolder, refund); emit Revoked(); } } contract ICUAllocation is Ownable { using SafeERC20 for ERC20Basic; using SafeMath for uint256; uint256 public constant BOUNTY_TOKENS = 47000000e18; uint256 public constant MAX_TREASURY_TOKENS = 2350000000e18; uint256 public icoEndTime; address[] public vestings; address public bountyAddress; address public treasuryAddress; bool public isBountySent; bool public isTeamSent; event VestingCreated( address _vesting, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable ); event VestingRevoked(address _vesting); constructor(address _bountyAddress, address _treasuryAddress) public { require(_bountyAddress != address(0) && _treasuryAddress != address(0)); bountyAddress = _bountyAddress; treasuryAddress = _treasuryAddress; } function setICOEndTime(uint256 _icoEndTime) public onlyOwner { icoEndTime = _icoEndTime; } function allocateBounty(MintableTokenAllocator _allocator, ICUCrowdsale _crowdsale) public onlyOwner { require(!isBountySent && icoEndTime < block.timestamp && _crowdsale.isSoftCapAchieved(0)); isBountySent = true; _allocator.allocate(bountyAddress, BOUNTY_TOKENS); } function allocateTreasury(MintableTokenAllocator _allocator) public onlyOwner { require(icoEndTime < block.timestamp, 'ICO is not ended'); require(isBountySent, 'Bounty is not sent'); require(isTeamSent, 'Team vesting is not created'); require(MAX_TREASURY_TOKENS >= _allocator.tokensAvailable(), 'Unsold tokens are not burned'); _allocator.allocate(treasuryAddress, _allocator.tokensAvailable()); } function createVesting( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, uint256 _periods, bool _revocable, address _unreleasedHolder, MintableTokenAllocator _allocator, uint256 _amount ) public onlyOwner returns (PeriodicTokenVesting) { require(icoEndTime > 0 && _amount > 0); isTeamSent = true; PeriodicTokenVesting vesting = new PeriodicTokenVesting( _beneficiary, _start, _cliff, _duration, _periods, _revocable, _unreleasedHolder ); vestings.push(vesting); emit VestingCreated(vesting, _beneficiary, _start, _cliff, _duration, _periods, _revocable); _allocator.allocate(address(vesting), _amount); return vesting; } function revokeVesting(PeriodicTokenVesting _vesting, ERC20Basic token) public onlyOwner() { _vesting.revoke(token); emit VestingRevoked(_vesting); } }
Takes actions on contribution
function onContribution( address, uint256 _tierIndex, uint256 _tokens, uint256 _bonus ) public onlyCrowdsale() { strategy.updateTierState(_tierIndex, _tokens, _bonus); }
13,111,372
pragma solidity ^ 0.4.23; import "./UniBotToken.sol"; contract Manager is Owned{ mapping(address => bool) public mapManager; function addManager(address _newManager) onlyOwner public{ mapManager[_newManager] = true; } function deleteManager(address _manager) onlyOwner public{ mapManager[_manager] = false; } modifier onlyManager { require(mapManager[msg.sender] || msg.sender == owner); _; } } //supporter can be approved kyc //owner will accept contract Supporter is Manager { mapping(address => bool) public mapSupporter; function addSupporter(address _newSupporter) onlyManager public{ mapSupporter[_newSupporter] = true; } function deleteSupporter(address _supporter) onlyManager public{ mapSupporter[_supporter] = false; } modifier onlySupporter { require(mapSupporter[msg.sender] || msg.sender == owner || mapManager[msg.sender]); _; } } contract IcoContract is Supporter{ bool public isLocked; uint public value; address public sender; UniBotToken public uniBotToken; address public tokenAddress; using SafeMath for uint; uint decimals = 18; uint minInvestPreICO = 0 ether; uint maxInvestPreICO = 1000 ether; uint minInvestICO = 0 ether; uint maxInvestICO = 100 ether; uint public maxTokenPreIco; uint public icoStartDate; uint public preIcoStartDate; uint public preIcoEndDate; uint public icoEndDate; uint softcap; uint hardcap; uint[3] public roundEndICO; uint[4] public roundBonusLocked; uint[4] public roundBonusUnlocked; uint public priceIcoLocked; uint public pricePreIcoLocked; uint public priceIcoUnlocked; uint public pricePreIcoUnlocked; bool icoEnded = false; address[] public icoLockAndUnLock; mapping(address => uint) public mapICOLU; mapping(address => bool) public kyc; mapping(address => uint) public bonus; mapping(address => uint) public bonusPreIco; mapping(address => uint) public bonusIco; mapping(address => uint) public bonusLockPreIco; mapping(address => uint) public bonusLockIco; mapping(address => uint) public bonusUnlockPreIco; mapping(address => uint) public bonusUnlockIco; mapping(address => uint) public totalCurrentEthPreIco; mapping(address => uint) public totalCurrentEthIco; mapping(address => uint) public totalEthBuyTokenLockInPreIco; mapping(address => uint) public totalEthBuyTokenUnlockInPreIco; mapping(address => uint) public totalEthBuyTokenLockInIco; mapping(address => uint) public totalEthBuyTokenUnlockInIco; event AppendAddressLU(address acc, address[] listAddress, bool result); function IcoContract(address unibotTokenAddress) public{ tokenAddress = unibotTokenAddress; uniBotToken = UniBotToken(tokenAddress); roundEndICO = [1527958800, 1523836800, 1530377999]; // 03 - 18 - 30 roundBonusLocked = [0, 20, 15, 10]; roundBonusUnlocked = [0, 15, 10, 5]; pricePreIcoUnlocked = 0.000066 ether; pricePreIcoLocked = 0.000052 ether; priceIcoUnlocked = 0.00009 ether; priceIcoLocked = 0.000082 ether; maxTokenPreIco = 1400000000 * 10 ** 18; //20% hardcap = 2450000000 * 10 ** 18; preIcoStartDate = 1525107600; //2018/05/01/ preIcoEndDate = 1527786000; //2018/06/01/ icoStartDate = 1527786001; //2018/06/01/ icoEndDate = 1530377999; //2018/06/30/ } function setIcoLockOrUnlock(address _icoContract) onlyOwner public{ bool result = true; if (_icoContract != address(0)) { uint index = icoLockAndUnLock.push(_icoContract); mapICOLU[_icoContract] = index; } else result = false; emit AppendAddressLU(_icoContract, icoLockAndUnLock, result); } function confirmListKyc(address[] list) onlySupporter public{ for (uint i = 0; i < list.length; i++) { require(list[i] != 0x0); kyc[list[i]] = true; } } function confirmKyc(address add) onlySupporter public{ kyc[add] = true; } function cancelKyc(address add) onlyManager public{ kyc[add] = false; } function switchRound(bool _isLocked, uint _value, address _address) public returns(bool success){ require((mapICOLU[msg.sender]) != 0); require(!icoEnded); uint currentTime = now; require(currentTime >= preIcoStartDate); isLocked = _isLocked; value = _value; sender = _address; require(kyc[sender]); if (currentTime <= preIcoEndDate) { //start pre ico uint total_invest_eth_pre = totalCurrentEthPreIco[sender] + value; require(total_invest_eth_pre >= minInvestPreICO && total_invest_eth_pre <= maxInvestPreICO); //check total eth if (isLocked) { processTokenLocked(true); totalCurrentEthPreIco[sender] = totalCurrentEthPreIco[sender].add(value); bonusPreIco[sender] = bonusPreIco[sender].sub(bonusLockPreIco[sender]); totalEthBuyTokenLockInPreIco[sender] = totalEthBuyTokenLockInPreIco[sender].add(value); if(totalEthBuyTokenLockInPreIco[sender] >= 500 ether){ bonusLockPreIco[sender] = totalEthBuyTokenLockInPreIco[sender].mul(10).div(100).div(pricePreIcoLocked); }else{ if(totalEthBuyTokenLockInPreIco[sender] >= 100 ether){ bonusLockPreIco[sender] = totalEthBuyTokenLockInPreIco[sender].mul(5).div(100).div(pricePreIcoLocked); } } bonusPreIco[sender] = bonusPreIco[sender].add(bonusLockPreIco[sender]); } else { processTokenUnlocked(true); totalCurrentEthPreIco[sender] = totalCurrentEthPreIco[sender].add(value); bonusPreIco[sender] = bonusPreIco[sender].sub(bonusUnlockPreIco[sender]); totalEthBuyTokenUnlockInPreIco[sender] = totalEthBuyTokenUnlockInPreIco[sender].add(value); if(totalEthBuyTokenLockInPreIco[sender] >= 500 ether){ bonusUnlockPreIco[sender] = totalEthBuyTokenLockInPreIco[sender].mul(5).div(100).div(pricePreIcoUnlocked); }else{ if(totalEthBuyTokenLockInPreIco[sender] >= 100 ether){ bonusUnlockPreIco[sender] = totalEthBuyTokenLockInPreIco[sender].mul(2).div(100).div(pricePreIcoUnlocked); } } bonusPreIco[sender] = bonusPreIco[sender].add(bonusUnlockPreIco[sender]); } } else { //start ico if (currentTime >= icoStartDate && currentTime <= icoEndDate) { uint total_invest_eth_ico = totalCurrentEthPreIco[sender] + value; require(total_invest_eth_ico >= minInvestICO && total_invest_eth_ico <= maxInvestICO); if (total_invest_eth_ico <= maxInvestICO) { //check total eth if (isLocked) { processTokenLocked(false); totalCurrentEthIco[sender] = totalCurrentEthIco[sender].add(value); bonusIco[sender] = bonusIco[sender].sub(bonusLockIco[sender]); totalEthBuyTokenLockInIco[sender] = totalEthBuyTokenLockInIco[sender].add(value); if(totalEthBuyTokenLockInIco[sender] >= 50 ether){ uniBotToken.balanceOf(sender); bonusLockIco[sender] = totalEthBuyTokenLockInIco[sender].mul(10).div(100).div(priceIcoLocked); }else{ if(totalEthBuyTokenLockInIco[sender] >= 10 ether){ bonusLockIco[sender] = totalEthBuyTokenLockInIco[sender].mul(5).div(100).div(priceIcoLocked); } } bonusIco[sender] = bonusIco[sender].add(bonusLockIco[sender]); } else { processTokenUnlocked(false); totalCurrentEthIco[sender] = totalCurrentEthIco[sender].add(value); bonusIco[sender] = bonusIco[sender].sub(bonusUnlockIco[sender]); totalEthBuyTokenUnlockInIco[sender] = totalEthBuyTokenUnlockInIco[sender].add(value); if(totalEthBuyTokenUnlockInIco[sender] >= 10 ether){ bonusUnlockIco[sender] = totalEthBuyTokenUnlockInIco[sender].mul(5).div(100).div(priceIcoUnlocked); } bonusIco[sender] = bonusIco[sender].add(bonusUnlockIco[sender]); } } else { //refund revert(); } } else { revert(); } } return true; } function processTokenLocked(bool isPreIco) internal{ uint total_token_enable = uniBotToken.getBalance(owner); if (isPreIco) { uint currentTotalTokenSold = hardcap - total_token_enable; uint amountTokenPreIco = (value * 10 ** 18).div(pricePreIcoLocked); require(currentTotalTokenSold < maxTokenPreIco); require(currentTotalTokenSold + amountTokenPreIco <= maxTokenPreIco); uniBotToken.transferToken(sender, amountTokenPreIco, true); } else { uint amountTokenIco = (value * 10 ** 18).div(priceIcoLocked); require(amountTokenIco <= total_token_enable); uint _bonusIcoTokenLocked = 0; if (now <= roundEndICO[0]) { //bonus _bonusIcoTokenLocked = roundBonusLocked[1] * amountTokenIco / 100; } else { if (now <= roundEndICO[1]) { //bonus _bonusIcoTokenLocked = roundBonusLocked[2] * amountTokenIco / 100; } else { if (now <= roundEndICO[2]) { //bonus _bonusIcoTokenLocked = roundBonusLocked[3] * amountTokenIco / 100; } else { //ico is finished! if (icoEnded == false) { icoEnded = true; } revert(); } } } uniBotToken.transferToken(sender, amountTokenIco, true); bonus[sender] += _bonusIcoTokenLocked; } } function processTokenUnlocked(bool isPreIco) internal{ uint total_token_enable = uniBotToken.getBalance(owner); if (isPreIco) { uint currentTotalTokenSold = hardcap - total_token_enable; uint amountTokenPreIco = (value * 10 ** 18).div(pricePreIcoUnlocked); require(currentTotalTokenSold < maxTokenPreIco); require(currentTotalTokenSold + amountTokenPreIco <= maxTokenPreIco); uniBotToken.transferToken(sender, amountTokenPreIco, false); } else { uint amountTokenIco = (value * 10 ** 18).div(priceIcoUnlocked); require(amountTokenIco <= total_token_enable); uint _bonusIcoTokenUnlocked = 0; if (now <= roundEndICO[0]) { _bonusIcoTokenUnlocked = roundBonusUnlocked[1] * amountTokenIco / 100; } else { if (now <= roundEndICO[1]) { _bonusIcoTokenUnlocked = roundBonusUnlocked[2] * amountTokenIco / 100; } else { if (now <= roundEndICO[2]) { _bonusIcoTokenUnlocked = roundBonusUnlocked[3] * amountTokenIco / 100; } else { //ico is finished! if (icoEnded == false) { icoEnded = true; } revert(); } } } bonus[sender] += _bonusIcoTokenUnlocked; uniBotToken.transferToken(sender, amountTokenIco, false); } } function setBonus(address _address, uint value) public onlyOwner { require(_address != 0x0); bonus[_address] = value; } function plusBonus(address _address, uint value) public onlyOwner { require(_address != 0x0); bonus[_address] += value; } function sendBonus(address _address) public onlyOwner { require(_address != 0x0); require(bonus[_address] > 0 || bonusIco[_address] > 0 || bonusPreIco[_address] > 0); uniBotToken.transferToken(_address, bonus[_address].add(bonusIco[_address]).add(bonusPreIco[_address]), false); bonus[_address] = 0; bonusIco[_address] = 0; bonusPreIco[_address] = 0; } function sendListBonusPlus(address[] list, uint[] listBonus) public onlyOwner{ require(list.length > 0); require(listBonus.length > 0); for (uint i = 0; i < list.length; i++) { if (list[i] != 0x0 && (bonus[list[i]] > 0 || listBonus[i] > 0 || bonusIco[list[i]] > 0 || bonusPreIco[list[i]]>0)) { uniBotToken.transferToken(list[i], bonus[list[i]].add(listBonus[i].mul(10 ** 18)).add(bonusIco[list[i]]).add(bonusPreIco[list[i]]), false); bonus[list[i]] = 0; bonusIco[list[i]] = 0; bonusPreIco[list[i]] = 0; } } } function sendListBonusAirdrop(address[] list, uint[] listBonus) public onlyOwner{ require(list.length > 0); require(listBonus.length > 0); for (uint i = 0; i < list.length; i++) { if (list[i] != 0x0 && listBonus[i] > 0) { uniBotToken.transferToken(list[i], listBonus[i].mul(10 ** 18), false); } } } function setDateIco(uint _preIcoStartDate, uint _preIcoEndDate, uint _icoStartDate, uint _round1_end, uint _round2_end, uint _round3_end) public onlyOwner{ require(_preIcoStartDate < _preIcoEndDate && _preIcoEndDate <= _icoStartDate && _icoStartDate < _round1_end && _round1_end < _round2_end && _round2_end < _round3_end); icoStartDate = _icoStartDate; preIcoStartDate = _preIcoStartDate; preIcoEndDate = _preIcoEndDate; roundEndICO[0] = _round1_end; roundEndICO[1] = _round2_end; roundEndICO[2] = _round3_end; icoEndDate = _round3_end; } } contract TokenUnlocked is Owned{ IcoContract public icoContractUnlocked; address public addressIcoContract; event TransferUnlock(address indexed from, address indexed to, uint eth_value, bool isLocked); event TransferEthUnlock(address indexed _to, uint amount); function TokenUnlocked(address icocontract) public{ addressIcoContract = icocontract; icoContractUnlocked = IcoContract(addressIcoContract); } function () payable public{ icoContractUnlocked.switchRound(false, msg.value, msg.sender); emit TransferUnlock(msg.sender, owner, msg.value, false); withdrawEtherToOwner(); } function withdrawEtherToOwner() public { owner.transfer(this.balance); emit TransferEthUnlock(owner, this.balance); } function setIcoContract(address icocontract) public { addressIcoContract = icocontract; icoContractUnlocked = IcoContract(addressIcoContract); } } contract TokenLocked is Owned{ IcoContract public icoContractLock; address public addressIcoContract; event TransferLock(address indexed from, address indexed to, uint eth_value, bool isLocked); event TransferEthLock(address indexed _to, uint amount); function TokenLocked(address icocontract) public{ addressIcoContract = icocontract; icoContractLock = IcoContract(addressIcoContract); } function () payable public{ icoContractLock.switchRound(true, msg.value, msg.sender); emit TransferLock(msg.sender, owner, msg.value, true); withdrawEtherToOwner(); } function withdrawEtherToOwner() public { owner.transfer(this.balance); emit TransferEthLock(owner, this.balance); } function setIcoContract(address icocontract) public { addressIcoContract = icocontract; icoContractLock = IcoContract(addressIcoContract); } }
bonusbonusbonusico is finished!
function processTokenLocked(bool isPreIco) internal{ uint total_token_enable = uniBotToken.getBalance(owner); if (isPreIco) { uint currentTotalTokenSold = hardcap - total_token_enable; uint amountTokenPreIco = (value * 10 ** 18).div(pricePreIcoLocked); require(currentTotalTokenSold < maxTokenPreIco); require(currentTotalTokenSold + amountTokenPreIco <= maxTokenPreIco); uniBotToken.transferToken(sender, amountTokenPreIco, true); uint amountTokenIco = (value * 10 ** 18).div(priceIcoLocked); require(amountTokenIco <= total_token_enable); uint _bonusIcoTokenLocked = 0; if (now <= roundEndICO[0]) { _bonusIcoTokenLocked = roundBonusLocked[1] * amountTokenIco / 100; if (now <= roundEndICO[1]) { _bonusIcoTokenLocked = roundBonusLocked[2] * amountTokenIco / 100; if (now <= roundEndICO[2]) { _bonusIcoTokenLocked = roundBonusLocked[3] * amountTokenIco / 100; if (icoEnded == false) { icoEnded = true; } revert(); } } } uniBotToken.transferToken(sender, amountTokenIco, true); bonus[sender] += _bonusIcoTokenLocked; } }
2,477,778
// SPDX-License-Identifier: Unlicensed pragma solidity 0.7.6; // ============ Contract information ============ /** * @title InterestRateSwapFactory * @notice A deployment contract for Greenwood basis swap pools * @author Greenwood Labs */ // ============ Imports ============ import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import './libraries/FactoryUtils.sol'; contract Factory { using SafeMath for uint256; using SafeERC20 for IERC20; // ============ Immutable storage ============ address private immutable governance; // ============ Mutable storage ============ mapping(address => mapping(uint256 => mapping(uint256 => mapping(uint256 => mapping(uint256 => address))))) public getPool; mapping(uint256 => bool) public swapDurations; mapping(uint256 => bool) public protocols; mapping(uint256 => mapping(address => bool)) public protocolMarkets; mapping(uint256 => address) public protocolAdapters; mapping(address => uint256) public underlierDecimals; mapping(address => Params) public getParamsByPool; address[] public allPools; uint256 public swapDurationCount; uint256 public protocolCount; uint256 public protocolMarketCount; bool public isPaused; // ============ Structs ============ struct Params { uint256 durationInSeconds; uint256 position; uint256 protocol0; uint256 protocol1; address underlier; } struct FeeParams { uint256 rateLimit; uint256 rateSensitivity; uint256 utilizationInflection; uint256 rateMultiplier; } // ============ Events ============ event PoolCreated( uint256 durationInSeconds, address pool, uint256 position, uint256[] protocols, address indexed underlier, uint256 poolLength ); // ============ Constructor ============ constructor( address _governance ) { governance = _governance; } // ============ Modifiers ============ modifier onlyGovernance { // assert that the caller is governance require(msg.sender == governance); _; } // ============ External methods ============ // ============ Get the number of created pools ============ function allPoolsLength() external view returns (uint256) { // return the length of the allPools array return allPools.length; } // ============ Pause and unpause the factory ============ function togglePause() external onlyGovernance() returns (bool){ // toggle the value of isPaused isPaused = !isPaused; return true; } // ============ Update the supported swap durations ============ function updateSwapDurations( uint256 _duration, bool _is_supported ) external onlyGovernance() returns (bool){ // get the initial value bool initialValue = swapDurations[_duration]; // update the swapDurations mapping swapDurations[_duration] = _is_supported; // check if a swapDuration is being added if (initialValue == false && _is_supported == true) { // increment the swapDurationCount swapDurationCount = swapDurationCount.add(1); } // check if a swapDuration is being removed else if (initialValue == true && _is_supported == false) { // decrement the swapDurationCount swapDurationCount = swapDurationCount.sub(1); } return true; } // ============ Update the supported protocols ============ function updateProtocols( uint256 _protocol, bool _is_supported ) external onlyGovernance() returns (bool){ // get the initial value bool initialValue = protocols[_protocol]; // update the protocols mapping protocols[_protocol] = _is_supported; // check if a protocol is being added if (initialValue == false && _is_supported == true) { // increment the protocolCount protocolCount = protocolCount.add(1); } // check if a protocol is being removed else if (initialValue == true && _is_supported == false) { // decrement the protocolCount protocolCount = protocolCount.sub(1); } return true; } // ============ Update the supported protocol markets ============ function updateProtocolMarkets( uint256 _protocol, address _market, bool _is_supported ) external onlyGovernance() returns (bool){ // get the initial value bool initialValue = protocolMarkets[_protocol][_market]; // update the protocolMarkets mapping protocolMarkets[_protocol][_market] = _is_supported; // check if a protocol market is being added if (initialValue == false && _is_supported == true) { // increment the protocolMarketCount protocolMarketCount = protocolMarketCount.add(1); } // check if a protocol market is being removed else if (initialValue == true && _is_supported == false) { // decrement the protocolMarketCount protocolMarketCount = protocolMarketCount.sub(1); } return true; } // ============ Update the protocol adapters mapping ============ function updateProtocolAdapters( uint256 _protocol, address _adapter ) external onlyGovernance() returns(bool) { // update the protocolMarkets mapping protocolAdapters[_protocol] = _adapter; return true; } // ============ Update the underlier decimals mapping ============ function updateUnderlierDecimals ( address _underlier, uint256 _decimals ) external onlyGovernance() returns (bool) { require(_decimals <= 18, '20'); // update the underlierDecimals mapping underlierDecimals[_underlier] = _decimals; return true; } // ============ Create a new pool ============ function createPool( uint256 _duration, uint256 _position, uint256[] memory _protocols, address _underlier, uint256 _initialDeposit, uint256 _rateLimit, uint256 _rateSensitivity, uint256 _utilizationInflection, uint256 _rateMultiplier ) external returns (address pool) { // assert that the factory is not paused require(isPaused == false, '1'); // assert that the duration of the swap is supported require(swapDurations[_duration] == true, '2'); // assert that the position is supported require(_position == 0 || _position == 1, '3'); // assert that the protocols are not the same require(_protocols[0] != _protocols[1], '4'); // assert that both protocols are supported require(protocols[_protocols[0]] && protocols[_protocols[1]], '4'); // assert that the specified protocols support the specified underlier require(protocolMarkets[_protocols[0]][_underlier] && protocolMarkets[_protocols[1]][_underlier], '5'); // assert that the pool has not already been created require(getPool[_underlier][_protocols[0]][_protocols[1]][_duration][_position] == address(0), '6'); // assert that the adapter for the specified protocol0 is defined require(protocolAdapters[_protocols[0]] != address(0), '7'); // assert that the adapter for the specified protocol1 is defined require(protocolAdapters[_protocols[1]] != address(0), '7'); // assert that the decimals for the underlier is defined require(underlierDecimals[_underlier] != 0, '8'); FeeParams memory feeParams; bytes memory initCode; bytes32 salt; // scope to avoid stack too deep errors { feeParams = FeeParams( _rateLimit, _rateSensitivity, _utilizationInflection, _rateMultiplier ); } // scope to avoid stack too deep errors { // generate byte code (bytes memory encodedParams, bytes memory encodedPackedParams) = _generateByteCode( _duration, _position, _protocols, _underlier, _initialDeposit, feeParams ); // generate the init code initCode = FactoryUtils.generatePoolInitCode(encodedParams); // generate the salt salt = keccak256(encodedPackedParams); } // get the address of the pool assembly { pool := create2(0, add(initCode, 32), mload(initCode), salt) } // add the pool to the registry getPool[_underlier][_protocols[0]][_protocols[1]][_duration][_position] = pool; getParamsByPool[pool] = Params(_duration, _position, _protocols[0], _protocols[1], _underlier); allPools.push(pool); // transfer the initial deposit into the pool IERC20(_underlier).safeTransferFrom( msg.sender, pool, _initialDeposit ); // emit a PoolCreated event emit PoolCreated( _duration, pool, _position, _protocols, _underlier, allPools.length ); } // ============ Internal functions ============ // ============ Generates byte code for pool creation ============ function _generateByteCode( uint256 _duration, uint256 _position, uint256[] memory _protocols, address _underlier, uint256 _initialDeposit, FeeParams memory feeParams ) internal view returns (bytes memory encodedParams, bytes memory encodedPackedParams) { // create the initcode encodedParams = abi.encode( _underlier, underlierDecimals[_underlier], protocolAdapters[_protocols[0]], protocolAdapters[_protocols[1]], _protocols[0], _protocols[1], _position, _duration, _initialDeposit, feeParams.rateLimit, feeParams.rateSensitivity, feeParams.utilizationInflection, feeParams.rateMultiplier, msg.sender ); // create the salt encodedPackedParams = abi.encodePacked( _underlier, underlierDecimals[_underlier], protocolAdapters[_protocols[0]], protocolAdapters[_protocols[1]], _protocols[0], _protocols[1], _position, _duration, _initialDeposit, feeParams.rateLimit, feeParams.rateSensitivity, feeParams.utilizationInflection, feeParams.rateMultiplier, msg.sender ); } } // 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.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; 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: Unlicensed pragma solidity 0.7.6; import '../Pool.sol'; library FactoryUtils { function generatePoolInitCode(bytes memory encodedParams) external pure returns (bytes memory) { // generate the init code return abi.encodePacked( type(Pool).creationCode, encodedParams ); } } // 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: Unlicensed pragma solidity 0.7.6; // ============ Contract information ============ /** * @title Interest Rate Swaps V1 * @notice A pool for Interest Rate Swaps * @author Greenwood Labs */ // ============ Imports ============ import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/math/Math.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '../interfaces/IPool.sol'; import '../interfaces/IAdapter.sol'; import '../interfaces/IGreenwoodERC20.sol'; import './GreenwoodERC20.sol'; contract Pool is IPool, GreenwoodERC20 { // ============ Import usage ============ using SafeMath for uint256; using SafeERC20 for IERC20; // ============ Immutable storage ============ address private constant GOVERNANCE = 0xe3D5260Cd7F8a4207f41C3B2aC87882489f97213; uint256 private constant TEN_EXP_18 = 1000000000000000000; uint256 private constant STANDARD_DECIMALS = 18; uint256 private constant BLOCKS_PER_DAY = 6570; // 13.15 seconds per block uint256 private constant MAX_TO_PAY_BUFFER_NUMERATOR = 10; uint256 private constant MAX_TO_PAY_BUFFER_DENOMINATOR = 100; uint256 private constant DAYS_PER_YEAR = 360; // ============ Mutable storage ============ address private factory; address public adapter0; address public adapter1; address public underlier; uint256 public protocol0; uint256 public protocol1; uint256 public totalSwapCollateral; uint256 public totalSupplementaryCollateral; uint256 public totalActiveLiquidity; uint256 public totalAvailableLiquidity; uint256 public utilization; uint256 public totalFees; uint256 public fee; uint256 public direction; uint256 public durationInDays; uint256 public underlierDecimals; uint256 public decimalDifference; uint256 public rateLimit; uint256 public rateSensitivity; uint256 public utilizationInflection; uint256 public rateMultiplier; uint256 public maxDepositLimit; mapping(bytes32 => Swap) public swaps; mapping(address => uint256) public swapNumbers; mapping(address => uint256) public liquidityProviderLastDeposit; // ============ Structs ============ struct Swap { address user; bool isClosed; uint256 notional; uint256 swapCollateral; uint256 activeLiquidity; uint256 openBlock; uint256 underlierProtocol0BorrowIndex; uint256 underlierProtocol1BorrowIndex; } // ============ Modifiers ============ // None // ============ Events ============ event OpenSwap(address indexed user, uint256 notional, uint256 activeLiquidity, uint256 swapFee); event CloseSwap(address indexed user, uint256 notional, uint256 userToPay, uint256 ammToPay); event DepositLiquidity(address indexed user, uint256 liquidityAmount); event WithdrawLiquidity(address indexed user, uint256 liquidityAmount, uint256 feesAccrued); event Liquidate(address indexed liquidator, address indexed user, uint256 swapNumber, uint256 liquidatorReward); event Mint(address indexed user, uint256 underlyingTokenAmount, uint256 liquidityTokenAmount); event Burn(address indexed user, uint256 underlyingTokenAmount, uint256 liquidityTokenAmount); // ============ Constructor ============ constructor( address _underlier, uint256 _underlierDecimals, address _adapter0, address _adapter1, uint256 _protocol0, uint256 _protocol1, uint256 _direction, uint256 _durationInDays, uint256 _initialDeposit, uint256 _rateLimit, uint256 _rateSensitivity, uint256 _utilizationInflection, uint256 _rateMultiplier, address _poolDeployer ) { // assert that the pool can be initialized with a non-zero amount require(_initialDeposit > 0, 'Initial token amount must be greater than 0'); // initialize the pool factory = msg.sender; underlier = _underlier; underlierDecimals = _underlierDecimals; direction = _direction; durationInDays = _durationInDays; adapter0 = _adapter0; adapter1 = _adapter1; protocol0 = _protocol0; protocol1 = _protocol1; // calculate difference in decimals between underlier and STANDARD_DECIMALS decimalDifference = _calculatedDecimalDifference(underlierDecimals, STANDARD_DECIMALS); // adjust the token decimals to the standard number uint256 adjustedInitialDeposit = _convertToStandardDecimal(_initialDeposit); totalAvailableLiquidity = adjustedInitialDeposit; rateLimit = _rateLimit; rateSensitivity = _rateSensitivity; utilizationInflection = _utilizationInflection; rateMultiplier = _rateMultiplier; maxDepositLimit = 1000000000000000000000000; // calculate the initial swap fee fee = _calculateFee(); // Update the pool deployer's deposit block number liquidityProviderLastDeposit[_poolDeployer] = block.number; // mint LP tokens to the pool deployer _mintLPTokens(_poolDeployer, adjustedInitialDeposit); } // ============ Opens a new basis swap ============ function openSwap(uint256 _notional) external override returns (bool) { // assert that a swap is opened with an non-zero notional require(_notional > 0, '9'); // adjust notional to standard decimal places uint256 adjustedNotional = _convertToStandardDecimal(_notional); // calculate the swap collateral and trade active liquidity based off the notional (uint256 swapCollateral, uint256 activeLiquidity) = _calculateSwapCollateralAndActiveLiquidity(adjustedNotional); // assert that there is sufficient liquidity to open this swap require(activeLiquidity <= totalAvailableLiquidity, '10'); // assign the supplementary collateral uint256 supplementaryCollateral = activeLiquidity; // calculate the fee based on swap collateral uint256 swapFee = swapCollateral.mul(fee).div(TEN_EXP_18); // calculate the current borrow index for the underlier on protocol 0 uint256 underlierProtocol0BorrowIndex = IAdapter(adapter0).getBorrowIndex(underlier); // calculate the current borrow index for the underlier on protocol 1 uint256 underlierProtocol1BorrowIndex = IAdapter(adapter1).getBorrowIndex(underlier); // create the swap struct Swap memory swap = Swap( msg.sender, false, adjustedNotional, swapCollateral, activeLiquidity, block.number, underlierProtocol0BorrowIndex, underlierProtocol1BorrowIndex ); // create a swap key by hashing together the user and their current swap number bytes32 swapKey = keccak256(abi.encode(msg.sender, swapNumbers[msg.sender])); swaps[swapKey] = swap; // update the user's swap number swapNumbers[msg.sender] = swapNumbers[msg.sender].add(1); // update the total active liquidity totalActiveLiquidity = totalActiveLiquidity.add(activeLiquidity); // update the total swap collateral totalSwapCollateral = totalSwapCollateral.add(swapCollateral); // update the total supplementary collateral totalSupplementaryCollateral = totalSupplementaryCollateral.add(supplementaryCollateral); // update the total available liquidity totalAvailableLiquidity = totalAvailableLiquidity.sub(activeLiquidity); // update the total fees accrued totalFees = totalFees.add(swapFee); // the total amount to debit the user (swap collateral + fee + the supplementary collateral) uint256 amountToDebit = swapCollateral.add(fee).add(supplementaryCollateral); // calculate the new pool utilization utilization = _calculateUtilization(); // calculate the new fixed interest rate fee = _calculateFee(); // transfer underlier from the user IERC20(underlier).safeTransferFrom( msg.sender, address(this), _convertToUnderlierDecimal(amountToDebit) ); // emit an open swap event emit OpenSwap(msg.sender, adjustedNotional, activeLiquidity, swapFee); // return true on successful open swap return true; } // ============ Closes an interest rate swap ============ function closeSwap(uint256 _swapNumber) external override returns (bool) { // the key of the swap bytes32 swapKey = keccak256(abi.encode(msg.sender, _swapNumber)); // assert that a swap exists for this user require(swaps[swapKey].user == msg.sender, '11'); // assert that this swap has not already been closed require(!swaps[swapKey].isClosed, '12'); // get the swap to be closed Swap memory swap = swaps[swapKey]; // the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap (uint256 userToPay, uint256 ammToPay) = _calculateInterestAccrued(swap); // assert that the swap cannot be closed in the same block that it was opened require(block.number > swap.openBlock, '13'); // the total payout for this swap uint256 payout = userToPay > ammToPay ? userToPay.sub(ammToPay) : ammToPay.sub(userToPay); // the supplementary collateral of this swap uint256 supplementaryCollateral = swap.activeLiquidity; // the active liquidity recovered upon closure of this swap uint256 activeLiquidityRecovered; // the amount to reward the user upon closing of the swap uint256 redeemableFunds; // the user won the swap if (ammToPay > userToPay) { // ensure the payout does not exceed the active liquidity for this swap payout = Math.min(payout, swap.activeLiquidity); // active liquidity recovered is the the total active liquidity reduced by the user's payout activeLiquidityRecovered = swap.activeLiquidity.sub(payout); // User can redeem all of swap collateral, all of supplementary collateral, and the payout redeemableFunds = swap.swapCollateral.add(supplementaryCollateral).add(payout); } // the AMM won the swap else if (ammToPay < userToPay) { // ensure the payout does not exceed the swap collateral for this swap payout = Math.min(payout, swap.swapCollateral); // active liquidity recovered is the the total active liquidity increased by the amm's payout activeLiquidityRecovered = swap.activeLiquidity.add(payout); // user can redeem all of swap collateral, all of supplementary collateral, with the payout subtracted redeemableFunds = swap.swapCollateral.add(supplementaryCollateral).sub(payout); } // neither party won the swap else { // active liquidity recovered is the the initial active liquidity for the trade activeLiquidityRecovered = swap.activeLiquidity; // user can redeem all of swap collateral and all of supplementary collateral redeemableFunds = swap.swapCollateral.add(supplementaryCollateral); } // update the total active liquidity totalActiveLiquidity = totalActiveLiquidity.sub(swap.activeLiquidity); // update the total swap collateral totalSwapCollateral = totalSwapCollateral.sub(swap.swapCollateral); // update the total supplementary collateral totalSupplementaryCollateral = totalSupplementaryCollateral.sub(supplementaryCollateral); // update the total available liquidity totalAvailableLiquidity = totalAvailableLiquidity.add(activeLiquidityRecovered); // close the swap swaps[swapKey].isClosed = true; // calculate the new pool utilization utilization = _calculateUtilization(); // calculate the new fee fee = _calculateFee(); // transfer redeemable funds to the user IERC20(underlier).safeTransfer( msg.sender, _convertToUnderlierDecimal(redeemableFunds) ); // emit a close swap event emit CloseSwap(msg.sender, swap.notional, userToPay, ammToPay); return true; } // ============ Deposit liquidity into the pool ============ function depositLiquidity(uint256 _liquidityAmount) external override returns (bool) { // adjust liquidity amount to standard decimals uint256 adjustedLiquidityAmount = _convertToStandardDecimal(_liquidityAmount); // asert that liquidity amount must be greater than 0 and amount to less than the max deposit limit require(adjustedLiquidityAmount > 0 && adjustedLiquidityAmount.add(totalActiveLiquidity).add(totalAvailableLiquidity) <= maxDepositLimit, '14'); // transfer the specified amount of underlier into the pool IERC20(underlier).safeTransferFrom(msg.sender, address(this), _liquidityAmount); // add to the total available liquidity in the pool totalAvailableLiquidity = totalAvailableLiquidity.add(adjustedLiquidityAmount); // update the most recent deposit block of the liquidity provider liquidityProviderLastDeposit[msg.sender] = block.number; // calculate the new pool utilization utilization = _calculateUtilization(); // calculate the new fee fee = _calculateFee(); // mint LP tokens to the liiquidity provider _mintLPTokens(msg.sender, adjustedLiquidityAmount); // emit deposit liquidity event emit DepositLiquidity(msg.sender, adjustedLiquidityAmount); return true; } // ============ Withdraw liquidity from the pool ============ function withdrawLiquidity(uint256 _liquidityTokenAmount) external override returns (bool) { // assert that withdrawal does not occur in the same block as a deposit require(liquidityProviderLastDeposit[msg.sender] < block.number, '19'); // asert that liquidity amount must be greater than 0 require(_liquidityTokenAmount > 0, '14'); // transfer the liquidity tokens from sender to the pool IERC20(address(this)).safeTransferFrom(msg.sender, address(this), _liquidityTokenAmount); // determine the amount of underlying tokens that the liquidity tokens can be redeemed for uint256 redeemableUnderlyingTokens = calculateLiquidityTokenValue(_liquidityTokenAmount); // assert that there is enough available liquidity to safely withdraw this amount require(totalAvailableLiquidity >= redeemableUnderlyingTokens, '10'); // the fees that this withdraw will yield (total fees accrued * withdraw amount / total liquidity provided) uint256 feeShare = totalFees.mul(redeemableUnderlyingTokens).div(totalActiveLiquidity.add(totalAvailableLiquidity)); // update the total fees remaining in the pool totalFees = totalFees.sub(feeShare); // remove the withdrawn amount from the total available liquidity in the pool totalAvailableLiquidity = totalAvailableLiquidity.sub(redeemableUnderlyingTokens); // calculate the new pool utilization utilization = _calculateUtilization(); // calculate the new fee fee = _calculateFee(); // mint LP tokens to the liiquidity provider _burnLPTokens(msg.sender, _liquidityTokenAmount); // emit withdraw liquidity event emit WithdrawLiquidity(msg.sender, redeemableUnderlyingTokens, feeShare); return true; } // ============ Liquidate a swap that has expired ============ function liquidate(address _user, uint256 _swapNumber) external override returns (bool) { // the key of the swap bytes32 swapKey = keccak256(abi.encode(_user, _swapNumber)); // assert that a swap exists for this user require(swaps[swapKey].user == _user, '11'); // get the swap to be liquidated Swap memory swap = swaps[swapKey]; // assert that the swap has not already been closed require(!swap.isClosed, '12'); // the expiration block of the swap uint256 expirationBlock = swap.openBlock.add(durationInDays.mul(BLOCKS_PER_DAY)); // assert that the swap has eclipsed the expiration block require(block.number >= expirationBlock, '17'); // transfer trade active liquidity from the liquidator IERC20(underlier).safeTransferFrom( msg.sender, address(this), _convertToUnderlierDecimal(swap.activeLiquidity) ); // the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap (uint256 userToPay, uint256 ammToPay) =_calculateInterestAccrued(swap); // the total payout for this swap uint256 payout = userToPay > ammToPay ? userToPay.sub(ammToPay) : ammToPay.sub(userToPay); // the supplementary collateral of this swap uint256 supplementaryCollateral = swap.activeLiquidity; // the active liquidity recovered upon liquidation of this swap uint256 activeLiquidityRecovered; // the amount to reward the liquidator upon liquidation of the swap uint256 liquidatorReward; // the user won the swap if (ammToPay > userToPay) { // ensure the payout does not exceed the active liquidity for this swap payout = Math.min(payout, swap.activeLiquidity); // active liquidity recovered is the the total active liquidity increased by the user's unclaimed payout activeLiquidityRecovered = swap.activeLiquidity.add(payout); // liquidator is rewarded the supplementary collateral and the difference between the swap collateral and the payout liquidatorReward = supplementaryCollateral.add(swap.swapCollateral).sub(payout); } // the AMM won the swap else if (ammToPay < userToPay) { // ensure the payout does not exceed the swap collateral for this swap payout = Math.min(payout, swap.swapCollateral); // active liquidity recovered is the the total active liquidity increased by the entire swap collateral activeLiquidityRecovered = swap.activeLiquidity.add(swap.swapCollateral); // liquidator is rewarded all of the supplementary collateral liquidatorReward = supplementaryCollateral; } // neither party won the swap else { // active liquidity recovered is the the total active liquidity for this swap activeLiquidityRecovered = swap.activeLiquidity; // liquidator is rewarded all of the supplementary collateral and the swap collateral liquidatorReward = supplementaryCollateral.add(swap.swapCollateral); } // update the total active liquidity totalActiveLiquidity = totalActiveLiquidity.sub(swap.activeLiquidity); // update the total swap collateral totalSwapCollateral = totalSwapCollateral.sub(swap.swapCollateral); // update the total supplementary collateral totalSupplementaryCollateral = totalSupplementaryCollateral.sub(supplementaryCollateral); // update the total available liquidity totalAvailableLiquidity = totalAvailableLiquidity.add(activeLiquidityRecovered); // close the swap swaps[swapKey].isClosed = true; // calculate the new pool utilization utilization = _calculateUtilization(); // calculate the new fee fee = _calculateFee(); // transfer liquidation reward to the liquidator IERC20(underlier).safeTransfer( msg.sender, _convertToUnderlierDecimal(liquidatorReward) ); // emit liquidate event emit Liquidate(msg.sender, _user, _swapNumber, liquidatorReward); return true; } // ============ External view for the interest accrued on a variable rate ============ function calculateVariableInterestAccrued(uint256 _notional, uint256 _protocol, uint256 _borrowIndex) external view override returns (uint256) { return _calculateVariableInterestAccrued(_notional, _protocol, _borrowIndex); } // ============ Calculates the current variable rate for the underlier on a particular protocol ============ function calculateVariableRate(uint256 _protocol) external view returns (uint256) { // the adapter to use given the particular protocol address adapter = _protocol == protocol0 ? adapter0 : adapter1; // use the current variable rate for the underlying token uint256 variableRate = IAdapter(adapter).getBorrowRate(underlier); return variableRate; } function changeMaxDepositLimit(uint256 _limit) external { // assert that only governance can adjust the deposit limit require(msg.sender == GOVERNANCE, '18'); // change the deposit limit maxDepositLimit = _limit; } // ============ Calculates the current approximate value of liquidity tokens denoted in the underlying token ============ function calculateLiquidityTokenValue(uint256 liquidityTokenAmount) public view returns (uint256 redeemableUnderlyingTokens) { // get the total underlying token balance in this pool with supplementary and swap collateral amounts excluded uint256 adjustedUnderlyingTokenBalance = _convertToStandardDecimal(IERC20(underlier).balanceOf(address(this))) .sub(totalSwapCollateral) .sub(totalSupplementaryCollateral); // the total supply of LP tokens in circulation uint256 _totalSupply = totalSupply(); // determine the amount of underlying tokens that the liquidity tokens can be redeemed for redeemableUnderlyingTokens = liquidityTokenAmount.mul(adjustedUnderlyingTokenBalance).div(_totalSupply); } // ============ Calculates the max variable rate to pay ============ function calculateMaxVariableRate(address adapter) external view returns (uint256) { return _calculateMaxVariableRate(adapter); } // ============ Internal methods ============ // ============ Mints LP tokens to users that deposit liquidity to the protocol ============ function _mintLPTokens(address to, uint256 underlyingTokenAmount) internal { // the total supply of LP tokens in circulation uint256 _totalSupply = totalSupply(); // determine the amount of LP tokens to mint uint256 mintableLiquidity; if (_totalSupply == 0) { // initialize the supply of LP tokens mintableLiquidity = underlyingTokenAmount; } else { // get the total underlying token balance in this pool uint256 underlyingTokenBalance = _convertToStandardDecimal(IERC20(underlier).balanceOf(address(this))); // adjust the underlying token balance to standardize the decimals // the supplementary collateral, swap collateral, and newly added liquidity amounts are excluded uint256 adjustedUnderlyingTokenBalance = underlyingTokenBalance .sub(totalSwapCollateral) .sub(totalSupplementaryCollateral) .sub(underlyingTokenAmount); // mint a proportional amount of LP tokens mintableLiquidity = underlyingTokenAmount.mul(_totalSupply).div(adjustedUnderlyingTokenBalance); } // assert that enough liquidity tokens are available to be minted require(mintableLiquidity > 0, 'INSUFFICIENT_LIQUIDITY_MINTED'); // mint the tokens directly to the LP _mint(to, mintableLiquidity); // emit minting of LP token event emit Mint(to, underlyingTokenAmount, mintableLiquidity); } // ============ Burns LP tokens and sends users the equivalent underlying tokens in return ============ function _burnLPTokens(address to, uint256 liquidityTokenAmount) internal { // determine the amount of underlying tokens that the liquidity tokens can be redeemed for uint256 redeemableUnderlyingTokens = calculateLiquidityTokenValue(liquidityTokenAmount); // assert that enough underlying tokens are available to send to the redeemer require(redeemableUnderlyingTokens > 0, 'INSUFFICIENT_LIQUIDITY_BURNED'); // burn the liquidity tokens _burn(address(this), liquidityTokenAmount); // transfer the underlying tokens IERC20(underlier).safeTransfer(to, _convertToUnderlierDecimal(redeemableUnderlyingTokens)); // emit burning of LP token event emit Mint(to, redeemableUnderlyingTokens, liquidityTokenAmount); } // ============ Calculate the current pool fee ============ function _calculateFee() internal view returns (uint256) { // the new fee based on updated pool utilization uint256 newFee; // the fee offered before the utilization inflection is hit // (utilization * rate sensitivity) + rate limit int256 preInflectionLeg = int256(utilization.mul(rateSensitivity).div(TEN_EXP_18).add(rateLimit)); // pool utilization is below the inflection if (utilization < utilizationInflection) { // assert that the leg is positive before converting to uint256 require(preInflectionLeg > 0); newFee = uint256(preInflectionLeg); } // pool utilization is at or above the inflection else { // The additional change in the rate after the utilization inflection is hit // rate multiplier * (utilization - utilization inflection) int256 postInflectionLeg = int256(rateMultiplier.mul(utilization.sub(utilizationInflection)).div(TEN_EXP_18)); // assert that the addition of the legs is positive before converting to uint256 require(preInflectionLeg + postInflectionLeg > 0); newFee = uint256(preInflectionLeg + postInflectionLeg); } // adjust the fee value as a percentage return newFee.div(100); } // ============ Calculates the pool utilization ============ function _calculateUtilization() internal view returns (uint256) { // get the total liquidity of this pool uint256 totalPoolLiquidity = totalActiveLiquidity.add(totalAvailableLiquidity); // pool utilization is the total active liquidity / total pool liquidity uint256 newUtilization = totalActiveLiquidity.mul(TEN_EXP_18).div(totalPoolLiquidity); // adjust utilization to be an integer between 0 and 100 uint256 adjustedUtilization = newUtilization * 100; return adjustedUtilization; } // ============ Calculates the swap collateral and active liquidity needed for a given notional ============ function _calculateSwapCollateralAndActiveLiquidity(uint256 _notional) internal view returns (uint256, uint256) { // The maximum rate the user will pay on a swap uint256 userMaxRateToPay = direction == 0 ? _calculateMaxVariableRate(adapter0) : _calculateMaxVariableRate(adapter1); // the maximum rate the AMM will pay on a swap uint256 ammMaxRateToPay = direction == 1 ? _calculateMaxVariableRate(adapter0) : _calculateMaxVariableRate(adapter1); // notional * maximum rate to pay * (swap duration in days / days per year) uint256 swapCollateral = _calculateMaxAmountToPay(_notional, userMaxRateToPay); uint256 activeLiquidity = _calculateMaxAmountToPay(_notional, ammMaxRateToPay); return (swapCollateral, activeLiquidity); } // ============ Calculates the maximum amount to pay over a specific time window with a given notional and rate ============ function _calculateMaxAmountToPay(uint256 _notional, uint256 _rate) internal view returns (uint256) { // the period by which to adjust the rate uint256 period = DAYS_PER_YEAR.div(durationInDays); // notional * maximum rate to pay / (days per year / swap duration in days) return _notional.mul(_rate).div(TEN_EXP_18).div(period); } // ============ Calculates the maximum variable rate ============ function _calculateMaxVariableRate(address _adapter) internal view returns (uint256) { // use the current variable rate for the underlying token uint256 variableRate = IAdapter(_adapter).getBorrowRate(underlier); // calculate a variable rate buffer uint256 maxBuffer = MAX_TO_PAY_BUFFER_NUMERATOR.mul(TEN_EXP_18).div(MAX_TO_PAY_BUFFER_DENOMINATOR); // add the buffer to the current variable rate return variableRate.add(maxBuffer); } // ============ Calculates the interest accrued for both parties on a swap ============ function _calculateInterestAccrued(Swap memory _swap) internal view returns (uint256, uint256) { // the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap uint256 userToPay; uint256 ammToPay; // the fixed interest accrued on this swap uint256 protocol0VariableInterestAccrued = _calculateVariableInterestAccrued(_swap.notional, protocol0, _swap.underlierProtocol0BorrowIndex); // the variable interest accrued on this swap uint256 protocol1VariableInterestAccrued = _calculateVariableInterestAccrued(_swap.notional, protocol1, _swap.underlierProtocol1BorrowIndex); // user went long on the variable rate if (direction == 0) { userToPay = protocol0VariableInterestAccrued; ammToPay = protocol1VariableInterestAccrued; } // user went short on the variable rate else { userToPay = protocol1VariableInterestAccrued; ammToPay = protocol0VariableInterestAccrued; } return (userToPay, ammToPay); } // ============ Calculates the interest accrued on a variable rate ============ function _calculateVariableInterestAccrued(uint256 _notional, uint256 _protocol, uint256 _openSwapBorrowIndex) internal view returns (uint256) { // the adapter to use based on the protocol address adapter = _protocol == protocol0 ? adapter0 : adapter1; // get the current borrow index of the underlying asset uint256 currentBorrowIndex = IAdapter(adapter).getBorrowIndex(underlier); // The ratio between the current borrow index and the borrow index at time of open swap uint256 indexRatio = currentBorrowIndex.mul(TEN_EXP_18).div(_openSwapBorrowIndex); // notional * (current borrow index / borrow index when swap was opened) - notional return _notional.mul(indexRatio).div(TEN_EXP_18).sub(_notional); } // ============ Converts an amount to have the contract standard numfalse,ber of decimals ============ function _convertToStandardDecimal(uint256 _amount) internal view returns (uint256) { // set adjustment direction to false to convert to standard pool decimals return _convertToDecimal(_amount, true); } // ============ Converts an amount to have the underlying token's number of decimals ============ function _convertToUnderlierDecimal(uint256 _amount) internal view returns (uint256) { // set adjustment direction to true to convert to underlier decimals return _convertToDecimal(_amount, false); } // ============ Converts an amount to have a particular number of decimals ============ function _convertToDecimal(uint256 _amount, bool _adjustmentDirection) internal view returns (uint256) { // the amount after it has been converted to have the underlier number of decimals uint256 convertedAmount; // the underlying token has less decimal places if (underlierDecimals < STANDARD_DECIMALS) { convertedAmount = _adjustmentDirection ? _amount.mul(10 ** decimalDifference) : _amount.div(10 ** decimalDifference); } // there is no difference in the decimal places else { convertedAmount = _amount; } return convertedAmount; } // ============ Calculates the difference between the underlying decimals and the standard decimals ============ function _calculatedDecimalDifference(uint256 _x_decimal, uint256 _y_decimal) internal pure returns (uint256) { // the difference in decimals uint256 difference; // the second decimal is greater if (_x_decimal < _y_decimal) { difference = _y_decimal.sub(_x_decimal); } return difference; } } // 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: Unlicensed pragma solidity 0.7.6; interface IPool { function openSwap(uint256 _notional) external returns (bool); function closeSwap(uint256 _swapNumber) external returns (bool); function depositLiquidity(uint256 _liquidityAmount) external returns (bool); function withdrawLiquidity(uint256 _liquidityAmount) external returns (bool); function liquidate(address _user, uint256 _swapNumber) external returns (bool); function calculateVariableInterestAccrued(uint256 _notional, uint256 _protocol, uint256 _borrowIndex) external view returns (uint256); } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.6.12; interface IAdapter { function getBorrowIndex(address underlier) external view returns (uint256); function getBorrowRate(address underlier) external view returns (uint256); } // SPDX-License-Identifier: Unlicensed pragma solidity 0.7.6; interface IGreenwoodERC20 { function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Unlicensed pragma solidity 0.7.6; // ============ Contract information ============ /** * @title Greenwood LP token * @notice An LP token for Greenwood Basis Swaps * @author Greenwood Labs */ // ============ Imports ============ import '../interfaces/IGreenwoodERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; contract GreenwoodERC20 is IGreenwoodERC20 { // ============ Import usage ============ using SafeMath for uint256; // ============ Immutable storage ============ string public constant override name = 'Greenwood'; string public constant override symbol = 'GRN'; uint256 public constant override decimals = 18; // ============ Mutable storage ============ uint256 private _totalSupply; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; // ============ Events ============ event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); // ============ Constructor ============ constructor() {} // ============ External methods ============ // ============ Returns the amount of tokens in existence ============ function totalSupply() public view override returns (uint256) { return _totalSupply; } // ============ Returns the amount of tokens owned by `account` ============ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } // ============ Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` ============ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } // ============ Sets `amount` as the allowance of `spender` over the caller's tokens ============ function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } // ============ Moves `amount` tokens from the caller's account to `recipient` ============ function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } // ============ Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism ============ function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds allowance')); return true; } // ============ Internal methods ============ // ============ Creates `amount` tokens and assigns them to `account`, increasing the total supply ============ function _mint(address account, uint256 amount) internal { require(account != address(0), 'GreenwoodERC20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } // ============ Destroys `amount` tokens from `account`, reducing the total supply ============ function _burn(address account, uint256 amount) internal { require(account != address(0), 'GreenwoodERC20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'GreenwoodERC20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } // ============ Sets `amount` as the allowance of `spender` over the tokens of the `owner` ============ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), 'GreenwoodERC20: approve from the zero address'); require(spender != address(0), 'GreenwoodERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } // ============ Moves tokens `amount` from `sender` to `recipient` ============ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), 'GreenwoodERC20: transfer from the zero address'); require(recipient != address(0), 'GreenwoodERC20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
assert that a swap is opened with an non-zero notional adjust notional to standard decimal places calculate the swap collateral and trade active liquidity based off the notional assert that there is sufficient liquidity to open this swap assign the supplementary collateral calculate the fee based on swap collateral calculate the current borrow index for the underlier on protocol 0 calculate the current borrow index for the underlier on protocol 1 create the swap struct create a swap key by hashing together the user and their current swap number update the user's swap number update the total active liquidity update the total swap collateral update the total supplementary collateral update the total available liquidity update the total fees accrued the total amount to debit the user (swap collateral + fee + the supplementary collateral) calculate the new pool utilization calculate the new fixed interest rate transfer underlier from the user emit an open swap event return true on successful open swap
function openSwap(uint256 _notional) external override returns (bool) { require(_notional > 0, '9'); uint256 adjustedNotional = _convertToStandardDecimal(_notional); (uint256 swapCollateral, uint256 activeLiquidity) = _calculateSwapCollateralAndActiveLiquidity(adjustedNotional); require(activeLiquidity <= totalAvailableLiquidity, '10'); uint256 supplementaryCollateral = activeLiquidity; uint256 swapFee = swapCollateral.mul(fee).div(TEN_EXP_18); uint256 underlierProtocol0BorrowIndex = IAdapter(adapter0).getBorrowIndex(underlier); uint256 underlierProtocol1BorrowIndex = IAdapter(adapter1).getBorrowIndex(underlier); Swap memory swap = Swap( msg.sender, false, adjustedNotional, swapCollateral, activeLiquidity, block.number, underlierProtocol0BorrowIndex, underlierProtocol1BorrowIndex ); bytes32 swapKey = keccak256(abi.encode(msg.sender, swapNumbers[msg.sender])); swaps[swapKey] = swap; swapNumbers[msg.sender] = swapNumbers[msg.sender].add(1); totalActiveLiquidity = totalActiveLiquidity.add(activeLiquidity); totalSwapCollateral = totalSwapCollateral.add(swapCollateral); totalSupplementaryCollateral = totalSupplementaryCollateral.add(supplementaryCollateral); totalAvailableLiquidity = totalAvailableLiquidity.sub(activeLiquidity); totalFees = totalFees.add(swapFee); uint256 amountToDebit = swapCollateral.add(fee).add(supplementaryCollateral); utilization = _calculateUtilization(); fee = _calculateFee(); IERC20(underlier).safeTransferFrom( msg.sender, address(this), _convertToUnderlierDecimal(amountToDebit) ); emit OpenSwap(msg.sender, adjustedNotional, activeLiquidity, swapFee); return true; }
1,627,869
/* 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.5.7; pragma experimental "ABIEncoderV2"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { CommonMath } from "set-protocol-contract-utils/contracts/lib/CommonMath.sol"; import { CompoundUtils } from "set-protocol-contract-utils/contracts/lib/CompoundUtils.sol"; import { CTokenWhiteListed } from "./lib/CTokenWhiteListed.sol"; import { ERC20Wrapper } from "../../lib/ERC20Wrapper.sol"; import { ExchangeIssuanceLibrary } from "./lib/ExchangeIssuanceLibrary.sol"; import { ExchangeIssuanceModule } from "./ExchangeIssuanceModule.sol"; import { ICToken } from "../interfaces/ICToken.sol"; import { IAddressToAddressWhiteList } from "../interfaces/IAddressToAddressWhiteList.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { SetTokenLibrary } from "../lib/SetTokenLibrary.sol"; /** * @title CTokenExchangeIssuanceModule * @author Set Protocol * * The CTokenExchangeIssuanceModule facilitates the exchangeIssue and exchangeRedeem functions which allows * the issuance and redemption of Sets containing cTokens using exchange orders and Compound functions. * Note: This module is not compatible with Compound Ether (cETH). */ contract CTokenExchangeIssuanceModule is ExchangeIssuanceModule, CTokenWhiteListed { using SafeMath for uint256; /* ============ State Variables ============ */ // Address of transferProxy address public transferProxy; /* ============ Constructor ============ */ /** * Constructor function for CTokenExchangeIssuanceModule * * @param _core The address of Core * @param _vault The address of Vault * @param _transferProxy The address of TransferProxy * @param _cTokenWhiteList The instance of cTokenWhiteList contract */ constructor( address _core, address _vault, address _transferProxy, IAddressToAddressWhiteList _cTokenWhiteList ) public ExchangeIssuanceModule( _core, _vault ) CTokenWhiteListed( _transferProxy, _cTokenWhiteList ) { transferProxy = _transferProxy; } /* ============ Public Functions ============ */ /** * Performs trades via exchange wrappers to acquire components, mints cToken from underlying, and issues a Set to the caller * * @param _exchangeIssuanceParams A Struct containing exchange issuance metadata * @param _orderData Bytes array containing the exchange orders to execute */ function exchangeIssue( ExchangeIssuanceLibrary.ExchangeIssuanceParams memory _exchangeIssuanceParams, bytes memory _orderData ) public nonReentrant { // Validate the issuance quantity, send token and receive token data validateExchangeIssuanceParams(_exchangeIssuanceParams); // Validate that all receiveTokens are components of the Set SetTokenLibrary.validateTokensAreComponents( _exchangeIssuanceParams.setAddress, _exchangeIssuanceParams.receiveTokens ); // Transfer the send tokens to the appropriate exchanges transferSendTokensToExchangeWrappers( _exchangeIssuanceParams.sendTokenExchangeIds, _exchangeIssuanceParams.sendTokens, _exchangeIssuanceParams.sendTokenAmounts ); // Calculate expected receive token balances uint256[] memory requiredBalances = calculateReceiveTokenBalances( _exchangeIssuanceParams ); // Execute the exchange orders using the encoded order data and deposits tokens in vault executeExchangeOrders(_orderData); // Withdraw underlying tokens required from vault, mint cTokens in the module, and return to vault under sender address mintCTokensFromExchangedComponents( _exchangeIssuanceParams.receiveTokens, _exchangeIssuanceParams.receiveTokenAmounts ); // Check that sender's receive token balances in Vault are correct ExchangeIssuanceLibrary.validatePostExchangeReceiveTokenBalances( vault, _exchangeIssuanceParams.receiveTokens, requiredBalances, msg.sender ); // Transfer remaining required underlying components from caller to module, mint cTokens and deposit in vault to caller mintCTokensFromCaller( _exchangeIssuanceParams.setAddress, _exchangeIssuanceParams.quantity ); // Issue Set to the caller coreInstance.issueModule( msg.sender, msg.sender, _exchangeIssuanceParams.setAddress, _exchangeIssuanceParams.quantity ); emit LogExchangeIssue( _exchangeIssuanceParams.setAddress, msg.sender, _exchangeIssuanceParams.quantity, _exchangeIssuanceParams.sendTokens, _exchangeIssuanceParams.sendTokenAmounts ); } /** * Redeems a Set, redeems cToken to underlying, and performs trades via exchange wrappers for specified receive tokens. * The receive tokens are attributed to the caller. * * @param _exchangeIssuanceParams A Struct containing exchange issuance metadata * @param _orderData Bytes array containing the exchange orders to execute */ function exchangeRedeem( ExchangeIssuanceLibrary.ExchangeIssuanceParams memory _exchangeIssuanceParams, bytes memory _orderData ) public nonReentrant { // Validate exchangeIssuanceParams validateExchangeIssuanceParams(_exchangeIssuanceParams); // Validate that all sendTokens are components of the Set SetTokenLibrary.validateTokensAreComponents( _exchangeIssuanceParams.setAddress, _exchangeIssuanceParams.sendTokens ); // Redeem Set into the vault, attributing components to this contract coreInstance.redeemModule( msg.sender, address(this), _exchangeIssuanceParams.setAddress, _exchangeIssuanceParams.quantity ); // Calculate expected receive token balances uint256[] memory requiredBalances = calculateReceiveTokenBalances( _exchangeIssuanceParams ); // Withdraw underlying tokens required, redeem cTokens in the module, and send to exchange wrapper redeemCTokensAndTransferToExchangeWrappers( _exchangeIssuanceParams.sendTokenExchangeIds, _exchangeIssuanceParams.sendTokens, _exchangeIssuanceParams.sendTokenAmounts ); // Execute the exchange orders using the encoded order data and deposits tokens in vault executeExchangeOrders(_orderData); // Check that sender's receive token balances in Vault are correct ExchangeIssuanceLibrary.validatePostExchangeReceiveTokenBalances( vault, _exchangeIssuanceParams.receiveTokens, requiredBalances, msg.sender ); // Withdraw receive tokens from the Vault to the user coreInstance.batchWithdrawModule( msg.sender, msg.sender, _exchangeIssuanceParams.receiveTokens, _exchangeIssuanceParams.receiveTokenAmounts ); // Withdraw any remaining non-exchanged components to the user withdrawRemainingComponentsToUser(_exchangeIssuanceParams.setAddress); emit LogExchangeRedeem( _exchangeIssuanceParams.setAddress, msg.sender, _exchangeIssuanceParams.quantity, _exchangeIssuanceParams.receiveTokens, _exchangeIssuanceParams.receiveTokenAmounts ); } /* ============ Private Functions ============ */ /** * Withdraw required underlying from vault, mint required amount of cTokens, and deposit back into vault * * @param _receiveTokens Array of SetToken component addresses to receive * @param _receiveTokenAmounts Array of SetToken component required quantities to receive */ function mintCTokensFromExchangedComponents( address[] memory _receiveTokens, uint256[] memory _receiveTokenAmounts ) private { for (uint256 i = 0; i < _receiveTokens.length; i++) { address currentComponentAddress = _receiveTokens[i]; uint256 currentComponentQuantity = _receiveTokenAmounts[i]; // If cToken, calculate required underlying tokens and transfer to module address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress); if (underlyingAddress != address(0)) { ICToken cTokenInstance = ICToken(currentComponentAddress); // Calculate required amount of underlying. Calculated as cToken quantity * exchangeRate / 10 ** 18. uint256 exchangeRate = cTokenInstance.exchangeRateCurrent(); uint256 underlyingQuantity = CompoundUtils.convertCTokenToUnderlying(currentComponentQuantity, exchangeRate); // Withdraw send tokens from vault (owned by order sender) to the module coreInstance.withdrawModule( msg.sender, address(this), underlyingAddress, underlyingQuantity ); // Mint cToken and deposit to vault under sender mintCToken(cTokenInstance, underlyingAddress, underlyingQuantity); } } } /** * Transfer non-exchanged underlying tokens from caller, mint cTokens and deposit to the Vault under sender * to the caller * * @param _setAddress Address of the Set * @param _quantity Quantity of the Set to issue */ function mintCTokensFromCaller( address _setAddress, uint256 _quantity ) private { // Get SetToken details ISetToken baseSet = ISetToken(_setAddress); address[] memory baseSetComponents = baseSet.getComponents(); uint256[] memory baseSetUnits = baseSet.getUnits(); uint256 baseSetNaturalUnit = baseSet.naturalUnit(); // Calculate the number of natural units required. Note: validateExchangeIssuanceParams ensures quantity is a // multiple of natural unit uint256 quantityOfNaturalUnits = _quantity.div(baseSetNaturalUnit); for (uint256 i = 0; i < baseSetComponents.length; i++) { address currentComponentAddress = baseSetComponents[i]; // Get existing component quantity in the vault uint256 currentComponentQuantity = vaultInstance.getOwnerBalance(currentComponentAddress, msg.sender); // Calculate required quantity for component uint256 requiredQuantity = quantityOfNaturalUnits.mul(baseSetUnits[i]); // If cToken and balance of cToken in vault is less than required for issuing the Set // transfer difference from user and mint cToken address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress); if (underlyingAddress != address(0) && currentComponentQuantity < requiredQuantity) { // Calculate amount of remaining cTokens needed to issue Set uint256 quantityToMint = requiredQuantity - currentComponentQuantity; ICToken cTokenInstance = ICToken(currentComponentAddress); // Calculate required amount of underlying. Calculated as cToken quantity * exchangeRate / 10 ** 18. uint256 exchangeRate = cTokenInstance.exchangeRateCurrent(); uint256 underlyingQuantity = CompoundUtils.convertCTokenToUnderlying(quantityToMint, exchangeRate); // Transfer underlying from caller to module coreInstance.transferModule( underlyingAddress, underlyingQuantity, msg.sender, address(this) ); // Mint cToken and deposit to vault under sender mintCToken(cTokenInstance, underlyingAddress, underlyingQuantity); } } } /** * Withdraw required underlying from vault, redeem required amount of cTokens, and transfer to exchange wrappers * * @param _sendTokenExchangeIds List of exchange wrapper enumerations corresponding to * @param _sendTokens Array of SetToken component addresses to send * @param _sendTokenAmounts Array of SetToken component required quantities to send */ function redeemCTokensAndTransferToExchangeWrappers( uint8[] memory _sendTokenExchangeIds, address[] memory _sendTokens, uint256[] memory _sendTokenAmounts ) private { for (uint256 i = 0; i < _sendTokens.length; i++) { address exchangeWrapper = coreInstance.exchangeIds(_sendTokenExchangeIds[i]); address currentComponentAddress = _sendTokens[i]; uint256 currentComponentQuantity = _sendTokenAmounts[i]; // If cToken redeem cToken and replace send token and amounts with underlying address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress); if (underlyingAddress != address(0)) { // Withdraw cToken send tokens from vault (owned by this contract) to the module and redeem cToken redeemCToken( ICToken(currentComponentAddress), currentComponentQuantity ); // Get balance of underlying in the contract after cToken redemption to ensure tokens are flushed uint256 underlyingQuantity = ERC20Wrapper.balanceOf( underlyingAddress, address(this) ); // Ensure unlimited allowance for underlying component to transferProxy. ERC20Wrapper.ensureAllowance( underlyingAddress, // Token address(this), // Owner transferProxy, // Spender underlyingQuantity // Set unlimited if allowance less than quantity ); // Transfer send tokens to the appropriate exchange wrapper coreInstance.transferModule( underlyingAddress, // Token underlyingQuantity, // Quantity address(this), // From address exchangeWrapper // To address ); } else { // Withdraw non cToken send tokens from vault (owned by this contract) to the appropriate exchange wrapper coreInstance.withdrawModule( address(this), // From address in vault exchangeWrapper, // To address currentComponentAddress, // Token address currentComponentQuantity // Token quantity ); } } } /** * Mint cToken and deposit in vault under sender * * @param _cToken Instance of cToken component to mint * @param _underlyingAddress Underlying component address * @param _underlyingQuantity Quantity of underlying to mint */ function mintCToken( ICToken _cToken, address _underlyingAddress, uint256 _underlyingQuantity ) private { // Ensure unlimited allowance for underlying token to cToken contract. ERC20Wrapper.ensureAllowance( _underlyingAddress, address(this), address(_cToken), _underlyingQuantity ); // Mint cToken using underlying uint256 mintResponse = _cToken.mint(_underlyingQuantity); require( mintResponse == 0, "CTokenExchangeIssuanceModule.mintCToken: Error minting cToken" ); // Get balance of cTokens minted in the contract to ensure tokens are flushed at the end uint256 cTokenQuantity = ERC20Wrapper.balanceOf( address(_cToken), address(this) ); // Ensure unlimited allowance for cToken to transferProxy. This is for the case if we add a new cToken to the whitelist ERC20Wrapper.ensureAllowance( address(_cToken), address(this), transferProxy, cTokenQuantity ); // Deposit transformed cTokens to vault (owned by order sender) coreInstance.depositModule( address(this), msg.sender, address(_cToken), cTokenQuantity ); } /** * Withdraw cToken from vault, and redeem cToken in module * * @param _cToken Instance of cToken component to redeem * @param _cTokenQuantity Quantity of cToken to redeem */ function redeemCToken( ICToken _cToken, uint256 _cTokenQuantity ) private { // Withdraw cToken send tokens from vault (owned by this contract) to the module coreInstance.withdrawModule( address(this), // From address in vault address(this), // To address address(_cToken), // Token address _cTokenQuantity // Token quantity ); // Redeem cToken to underlying uint256 redeemResponse = _cToken.redeem(_cTokenQuantity); require( redeemResponse == 0, "CTokenExchangeIssuanceModule.redeemCToken: Error redeeming cToken" ); } /** * Transfers send tokens from the user to the appropriate exchange wrapper. Used in exchange issue * * @param _sendTokenExchangeIds List of exchange wrapper enumerations corresponding to * the wrapper that will handle the component * @param _sendTokens Array of addresses of the payment tokens * @param _sendTokenAmounts Array of amounts of payment Tokens */ function transferSendTokensToExchangeWrappers( uint8[] memory _sendTokenExchangeIds, address[] memory _sendTokens, uint256[] memory _sendTokenAmounts ) private { for (uint256 i = 0; i < _sendTokens.length; i++) { // Get exchange address from state mapping based on header exchange info address exchangeWrapper = coreInstance.exchangeIds(_sendTokenExchangeIds[i]); // Transfer send tokens to the appropriate exchange wrapper coreInstance.transferModule( _sendTokens[i], _sendTokenAmounts[i], msg.sender, exchangeWrapper ); } } /** * Withdraws any remaining un-exchanged cToken and non cToken components from the Vault in the possession of this contract * to the caller * * @param _setAddress Address of the Base Set */ function withdrawRemainingComponentsToUser( address _setAddress ) private { address[] memory baseSetComponents = ISetToken(_setAddress).getComponents(); for (uint256 i = 0; i < baseSetComponents.length; i++) { address currentComponentAddress = baseSetComponents[i]; uint256 currentComponentQuantity = vaultInstance.getOwnerBalance(currentComponentAddress, address(this)); // Remaining cTokens are redeemed to underlying and all tokens are sent to the caller if (currentComponentQuantity > 0) { address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress); if (underlyingAddress != address(0)) { // Withdraw cToken send tokens from vault (owned by this contract) to the module and redeem redeemCToken( ICToken(currentComponentAddress), currentComponentQuantity ); // Get balance of underlying after cToken redemption. uint256 underlyingQuantity = ERC20Wrapper.balanceOf( underlyingAddress, address(this) ); // Ensure allowance for underlying component to transferProxy. ERC20Wrapper.ensureAllowance( underlyingAddress, address(this), transferProxy, underlyingQuantity ); // Transfer underlying components to caller coreInstance.transferModule( underlyingAddress, underlyingQuantity, address(this), msg.sender ); } else { // Return the unexchanged non cToken components to the caller coreInstance.withdrawModule( address(this), msg.sender, currentComponentAddress, currentComponentQuantity ); } } } } }
Withdraw required underlying from vault, redeem required amount of cTokens, and transfer to exchange wrappers _sendTokenExchangeIds List of exchange wrapper enumerations corresponding to _sendTokens Array of SetToken component addresses to send _sendTokenAmounts Array of SetToken component required quantities to send/ If cToken redeem cToken and replace send token and amounts with underlying Withdraw cToken send tokens from vault (owned by this contract) to the module and redeem cToken Get balance of underlying in the contract after cToken redemption to ensure tokens are flushed Ensure unlimited allowance for underlying component to transferProxy. Transfer send tokens to the appropriate exchange wrapper Withdraw non cToken send tokens from vault (owned by this contract) to the appropriate exchange wrapper
function redeemCTokensAndTransferToExchangeWrappers( uint8[] memory _sendTokenExchangeIds, address[] memory _sendTokens, uint256[] memory _sendTokenAmounts ) private { for (uint256 i = 0; i < _sendTokens.length; i++) { address exchangeWrapper = coreInstance.exchangeIds(_sendTokenExchangeIds[i]); address currentComponentAddress = _sendTokens[i]; uint256 currentComponentQuantity = _sendTokenAmounts[i]; address underlyingAddress = cTokenWhiteList.whitelist(currentComponentAddress); if (underlyingAddress != address(0)) { redeemCToken( ICToken(currentComponentAddress), currentComponentQuantity ); uint256 underlyingQuantity = ERC20Wrapper.balanceOf( underlyingAddress, address(this) ); ERC20Wrapper.ensureAllowance( ); coreInstance.transferModule( ); coreInstance.withdrawModule( ); } } }
1,046,431
// Sources flattened with hardhat v2.1.2 https://hardhat.org // File @ensdomains/ens/contracts/ENS.sol@v0.6.0 pragma solidity ^0.8.0; interface ENS { // 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); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external virtual; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external virtual; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external virtual returns(bytes32); function setResolver(bytes32 node, address resolver) external virtual; function setOwner(bytes32 node, address owner) external virtual; function setTTL(bytes32 node, uint64 ttl) external virtual; function setApprovalForAll(address operator, bool approved) external virtual; function owner(bytes32 node) external virtual view returns (address); function resolver(bytes32 node) external virtual view returns (address); function ttl(bytes32 node) external virtual view returns (uint64); function recordExists(bytes32 node) external virtual view returns (bool); function isApprovedForAll(address owner, address operator) external virtual view returns (bool); } // File @ensdomains/ens/contracts/ENSRegistry.sol@v0.6.0 pragma solidity ^0.8.0; /** * The ENS registry contract. */ contract ENSRegistry is ENS { struct Record { address owner; address resolver; uint64 ttl; } mapping (bytes32 => Record) records; mapping (address => mapping(address => bool)) operators; // Permits modifications only by the owner of the specified node. modifier authorised(bytes32 node) { address owner = records[node].owner; require(owner == msg.sender || operators[owner][msg.sender]); _; } /** * @dev Constructs a new ENS registrar. */ constructor() public { records[0x0].owner = msg.sender; } /** * @dev Sets the record for a node. * @param node The node to update. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external virtual override { setOwner(node, owner); _setResolverAndTTL(node, resolver, ttl); } /** * @dev Sets the record for a subnode. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external virtual override { bytes32 subnode = setSubnodeOwner(node, label, owner); _setResolverAndTTL(subnode, resolver, ttl); } /** * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) public virtual override authorised(node) { _setOwner(node, owner); emit Transfer(node, owner); } /** * @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public virtual override authorised(node) returns(bytes32) { bytes32 subnode = keccak256(abi.encodePacked(node, label)); _setOwner(subnode, owner); emit NewOwner(node, label, owner); return subnode; } /** * @dev Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) public virtual override authorised(node) { emit NewResolver(node, resolver); records[node].resolver = resolver; } /** * @dev Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) public virtual override authorised(node) { emit NewTTL(node, ttl); records[node].ttl = ttl; } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s ENS records. Emits the ApprovalForAll event. * @param operator Address to add to the set of authorized operators. * @param approved True if the operator is approved, false to revoke approval. */ function setApprovalForAll(address operator, bool approved) external virtual override { operators[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Returns the address that owns the specified node. * @param node The specified node. * @return address of the owner. */ function owner(bytes32 node) public virtual override view returns (address) { address addr = records[node].owner; if (addr == address(this)) { return address(0x0); } return addr; } /** * @dev Returns the address of the resolver for the specified node. * @param node The specified node. * @return address of the resolver. */ function resolver(bytes32 node) public virtual override view returns (address) { return records[node].resolver; } /** * @dev Returns the TTL of a node, and any records associated with it. * @param node The specified node. * @return ttl of the node. */ function ttl(bytes32 node) public virtual override view returns (uint64) { return records[node].ttl; } /** * @dev Returns whether a record has been imported to the registry. * @param node The specified node. * @return Bool if record exists */ function recordExists(bytes32 node) public virtual override view returns (bool) { return records[node].owner != address(0x0); } /** * @dev Query if an address is an authorized operator for another address. * @param owner The address that owns the records. * @param operator The address that acts on behalf of the owner. * @return True if `operator` is an approved operator for `owner`, false otherwise. */ function isApprovedForAll(address owner, address operator) external virtual override view returns (bool) { return operators[owner][operator]; } function _setOwner(bytes32 node, address owner) internal virtual { records[node].owner = owner; } function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal { if(resolver != records[node].resolver) { records[node].resolver = resolver; emit NewResolver(node, resolver); } if(ttl != records[node].ttl) { records[node].ttl = ttl; emit NewTTL(node, ttl); } } } // File contracts/deps.sol // File @ensdomains/root/contracts/Ownable.sol@v0.2.0 pragma solidity ^0.8.0; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner { require(isOwner(msg.sender)); _; } constructor() public { owner = msg.sender; } function transferOwnership(address newOwner) public onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function isOwner(address addr) public view returns (bool) { return owner == addr; } } // File @ensdomains/root/contracts/Controllable.sol@v0.2.0 pragma solidity ^0.8.0; contract Controllable is Ownable { mapping(address=>bool) public controllers; event ControllerChanged(address indexed controller, bool enabled); modifier onlyController { require(controllers[msg.sender]); _; } function setController(address controller, bool enabled) public onlyOwner { controllers[controller] = enabled; emit ControllerChanged(controller, enabled); } } // File @ensdomains/root/contracts/Root.sol@v0.2.0 pragma solidity ^0.8.0; contract Root is Ownable, Controllable { bytes32 constant private ROOT_NODE = bytes32(0); bytes4 constant private INTERFACE_META_ID = bytes4(keccak256("supportsInterface(bytes4)")); event TLDLocked(bytes32 indexed label); ENS public ens; mapping(bytes32=>bool) public locked; constructor(ENS _ens) public { ens = _ens; } function setSubnodeOwner(bytes32 label, address owner) external onlyController { require(!locked[label]); ens.setSubnodeOwner(ROOT_NODE, label, owner); } function setResolver(address resolver) external onlyOwner { ens.setResolver(ROOT_NODE, resolver); } function lock(bytes32 label) external onlyOwner { emit TLDLocked(label); locked[label] = true; } function supportsInterface(bytes4 interfaceID) external pure returns (bool) { return interfaceID == INTERFACE_META_ID; } } // File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.0.0 pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/IERC721.sol@v4.0.0 pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.0.0 pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol@v4.0.0 pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol@v4.0.0 pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/utils/Address.sol@v4.0.0 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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/Context.sol@v4.0.0 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/utils/Strings.sol@v4.0.0 pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.0.0 pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/ERC721.sol@v4.0.0 pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. 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 || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol@v4.0.0 pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File contracts/TLDToken.sol pragma solidity ^0.8.0; contract TLDToken is ERC721, ERC721URIStorage, Ownable { struct TokenInfo { string name; address owner; string tokenURI; } Root public root; constructor(address _root, TokenInfo[] memory preloads, address _owner) ERC721("ENS Top-level domains", "TLD") { root = Root(_root); mintTLDs(preloads); transferOwnership(_owner); } function mintTLDs(TokenInfo[] memory tlds) public { for(uint i = 0; i < tlds.length; i++) { TokenInfo memory tld = tlds[i]; mintTLD(tld.name, tld.owner, tld.tokenURI); } } function mintTLD(string memory name, address owner, string memory tokenURI) public onlyOwner { uint256 tokenId = uint256(keccak256(bytes(name))); _mint(owner, tokenId); _setTokenURI(tokenId, tokenURI); } function claim(uint256 tokenId, address ensowner) external { // Safety check: Do not allow .eth to be changed this way require(_isApprovedOrOwner(_msgSender(), tokenId), "TLDToken: Not authorised to use token"); require(tokenId != uint256(keccak256('eth')), "TLDToken: Cannot change .eth"); root.setSubnodeOwner(bytes32(tokenId), ensowner); } function burn(uint256 tokenId) external { require(_isApprovedOrOwner(_msgSender(), tokenId) || isOwner(_msgSender()), "TLDToken: Only token or contract owner can call burn"); _burn(tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721URIStorage, ERC721) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721URIStorage, ERC721) returns (string memory) { return super.tokenURI(tokenId); } }
Returns whether a record has been imported to the registry. node The specified node. return Bool if record exists/
function recordExists(bytes32 node) public virtual override view returns (bool) { return records[node].owner != address(0x0); }
1,354,688
pragma solidity ^0.5.3; import "./PermissionsImplementation.sol"; import "./PermissionsUpgradable.sol"; /** @title Permissions Interface Contract * @notice This contract is the interface for permissions implementation contract. for any call, it forwards the call to the implementation contract */ contract PermissionsInterface { PermissionsImplementation private permImplementation; PermissionsUpgradable private permUpgradable; address private permImplUpgradeable; /** @notice constructor * @param _permImplUpgradeable permissions upgradable contract address */ constructor(address _permImplUpgradeable) public { permImplUpgradeable = _permImplUpgradeable; } /** @notice confirms that the caller is the address of upgradable contract */ modifier onlyUpgradeable { require(msg.sender == permImplUpgradeable, "invalid caller"); _; } /** @notice interface for setting the permissions policy in implementation * @param _nwAdminOrg network admin organization id * @param _nwAdminRole default network admin role id * @param _oAdminRole default organization admin role id */ function setPolicy(string calldata _nwAdminOrg, string calldata _nwAdminRole, string calldata _oAdminRole) external { permImplementation.setPolicy(_nwAdminOrg, _nwAdminRole, _oAdminRole); } /** @notice interface to initializes the breadth and depth values for sub organization management * @param _breadth controls the number of sub org a parent org can have * @param _depth controls the depth of nesting allowed for sub orgs */ function init(uint256 _breadth, uint256 _depth) external { permImplementation.init(_breadth, _depth); } /** @notice interface to add new node to an admin organization * @param _enodeId full enode id of the node to be added */ function addAdminNode(string calldata _enodeId) external { permImplementation.addAdminNode(_enodeId); } /** @notice interface to add accounts to an admin organization * @param _acct account address to be added */ function addAdminAccount(address _acct) external { permImplementation.addAdminAccount(_acct); } /** @notice interface to update network boot up status * @return bool true or false */ function updateNetworkBootStatus() external returns (bool) { return permImplementation.updateNetworkBootStatus(); } /** @notice interface to fetch network boot status * @return bool network boot status */ function getNetworkBootStatus() external view returns (bool){ return permImplementation.getNetworkBootStatus(); } /** @notice interface to add a new organization to the network * @param _orgId unique organization id * @param _enodeId full enode id linked to the organization * @param _account account id. this will have the org admin privileges */ function addOrg(string calldata _orgId, string calldata _enodeId, address _account) external { permImplementation.addOrg(_orgId, _enodeId, _account, msg.sender); } /** @notice interface to approve a newly added organization * @param _orgId unique organization id * @param _enodeId full enode id linked to the organization * @param _account account id this will have the org admin privileges */ function approveOrg(string calldata _orgId, string calldata _enodeId, address _account) external { permImplementation.approveOrg(_orgId, _enodeId, _account, msg.sender); } /** @notice interface to add sub org under an org * @param _pOrgId parent org id under which the sub org is being added * @param _orgId unique id for the sub organization * @param _enodeId full enode id linked to the sjb organization */ function addSubOrg(string calldata _pOrgId, string calldata _orgId, string calldata _enodeId) external { permImplementation.addSubOrg(_pOrgId, _orgId, _enodeId, msg.sender); } /** @notice interface to update the org status * @param _orgId unique id of the organization * @param _action 1 for suspending an org and 2 for revoke of suspension */ function updateOrgStatus(string calldata _orgId, uint256 _action) external { permImplementation.updateOrgStatus(_orgId, _action, msg.sender); } /** @notice interface to approve org status change * @param _orgId unique id for the sub organization * @param _action 1 for suspending an org and 2 for revoke of suspension */ function approveOrgStatus(string calldata _orgId, uint256 _action) external { permImplementation.approveOrgStatus(_orgId, _action, msg.sender); } /** @notice interface to add a new role definition to an organization * @param _roleId unique id for the role * @param _orgId unique id of the organization to which the role belongs * @param _access account access type for the role * @param _voter bool indicates if the role is voter role or not * @param _admin bool indicates if the role is an admin role * @dev account access type can have of the following four values: 0 - Read only 1 - Transact access 2 - Contract deployment access. Can transact as well 3 - Full access */ function addNewRole(string calldata _roleId, string calldata _orgId, uint256 _access, bool _voter, bool _admin) external { permImplementation.addNewRole(_roleId, _orgId, _access, _voter, _admin, msg.sender); } /** @notice interface to remove a role definition from an organization * @param _roleId unique id for the role * @param _orgId unique id of the organization to which the role belongs */ function removeRole(string calldata _roleId, string calldata _orgId) external { permImplementation.removeRole(_roleId, _orgId, msg.sender); } /** @notice interface to assign network admin/org admin role to an account this can be executed by network admin accounts only * @param _orgId unique id of the organization to which the account belongs * @param _account account id * @param _roleId role id to be assigned to the account */ function assignAdminRole(string calldata _orgId, address _account, string calldata _roleId) external { permImplementation.assignAdminRole(_orgId, _account, _roleId, msg.sender); } /** @notice interface to approve network admin/org admin role assigment this can be executed by network admin accounts only * @param _orgId unique id of the organization to which the account belongs * @param _account account id */ function approveAdminRole(string calldata _orgId, address _account) external { permImplementation.approveAdminRole(_orgId, _account, msg.sender); } /** @notice interface to update account status this can be executed by org admin accounts only * @param _orgId unique id of the organization to which the account belongs * @param _account account id * @param _action 1-suspending 2-activating back 3-blacklisting */ function updateAccountStatus(string calldata _orgId, address _account, uint256 _action) external { permImplementation.updateAccountStatus(_orgId, _account, _action, msg.sender); } /** @notice interface to add a new node to the organization * @param _orgId unique id of the organization to which the account belongs * @param _enodeId full enode id being dded to the org */ function addNode(string calldata _orgId, string calldata _enodeId) external { permImplementation.addNode(_orgId, _enodeId, msg.sender); } /** @notice interface to update node status * @param _orgId unique id of the organization to which the account belongs * @param _enodeId full enode id being dded to the org * @param _action 1-deactivate, 2-activate back, 3-blacklist the node */ function updateNodeStatus(string calldata _orgId, string calldata _enodeId, uint256 _action) external { permImplementation.updateNodeStatus(_orgId, _enodeId, _action, msg.sender); } /** @notice interface to initiate blacklisted node recovery * @param _orgId unique id of the organization to which the account belongs * @param _enodeId full enode id being recovered */ function startBlacklistedNodeRecovery(string calldata _orgId, string calldata _enodeId) external { permImplementation.startBlacklistedNodeRecovery(_orgId, _enodeId, msg.sender); } /** @notice interface to approve blacklisted node recoevry * @param _orgId unique id of the organization to which the account belongs * @param _enodeId full enode id being recovered */ function approveBlacklistedNodeRecovery(string calldata _orgId, string calldata _enodeId) external { permImplementation.approveBlacklistedNodeRecovery(_orgId, _enodeId, msg.sender); } /** @notice interface to initiate blacklisted account recovery * @param _orgId unique id of the organization to which the account belongs * @param _account account id being recovered */ function startBlacklistedAccountRecovery(string calldata _orgId, address _account) external { permImplementation.startBlacklistedAccountRecovery(_orgId, _account, msg.sender); } /** @notice interface to approve blacklisted node recovery * @param _orgId unique id of the organization to which the account belongs * @param _account account id being recovered */ function approveBlacklistedAccountRecovery(string calldata _orgId, address _account) external { permImplementation.approveBlacklistedAccountRecovery(_orgId, _account, msg.sender); } /** @notice interface to fetch detail of any pending approval activities for network admin organization * @param _orgId unique id of the organization to which the account belongs */ function getPendingOp(string calldata _orgId) external view returns (string memory, string memory, address, uint256) { return permImplementation.getPendingOp(_orgId); } /** @notice sets the permissions implementation contract address can be called from upgradable contract only * @param _permImplementation permissions implementation contract address */ function setPermImplementation(address _permImplementation) external onlyUpgradeable { permImplementation = PermissionsImplementation(_permImplementation); } /** @notice returns the address of permissions implementation contract * @return permissions implementation contract address */ function getPermissionsImpl() external view returns (address) { return address(permImplementation); } /** @notice interface to assigns a role id to the account give * @param _account account id * @param _orgId organization id to which the account belongs * @param _roleId role id to be assigned to the account */ function assignAccountRole(address _account, string calldata _orgId, string calldata _roleId) external { permImplementation.assignAccountRole(_account, _orgId, _roleId, msg.sender); } /** @notice interface to check if passed account is an network admin account * @param _account account id * @return true/false */ function isNetworkAdmin(address _account) external view returns (bool) { return permImplementation.isNetworkAdmin(_account); } /** @notice interface to check if passed account is an org admin account * @param _account account id * @param _orgId organization id * @return true/false */ function isOrgAdmin(address _account, string calldata _orgId) external view returns (bool) { return permImplementation.isOrgAdmin(_account, _orgId); } /** @notice interface to validate the account for access change operation * @param _account account id * @param _orgId organization id * @return true/false */ function validateAccount(address _account, string calldata _orgId) external view returns (bool) { return permImplementation.validateAccount(_account, _orgId); } }
interface to validate the account for access change operation _account account id _orgId organization id return true/false/
function validateAccount(address _account, string calldata _orgId) external view returns (bool) { return permImplementation.validateAccount(_account, _orgId); }
5,377,754
pragma solidity >=0.5.12 <=0.6.2; /** * @title Black-scholes Solidity Math Library * @author Alexander Angel */ import { ABDKMath64x64 } from "./ABDKMath64x64.sol"; import { SafeMath } from "./SafeMath.sol"; library Pricing { using ABDKMath64x64 for *; // stores numerators as int128, denominator is 2^64. using SafeMath for uint256; uint256 internal constant YEAR = 31449600; // 1 year in seconds uint256 internal constant MANTISSA = 10**8; uint256 internal constant DENOMINATOR = 10**18; // wei uint256 internal constant PERCENTAGE = 10**3; // Black-Scholes Approximation for ATM options ONLY. /** * @dev Calculate the ATM option price. 0.4 * S * sigma * sqrt(T-t). * @param s Spot price of underlying token in USD/DAI/USDC. * @param o "volatility" scaled by 1000. * @param t Time until expiration in seconds. */ function calculateATM( uint256 s, uint256 o, uint256 t ) internal pure returns (uint256 atm) { int128 spot = fromWeiToInt128(s); atm = ( int128(2).div(int128(5)).mul(spot).mul(o.fromUInt()).div(PERCENTAGE.fromUInt()).mul( (t.fromUInt().div(YEAR.fromUInt())).sqrt() ) ) .toUInt(); } // Black-Scholes functions. /** * @dev Calculate the d1 auxiliary variable. * @notice ( ln(s/k) + (o^2/2)*(T-t) ) / o * sqrt(T-t). * @param s Spot price of underlying token in USD/DAI/USDC. In wei. * @param k Strike price in USD/DAI/USDC. In wei. * @param o "volatility" scaled by 1000. * @param t Time until expiration in seconds. */ function auxiliary( uint256 s, uint256 k, uint256 o, uint256 t ) internal pure returns (int128 d1) { // ln( F / K ) int128 moneyness = logSimpleMoneyness(s, k); // (r + volatility^2 / 2), r = 0 for simplicity. This should be fixed. int128 vol = (percentageInt128(o).pow(2)).div(ABDKMath64x64.fromUInt(2)); // ( T - t ) time until expiry. seconds / seconds in a year = years int128 time = secondsToYears(t); // ln( F / K ) + (r + volatility^2 / 2) * (T - t) int128 numerator = moneyness.add(vol.mul(time)); // volatility * sqrt(T - t) int128 denominator = percentageInt128(o).mul((secondsToYears(t)).sqrt()); d1 = numerator.div(denominator); } /** * @dev Calculates the log simple moneyness. * @notice ln(F / K). * @param s Spot price of underlying token in USD/DAI/USDC. In wei. * @param k Strike price in USD/DAI/USDC. In wei. */ function logSimpleMoneyness(uint256 s, uint256 k) internal pure returns (int128 moneyness) { int128 spot = fromWeiToInt128(s); int128 strike = fromWeiToInt128(k); moneyness = (spot.div(strike)).ln(); } /** * @dev Calculate the d2 auxiliary variable. * @notice d1 - volatility*sqrt(T-t). * @param s Spot price of underlying token in USD/DAI/USDC. In wei. * @param k Strike price in USD/DAI/USDC. In wei. * @param o "volatility" scaled by 1000. * @param t Time until expiration in seconds. */ function auxiliary2( uint256 s, uint256 k, uint256 o, uint256 t ) internal pure returns (int128 d2) { // d1 = ( ln(s/k) + (o^2/2)*(T-t) ) / o * sqrt(T-t). int128 d1 = auxiliary(s, k, o, t); // d2 = d1 - volatility*sqrt(T-t). d2 = d1.sub(percentageInt128(o).mul((secondsToYears(t)).sqrt())); } /** @title Approximations to Standard Normal Distribution Function @author Ramu Yerukala and Naveen Kumar Boiroju International Journal of Scientific & Engineering Research, Volume 6, Issue 4, April-2015 515 ISSN 2229-5518 @notice We use an approximation for the standard normal distribution function (CDF21) as follows: exp( -z ^ 2 / 2) 1 - ( ----------------------------------- ) 44 8 5 ---- + --- * z + --- * sqrt( z^2 +3 ) 79 5 6 */ /** * @dev Calculates the numerator for the CDF. * @notice e ^ (-z ^ 2 / 2) */ function ndnumerator(int128 z) internal pure returns (int128 numerator) { numerator = ((z.neg()).pow(2).div((2).fromUInt())).exp(); } /** * @dev Calculates the first element for the denominator of CDF21. * @notice 44 ---- 79 */ function cdfA() internal pure returns (int128) { return (44).fromUInt().div((79).fromUInt()); } /** * @dev Calculates the second element for the denominator of CDF21. * @notice 8 --- * z 5 */ function cdfB(int128 z) internal pure returns (int128) { return z.mul((8).fromUInt()).div((5).fromUInt()); } /** * @dev Calculates the first element for the third element of the denominator of CDF21. * @notice ( z ^ 2 ). */ function cdfC0(int128 z) internal pure returns (int128) { return z.pow(2); } /** * @dev Calculates the items for the third element for the denominator of CDF21. * @notice ( z^2 + 3 ). */ function cdfC01(int128 z) internal pure returns (int128) { return cdfC0(z).add((3).fromUInt()); } /** * @dev Calculates the full element for the third element for the denominator of CDF21. * @notice sqrt( z^2 + 3 ). */ function cdfC1(int128 z) internal pure returns (int128) { return (cdfC01(z)).sqrt(); } /** * @dev Calculates the second element's first item for the denominator of the CDF21. * @notice ( 5 / 6). */ function cdfC2() internal pure returns (int128) { return int128(5).div(int128(6)); } /** * @dev Calculates the second element for the denominator of the CDF21. * @notice ( z * ( 5 / 6) ). */ function cdfC(int128 z) internal pure returns (int128) { return cdfC1(z).mul(cdfC2()); } /** * @dev Calculates the full denominator of the CDF21. */ function cdfDenominator(int128 z) internal pure returns (int128 denominator) { int128 a = cdfA(); int128 b = cdfB(z); int128 c = cdfC(z); denominator = a.add(b).add(c); } /** * @dev Calculates the normal distribution using an approximation. */ function normdist(int128 z) internal pure returns (int128 n) { int128 numerator = ndnumerator(z); int128 denominator = cdfDenominator(z); n = (1).fromUInt().sub(numerator.div(denominator)); } function cumulativeDistributionFunction(int128 x) internal pure returns (int128) { // where p = 0.3275911, // a1 = 0.254829592, a2 = −0.284496736, a3 = 1.421413741, a4 = −1.453152027, a5 = 1.061405429 int128 p = 0x53dd02a4f5ee2e46; int128 one = ABDKMath64x64.fromUInt(1); int128 two = ABDKMath64x64.fromUInt(2); int128 a1 = 0x413c831bb169f874; int128 a2 = -0x48d4c730f051a5fe; int128 a3 = 0x16a09e667f3bcc908; int128 a4 = -0x17401c57014c38f14; int128 a5 = 0x10fb844255a12d72e; int128 z = x.div(a3); int128 t = one.div(one.add(p.mul(z.abs()))); int128 erf = getErrorFunction(z, t); if (z < 0) { erf = erf.neg(); } int128 result = (one.div(two)).mul(one.add(erf)); return result; } function getErrorFunction(int128 z, int128 t) internal pure returns (int128) { // where a1 = 0.254829592, a2 = −0.284496736, a3 = 1.421413741, a4 = −1.453152027, a5 = 1.061405429 int128 step1; { int128 a3 = 0x16a09e667f3bcc908; int128 a4 = -0x17401c57014c38f14; int128 a5 = 0x10fb844255a12d72e; step1 = t.mul(a3.add(t.mul(a4.add(t.mul(a5))))); } int128 result; { int128 one = ABDKMath64x64.fromUInt(1); int128 a1 = 0x413c831bb169f874; int128 a2 = -0x48d4c730f051a5fe; int128 step2 = a1.add(t.mul(a2.add(step1))); result = one.sub(t.mul(step2.mul(((z).pow(2).neg()).exp()))); } return result; } /** * @dev Calculates a call option value using black-scholes. * @notice C(s, t) = s * N(d1) - Ke^-r(T - t) * N(d2). Where N() is the standard normal CDF. * @param s Spot price of underlying token in USD/DAI/USDC. In wei. * @param k Strike price in USD/DAI/USDC. In wei. * @param o "volatility" scaled by 1000. * @param t Time until expiration in seconds. * @return c The value of the call option for the contract's parameters. */ function call( uint256 s, uint256 k, uint256 o, uint256 t ) internal pure returns (int128 c) { int128 spot = fromWeiToInt128(s); int128 strike = fromWeiToInt128(k); int128 d1 = auxiliary(s, k, o, t); int128 d2 = auxiliary2(s, k, o, t); int128 nd1 = normdist(d1); int128 nd2 = normdist(d2); int128 bs = spot.mul(nd1) > strike.mul(nd2) ? spot.mul(nd1).sub(strike.mul(nd2)) : int128(0); c = bs; } /** * @dev Calculates a put option value using black-scholes. * @notice P(s, t) = Ke^-r(T - t) * N(-d2) - s * N(-d1). Where N() is the standard normal CDF. * @param s Spot price of underlying token in USD/DAI/USDC. In wei. * @param k Strike price in USD/DAI/USDC. In wei. * @param o "volatility" scaled by 1000. * @param t Time until expiration in seconds. * @return p The value of the put option for the contract's parameters. */ function put( uint256 s, uint256 k, uint256 o, uint256 t ) internal pure returns (int128 p) { int128 spot = fromWeiToInt128(s); int128 strike = fromWeiToInt128(k); int128 d1 = auxiliary(s, k, o, t); int128 d2 = auxiliary2(s, k, o, t); int128 nd1 = cumulativeDistributionFunction((d1).neg()); int128 nd2 = cumulativeDistributionFunction((d2).neg()); int128 bs = strike.mul(nd2) > spot.mul(nd1) ? strike.mul(nd2).sub(spot.mul(nd1)) : int128(0); p = bs; /* int128 spot = fromWeiToInt128(s); int128 strike = fromWeiToInt128(k); int128 d1 = auxiliary(s, k, o, t); int128 d2 = auxiliary2(s, k, o, t); int128 delta = cumulativeDistributionFunction(d1).sub((1).fromUInt()); int128 part1 = spot.mul(delta); int128 part2 = strike.mul(((1).fromUInt()).sub(cumulativeDistributionFunction(d2))); int128 bs = part1.add(part2); p = bs; */ } // Elasticity and greek functions. /** * @dev Calculates the numerator for the option elasticity function. * @notice spot * delta. delta = ( 1 - N(d1) ). d1 is negative for puts. */ function eNumerator( uint256 s, uint256 k, uint256 o, uint256 t, int128 d1 ) internal pure returns (int128 numerator) { int128 x = fromWeiToInt128(s); int128 delta = (1).fromUInt().sub(cumulativeDistributionFunction(d1)); numerator = x.mul(delta); } /** * @dev Calculates the denominator for the option elasticity function. * @notice P(s, t) + s */ function eDenominator( uint256 s, uint256 k, uint256 o, uint256 t ) internal pure returns (int128 denominator) { int128 x = fromWeiToInt128(s); int128 pxt = put(s, k, o, t); denominator = x.add(pxt); } /** * @dev Calculates the elasticity of an option. */ function elasticity( uint256 s, uint256 k, uint256 o, uint256 t, int128 d1 ) internal pure returns (int128 e) { int128 numerator = eNumerator(s, k, o, t, d1); int128 denominator = eDenominator(s, k, o, t); e = numerator.div(denominator); } /** * @dev Calculates the elasticity of an option and converts to a denormalized weight in wei. */ function getWeights( uint256 s, uint256 k, uint256 o, uint256 t ) internal pure returns (uint256 riskyW, uint256 riskFW) { // get d1 int128 d1 = auxiliary(s, k, o, t); // get elasticity using -d1 = weight of risky asset e.g. 0.5 int128 elasticity = elasticity(s, k, o, t, d1.neg()); // get weight of risk-free asset, 1 - riskyW = 1 - 0.5 = 0.5 int128 remainder = ABDKMath64x64.fromUInt(1).sub(elasticity); // convert to uint riskyW = _fromInt(elasticity); riskFW = _fromInt(remainder); // convert to 10 ^ 18 units riskyW = riskyW.mul(uint256(10**18).div(MANTISSA)); riskFW = riskFW.mul(uint256(10**18).div(MANTISSA)); } /** * @dev Gets call option price. Library entry point for easy testing. */ function getCall( uint256 s, uint256 k, uint256 o, uint256 t ) internal pure returns (uint256) { return _fromInt(call(s, k, o, t)).mul(uint256(10**18).div(MANTISSA)); } /** * @dev Gets call option price. Library entry point for easy testing. */ function getCallPrice( uint256 s, uint256 k, uint256 o, uint256 t ) public pure returns (uint256) { return _fromInt(call(s, k, o, t)).mul(uint256(10**18).div(MANTISSA)); } /** * @dev Gets put option price. Library entry point for easy testing. */ function getPutPrice( uint256 s, uint256 k, uint256 o, uint256 t ) public pure returns (uint256) { return _fromInt(put(s, k, o, t)).mul(uint256(10**18).div(MANTISSA)); } /** * @dev Gets put option price. Library entry point for easy testing. */ function getElasticity( uint256 s, uint256 k, uint256 o, uint256 t ) public pure returns (uint256) { int128 d1 = auxiliary(s, k, o, t); // get elasticity using -d1 = weight of risky asset e.g. 0.5 int128 elasticity = elasticity(s, k, o, t, d1.neg()); // convert to uint uint256 weight = _fromInt(elasticity); return weight.mul(uint256(10**18)).div(MANTISSA); } /** * @dev Library entry point for easy testing. */ function weights( uint256 s, uint256 k, uint256 o, uint256 t ) public pure returns (uint256 riskyW, uint256 riskFW) { (riskyW, riskFW) = getWeights(s, k, o, t); } // Conversion functions. /** * @dev Converts a wei value uint256 into an int128 numerator value. * @param x A uint256 amount. */ function fromWeiToInt128(uint256 x) internal pure returns (int128) { return x.divu(DENOMINATOR); } /** * @dev Converts a denormalized percentage (1000 = 100%, 10 = 1%) into an int128. */ function percentageInt128(uint256 denorm) internal pure returns (int128) { int128 numerator = denorm.fromUInt(); int128 denominator = PERCENTAGE.fromUInt(); return numerator.div(denominator); } /** * @dev Converts second units into an int128 with units of years. */ function secondsToYears(uint256 quantitySeconds) internal pure returns (int128) { int128 time = quantitySeconds.fromUInt(); int128 units = YEAR.fromUInt(); return time.div(units); } /** * @dev Converts a numerator x with denominator 2^64 into an uint256. * @notice Will return 0 if a fraction < 10^8. */ function _fromInt(int128 x) internal pure returns (uint256 y) { x = x.mul((MANTISSA).fromUInt()); y = x > 0 ? (x).toUInt() : uint256(0); } }
Calculates the full element for the third element for the denominator of CDF21. sqrt( z^2 + 3 )./
function cdfC1(int128 z) internal pure returns (int128) { return (cdfC01(z)).sqrt(); }
12,946,914
/* Copyright 2019 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.7; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { IDolomiteMargin } from "../../protocol/interfaces/IDolomiteMargin.sol"; import {Account} from "../../protocol/lib/Account.sol"; import {Actions} from "../../protocol/lib/Actions.sol"; import {Decimal} from "../../protocol/lib/Decimal.sol"; import {Interest} from "../../protocol/lib/Interest.sol"; import {Math} from "../../protocol/lib/Math.sol"; import {Monetary} from "../../protocol/lib/Monetary.sol"; import {Require} from "../../protocol/lib/Require.sol"; import {Types} from "../../protocol/lib/Types.sol"; import { IExpiry } from "../interfaces/IExpiry.sol"; import {DolomiteAmmRouterProxy} from "./DolomiteAmmRouterProxy.sol"; /** * @title LiquidatorProxyV1WithAmm * @author dYdX * * Contract for liquidating other accounts in DolomiteMargin. Does not take marginPremium into account. */ contract LiquidatorProxyV1WithAmm is ReentrancyGuard { using Math for uint256; using SafeMath for uint256; using Types for Types.Par; using Types for Types.Wei; // ============ Constants ============ bytes32 constant FILE = "LiquidatorProxyV1WithAmm"; // ============ Structs ============ struct Constants { Account.Info solidAccount; Account.Info liquidAccount; MarketInfo[] markets; IExpiry EXPIRY_PROXY; uint32 expiry; } struct MarketInfo { Monetary.Price price; Interest.Index index; } struct LiquidatorWithAmmCache { // mutable uint256 toLiquidate; // The amount of heldMarket the solidAccount will receive. Includes the liquidation reward. uint256 solidHeldUpdateWithReward; Types.Wei solidHeldWei; Types.Wei liquidHeldWei; Types.Wei liquidOwedWei; // immutable uint256 heldMarket; uint256 owedMarket; uint256 heldPrice; uint256 owedPrice; uint256 owedPriceAdj; } // ============ Storage ============ IDolomiteMargin DOLOMITE_MARGIN; DolomiteAmmRouterProxy ROUTER_PROXY; IExpiry EXPIRY_PROXY; // ============ Constructor ============ constructor ( address dolomiteMargin, address dolomiteAmmRouterProxy, address expiryProxy ) public { DOLOMITE_MARGIN = IDolomiteMargin(dolomiteMargin); ROUTER_PROXY = DolomiteAmmRouterProxy(dolomiteAmmRouterProxy); EXPIRY_PROXY = IExpiry(expiryProxy); } // ============ Public Functions ============ /** * Liquidate liquidAccount using solidAccount. This contract and the msg.sender to this contract * must both be operators for the solidAccount. * * @param solidAccount The account that will do the liquidating * @param liquidAccount The account that will be liquidated * @param owedMarket The owed market whose borrowed value will be added to `toLiquidate` * @param heldMarket The held market whose collateral will be recovered to take on the debt of * `owedMarket` * @param tokenPath The path through which the trade will be routed to recover the collateral * @param expiry The time at which the position expires, if this liquidation is for closing * an expired position. Else, 0. * @param revertOnFailToSellCollateral True to revert the transaction completely if all collateral from the * liquidation cannot repay the owed debt. False to swallow the error and sell * whatever is possible. */ function liquidate( Account.Info memory solidAccount, Account.Info memory liquidAccount, uint256 owedMarket, uint256 heldMarket, address[] memory tokenPath, uint expiry, bool revertOnFailToSellCollateral ) public nonReentrant { Require.that( owedMarket != heldMarket, FILE, "owedMarket equals heldMarket", owedMarket, heldMarket ); Require.that( !DOLOMITE_MARGIN.getAccountPar(liquidAccount, owedMarket).isPositive(), FILE, "owed market cannot be positive", owedMarket ); Require.that( DOLOMITE_MARGIN.getAccountPar(liquidAccount, heldMarket).isPositive(), FILE, "held market cannot be negative", heldMarket ); Require.that( DOLOMITE_MARGIN.getMarketIdByTokenAddress(tokenPath[0]) == heldMarket, FILE, "0-index token path incorrect", tokenPath[0] ); Require.that( DOLOMITE_MARGIN.getMarketIdByTokenAddress(tokenPath[tokenPath.length - 1]) == owedMarket, FILE, "last-index token path incorrect", tokenPath[tokenPath.length - 1] ); Require.that( uint32(expiry) == expiry, FILE, "expiry overflow", expiry ); // put all values that will not change into a single struct Constants memory constants = Constants({ solidAccount : solidAccount, liquidAccount : liquidAccount, markets : getMarketsInfo(), EXPIRY_PROXY : expiry > 0 ? EXPIRY_PROXY : IExpiry(address(0)), expiry : uint32(expiry) }); LiquidatorWithAmmCache memory cache = initializeCache( constants, heldMarket, owedMarket ); // validate the msg.sender and that the liquidAccount can be liquidated checkRequirements(constants); // get the max liquidation amount calculateMaxLiquidationAmount(cache); // if nothing to liquidate, do nothing Require.that( cache.toLiquidate != 0, FILE, "nothing to liquidate" ); uint totalSolidHeldWei = cache.solidHeldUpdateWithReward; if (cache.solidHeldWei.sign) { // If the solid account has held wei, add the amount the solid account will receive from liquidation to its // total held wei // We do this so we can accurately track how much the solid account has, in case we need to input it // exactly to Router#getParamsForSwapExactTokensForTokens totalSolidHeldWei = totalSolidHeldWei.add(cache.solidHeldWei.value); } (Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) = ROUTER_PROXY.getParamsForSwapTokensForExactTokens( constants.solidAccount.owner, constants.solidAccount.number, uint(- 1), // maxInputWei cache.toLiquidate, // the amount of owedMarket that needs to be repaid. Exact output amount tokenPath ); if (revertOnFailToSellCollateral) { Require.that( totalSolidHeldWei >= actions[0].amount.value, FILE, "totalSolidHeldWei is too small", totalSolidHeldWei, actions[0].amount.value ); } else if (totalSolidHeldWei < actions[0].amount.value) { (accounts, actions) = ROUTER_PROXY.getParamsForSwapExactTokensForTokens( constants.solidAccount.owner, constants.solidAccount.number, totalSolidHeldWei, // inputWei 1, // minOutputAmount; we will sell whatever collateral we can tokenPath ); } accounts = constructAccountsArray(constants, accounts); // execute the liquidations DOLOMITE_MARGIN.operate( accounts, constructActionsArray(constants, cache, accounts, actions) //solium-disable-line arg-overflow ); } // ============ Calculation Functions ============ /** * Calculate the additional owedAmount that can be liquidated until the collateralization of the * liquidator account reaches the minLiquidatorRatio. By this point, the cache will be set such * that the amount of owedMarket is non-positive and the amount of heldMarket is non-negative. */ function calculateMaxLiquidationAmount( LiquidatorWithAmmCache memory cache ) private pure { uint liquidHeldValue = cache.heldPrice.mul(cache.liquidHeldWei.value); uint liquidOwedValue = cache.owedPriceAdj.mul(cache.liquidOwedWei.value); if (liquidHeldValue <= liquidOwedValue) { // The user is under-collateralized; there is no reward left to give cache.solidHeldUpdateWithReward = cache.liquidHeldWei.value; cache.toLiquidate = Math.getPartialRoundUp(cache.liquidHeldWei.value, cache.heldPrice, cache.owedPriceAdj); } else { cache.solidHeldUpdateWithReward = Math.getPartial(cache.liquidOwedWei.value, cache.owedPriceAdj, cache.heldPrice); cache.toLiquidate = cache.liquidOwedWei.value; } } // ============ Helper Functions ============ /** * Make some basic checks before attempting to liquidate an account. * - Require that the msg.sender is permissioned to use the liquidator account * - Require that the liquid account is liquidatable based on the accounts global value (all assets held and owed, * not just what's being liquidated) */ function checkRequirements( Constants memory constants ) private view { // check credentials for msg.sender Require.that( constants.solidAccount.owner == msg.sender || DOLOMITE_MARGIN.getIsLocalOperator(constants.solidAccount.owner, msg.sender), FILE, "Sender not operator", constants.solidAccount.owner ); // require that the liquidAccount is liquidatable ( Monetary.Value memory liquidSupplyValue, Monetary.Value memory liquidBorrowValue ) = getCurrentAccountValues(constants, constants.liquidAccount); Require.that( liquidSupplyValue.value != 0, FILE, "Liquid account no supply" ); Require.that( DOLOMITE_MARGIN.getAccountStatus(constants.liquidAccount) == Account.Status.Liquid || !isCollateralized(liquidSupplyValue.value, liquidBorrowValue.value, DOLOMITE_MARGIN.getMarginRatio()), FILE, "Liquid account not liquidatable" ); } /** * Returns true if the supplyValue over-collateralizes the borrowValue by the ratio. */ function isCollateralized( uint256 supplyValue, uint256 borrowValue, Decimal.D256 memory ratio ) private pure returns (bool) { uint256 requiredMargin = Decimal.mul(borrowValue, ratio); return supplyValue >= borrowValue.add(requiredMargin); } // ============ Getter Functions ============ /** * Gets the current total supplyValue and borrowValue for some account. Takes into account what * the current index will be once updated. */ function getCurrentAccountValues( Constants memory constants, Account.Info memory account ) private view returns ( Monetary.Value memory, Monetary.Value memory ) { Monetary.Value memory supplyValue; Monetary.Value memory borrowValue; for (uint256 m = 0; m < constants.markets.length; m++) { Types.Par memory par = DOLOMITE_MARGIN.getAccountPar(account, m); if (par.isZero()) { continue; } Types.Wei memory userWei = Interest.parToWei(par, constants.markets[m].index); uint256 assetValue = userWei.value.mul(constants.markets[m].price.value); if (userWei.sign) { supplyValue.value = supplyValue.value.add(assetValue); } else { borrowValue.value = borrowValue.value.add(assetValue); } } return (supplyValue, borrowValue); } /** * Get the updated index and price for every market. */ function getMarketsInfo() private view returns (MarketInfo[] memory) { uint256 numMarkets = DOLOMITE_MARGIN.getNumMarkets(); MarketInfo[] memory markets = new MarketInfo[](numMarkets); for (uint256 m = 0; m < numMarkets; m++) { markets[m] = MarketInfo({ price : DOLOMITE_MARGIN.getMarketPrice(m), index : DOLOMITE_MARGIN.getMarketCurrentIndex(m) }); } return markets; } /** * Pre-populates cache values for some pair of markets. */ function initializeCache( Constants memory constants, uint256 heldMarket, uint256 owedMarket ) private view returns (LiquidatorWithAmmCache memory) { uint256 heldPrice = constants.markets[heldMarket].price.value; uint256 owedPrice = constants.markets[owedMarket].price.value; uint256 owedPriceAdj; if (constants.expiry > 0) { (, Monetary.Price memory owedPricePrice) = constants.EXPIRY_PROXY.getSpreadAdjustedPrices( heldMarket, owedMarket, constants.expiry ); owedPriceAdj = owedPricePrice.value; } else { owedPriceAdj = Decimal.mul( owedPrice, Decimal.onePlus(DOLOMITE_MARGIN.getLiquidationSpreadForPair(heldMarket, owedMarket)) ); } return LiquidatorWithAmmCache({ toLiquidate : 0, solidHeldUpdateWithReward : 0, solidHeldWei : Interest.parToWei( DOLOMITE_MARGIN.getAccountPar(constants.solidAccount, heldMarket), constants.markets[heldMarket].index ), liquidHeldWei : Interest.parToWei( DOLOMITE_MARGIN.getAccountPar(constants.liquidAccount, heldMarket), constants.markets[heldMarket].index ), liquidOwedWei : Interest.parToWei( DOLOMITE_MARGIN.getAccountPar(constants.liquidAccount, owedMarket), constants.markets[owedMarket].index ), heldMarket : heldMarket, owedMarket : owedMarket, heldPrice : heldPrice, owedPrice : owedPrice, owedPriceAdj : owedPriceAdj }); } // ============ Operation-Construction Functions ============ function constructAccountsArray( Constants memory constants, Account.Info[] memory accountsForTrade ) private pure returns (Account.Info[] memory) { Account.Info[] memory accounts = new Account.Info[](accountsForTrade.length + 1); for (uint i = 0; i < accountsForTrade.length; i++) { accounts[i] = accountsForTrade[i]; } assert( accounts[0].owner == constants.solidAccount.owner && accounts[0].number == constants.solidAccount.number ); accounts[accounts.length - 1] = constants.liquidAccount; return accounts; } function constructActionsArray( Constants memory constants, LiquidatorWithAmmCache memory cache, Account.Info[] memory accounts, Actions.ActionArgs[] memory actionsForTrade ) private pure returns (Actions.ActionArgs[] memory) { Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](actionsForTrade.length + 1); if (constants.expiry > 0) { // First action is a trade for closing the expired account // accountId is solidAccount; otherAccountId is liquidAccount actions[0] = Actions.ActionArgs({ actionType : Actions.ActionType.Trade, accountId : 0, amount : Types.AssetAmount({ sign : true, denomination : Types.AssetDenomination.Wei, ref : Types.AssetReference.Delta, value : cache.toLiquidate }), primaryMarketId : cache.owedMarket, secondaryMarketId : cache.heldMarket, otherAddress : address(constants.EXPIRY_PROXY), otherAccountId : accounts.length - 1, data : abi.encode(cache.owedMarket, constants.expiry) }); } else { // First action is a liquidation // accountId is solidAccount; otherAccountId is liquidAccount actions[0] = Actions.ActionArgs({ actionType : Actions.ActionType.Liquidate, accountId : 0, amount : Types.AssetAmount({ sign : true, denomination : Types.AssetDenomination.Wei, ref : Types.AssetReference.Delta, value : cache.toLiquidate }), primaryMarketId : cache.owedMarket, secondaryMarketId : cache.heldMarket, otherAddress : address(0), otherAccountId : accounts.length - 1, data : new bytes(0) }); } for (uint i = 0; i < actionsForTrade.length; i++) { actions[i + 1] = actionsForTrade[i]; } return actions; } }
Calculate the additional owedAmount that can be liquidated until the collateralization of the liquidator account reaches the minLiquidatorRatio. By this point, the cache will be set such that the amount of owedMarket is non-positive and the amount of heldMarket is non-negative./ The user is under-collateralized; there is no reward left to give
function calculateMaxLiquidationAmount( LiquidatorWithAmmCache memory cache ) private pure { uint liquidHeldValue = cache.heldPrice.mul(cache.liquidHeldWei.value); uint liquidOwedValue = cache.owedPriceAdj.mul(cache.liquidOwedWei.value); if (liquidHeldValue <= liquidOwedValue) { cache.solidHeldUpdateWithReward = cache.liquidHeldWei.value; cache.toLiquidate = Math.getPartialRoundUp(cache.liquidHeldWei.value, cache.heldPrice, cache.owedPriceAdj); cache.solidHeldUpdateWithReward = Math.getPartial(cache.liquidOwedWei.value, cache.owedPriceAdj, cache.heldPrice); cache.toLiquidate = cache.liquidOwedWei.value; } }
12,601,689
./full_match/80001/0x7418E7e5c93165da11Db6e73554dC5788D845051/sources/contracts/TSRewardsDrop.sol
Is Token Holder/
function isTokenHolder() public view returns (bool isOwner) { return IGatekeeper(gatekeeperContractAddress).isOwnerOf(memberContractAddress, msg.sender); }
5,690,958
pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "./LibEIP712.sol"; contract LibRequest is LibEIP712 { // solhint-disable max-line-length // Withdraw type hash string private constant REQUEST_TYPE = "WithdrawRequest(address userAddress,uint256 amount,address recipient,bool burn,uint256 nonce)"; bytes32 private constant REQUEST_TYPEHASH = keccak256(abi.encodePacked(REQUEST_TYPE)); // Crosschain withdraw type hash string private constant WITHDRAW_CROSSCHAIN_REQUEST_TYPE = "WithdrawRequest(address userAddress,uint256 amount,string recipient,address defiRelayer,uint256 fee,uint256 nonce)"; bytes32 private constant WITHDRAW_CROSSCHAIN_REQUEST_TYPEHASH = keccak256(abi.encodePacked(WITHDRAW_CROSSCHAIN_REQUEST_TYPE)); // Transfer type hash string private constant TRANSFER_REQUEST_TYPE = "TransferRequest(address userAddress,uint256[] amounts,address[] recipients,uint256 nonce)"; bytes32 private constant TRANSFER_REQUEST_TYPEHASH = keccak256(abi.encodePacked(TRANSFER_REQUEST_TYPE)); struct WithdrawRequest { address userAddress; uint256 amount; address recipient; bool burn; uint256 nonce; } struct WithdrawCrossChainRequest { address userAddress; uint256 amount; string recipient; address defiRelayer; uint256 fee; uint256 nonce; } struct TransferRequest { address userAddress; uint256[] amounts; address[] recipients; uint256 nonce; } /// @dev Calculates Keccak-256 hash of the withdraw request. /// @param request The request structure. /// @return Keccak-256 EIP712 hash of the withdraw request. function getRequestHash(WithdrawRequest memory request) public view returns (bytes32 requestHash) { requestHash = hashEIP712Message(hashRequest(request)); return requestHash; } /// @dev Calculates Keccak-256 hash of the crosschain withdraw request. /// @param request The request structure. /// @return Keccak-256 EIP712 hash of the crosschain withdraw request. function getWithdrawCrossChainRequestHash(WithdrawCrossChainRequest memory request) public view returns (bytes32 requestHash) { requestHash = hashEIP712Message(hashWithdrawCrossChainRequest(request)); return requestHash; } /// @dev Calculates Keccak-256 hash of the transfer request. /// @param request The request structure. /// @return Keccak-256 EIP712 hash of the transfer request. function getTransferRequestHash(TransferRequest memory request) public view returns (bytes32 requestHash) { requestHash = hashEIP712Message(hashTransferRequest(request)); return requestHash; } /// @dev Calculates EIP712 hash of the withdraw request. /// @param request The request structure. /// @return EIP712 hash of the withdraw request. function hashRequest(WithdrawRequest memory request) internal pure returns (bytes32 result) { return keccak256(abi.encode( REQUEST_TYPEHASH, request.userAddress, request.amount, request.recipient, request.burn, request.nonce )); } /// @dev Calculates EIP712 hash of the crosschain withdraw request. /// @param request The request structure. /// @return EIP712 hash of the crosschain withdraw request. function hashWithdrawCrossChainRequest(WithdrawCrossChainRequest memory request) internal pure returns (bytes32 result) { return keccak256(abi.encode( WITHDRAW_CROSSCHAIN_REQUEST_TYPEHASH, request.userAddress, request.amount, keccak256(abi.encodePacked(request.recipient)), request.defiRelayer, request.fee, request.nonce )); } /// @dev Calculates EIP712 hash of the transfer request. /// @param request The request structure. /// @return EIP712 hash of the transfer request. function hashTransferRequest(TransferRequest memory request) internal pure returns (bytes32 result) { return keccak256(abi.encode( TRANSFER_REQUEST_TYPEHASH, request.userAddress, keccak256(abi.encodePacked(request.amounts)), keccak256(abi.encodePacked(request.recipients)), request.nonce )); } }
Calculates EIP712 hash of the transfer request. request The request structure. return EIP712 hash of the transfer request.
function hashTransferRequest(TransferRequest memory request) internal pure returns (bytes32 result) { return keccak256(abi.encode( TRANSFER_REQUEST_TYPEHASH, request.userAddress, keccak256(abi.encodePacked(request.amounts)), keccak256(abi.encodePacked(request.recipients)), request.nonce )); }
12,772,515
./partial_match/137/0xf251b57Dd11B708CB0385F1f058Ec1211FC58B56/sources/ChildERC20Proxified.sol
Withdraw tokens amount tokens/
function withdraw(uint256 amount) public payable { _withdraw(msg.sender, amount); }
3,513,689
/** *Submitted for verification at Etherscan.io on 2020-09-26 */ pragma solidity ^0.6.12; // SPDX-License-Identifier: MIT /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ 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) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface Jplus { function balanceOf(address) external returns (uint); function transferFrom(address, address, uint) external returns (bool); function transfer(address, uint) external returns (bool); } contract Jpluslock is Ownable { using SafeMath for uint; address public constant tokenAddress = 0xE2779DF83D0C75Df4d2e6173Af671Adb5Aa56eF6; uint public constant tokensLocked = 10000e18; // 10,000 Tokens Locked uint public constant unlockRate = 67000; // 200 Token unlock in every month to 4 years uint public constant lockDuration = 30 days; // CAN WITHDRAW AFTER EVERY 30 DAYS uint public lastClaimedTime; uint public deployTime; constructor() public { deployTime = now; lastClaimedTime = now; } function claim() public onlyOwner { uint pendingUnlocked = getPendingUnlocked(); uint contractBalance = Jplus(tokenAddress).balanceOf(address(this)); uint amountToSend = pendingUnlocked; if (contractBalance < pendingUnlocked) { amountToSend = contractBalance; } require(Jplus(tokenAddress).transfer(owner, amountToSend), "Could not transfer Tokens."); lastClaimedTime = now; } function getPendingUnlocked() public view returns (uint) { uint timeDiff = now.sub(lastClaimedTime); uint pendingUnlocked = tokensLocked .mul(unlockRate) .mul(timeDiff) .div(lockDuration) .div(1e4); return pendingUnlocked; } // function to allow admin to claim *other* ERC20 tokens sent to this contract (by mistake) function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != tokenAddress, "Cannot transfer out reward tokens"); Jplus(_tokenAddr).transfer(_to, _amount); } }
function to allow admin to claim other ERC20 tokens sent to this contract (by mistake)
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != tokenAddress, "Cannot transfer out reward tokens"); Jplus(_tokenAddr).transfer(_to, _amount); }
10,653,452
./partial_match/3/0x863534bDC6e93d0D0e5a67293CBf1636E1Fc984d/sources/UtilityTokenETHOnly.sol
buy exchange rate return rate multiplied at 1e6/
function buyExchangeRate() internal view returns(uint256) { return _buyExchangeRate; }
5,247,326
//Address: 0xC9d46De506D91530631Ba356a1a37c0b11327784 //Contract name: Cryptoverse //Balance: 0 Ether //Verification Date: 12/11/2017 //Transacion Count: 15 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @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 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title 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 Announceable is Ownable { string public announcement; function setAnnouncement(string value) public onlyOwner { announcement = value; } } contract Withdrawable { address public withdrawOwner; function Withdrawable(address _withdrawOwner) public { require(_withdrawOwner != address(0)); withdrawOwner = _withdrawOwner; } /** * Transfers all the funs on this contract to the sender which must be withdrawOwner. */ function withdraw() public { withdrawTo(msg.sender, this.balance); } /** * Transfers the given amount of funds to given beneficiary address. Must be called by the withdrawOwner. */ function withdrawTo(address _beneficiary, uint _amount) public { require(msg.sender == withdrawOwner); require(_beneficiary != address(0)); require(_amount > 0); _beneficiary.transfer(_amount); } /** * Transfer withdraw ownership to another account. */ function setWithdrawOwner(address _newOwner) public { require(msg.sender == withdrawOwner); require(_newOwner != address(0)); withdrawOwner = _newOwner; } } contract Cryptoverse is StandardToken, Ownable, Announceable, Withdrawable { using SafeMath for uint; string public constant name = "Cryptoverse Sector"; string public constant symbol = "CVS"; uint8 public constant decimals = 0; /** * Raised whenever grid sector is updated. The event will be raised for any update operation, even when nothing * effectively changes. */ event SectorUpdated( uint16 indexed offset, address indexed owner, string link, string content, string title, bool nsfw ); /** Structure holding the information about the sector state. */ struct Sector { address owner; string link; string content; string title; bool nsfw; bool forceNsfw; } /** Time of the last purchase (or contract creation time). */ uint public lastPurchaseTimestamp = now; /** Whether owner is allowed to claim free sectors. */ bool public allowClaiming = true; /** The pricing */ uint[13] public prices = [1000 finney, 800 finney, 650 finney, 550 finney, 500 finney, 450 finney, 400 finney, 350 finney, 300 finney, 250 finney, 200 finney, 150 finney, 100 finney]; uint8 public constant width = 125; uint8 public constant height = 80; uint16 public constant length = 10000; /** * The current state of the grid is stored here. * * The grid has coordinates like screenspace/contentspace has: The [0;0] coordinate is at the top left corner. X axis * goes from top to bottom, Y axis goes from left to right. * * The coordinates are stored as grid[transform(x, y)] = grid[x + 125 * y], . */ Sector[10000] public grid; function Cryptoverse() Withdrawable(msg.sender) public { } function () public payable { // how many sectors is sender going to buy // NOTE: purchase via fallback is at flat price uint sectorCount = msg.value / 1000 finney; require(sectorCount > 0); // fire transfer event ahead of update event Transfer(address(0), msg.sender, sectorCount); // now find as many free sectors for (uint16 offset = 0; offset < length; offset++) { Sector storage sector = grid[offset]; if (sector.owner == address(0)) { // free sector setSectorOwnerInternal(offset, msg.sender, false); sectorCount--; if (sectorCount == 0) { return; } } } // not enough available free sectors revert(); } /** * Purchases the sectors at given offsets. The array length must be even and the bounds must be within grid size. */ function buy(uint16[] memory _offsets) public payable { require(_offsets.length > 0); uint cost = _offsets.length * currentPrice(); require(msg.value >= cost); // fire transfer event ahead of update event Transfer(address(0), msg.sender, _offsets.length); for (uint i = 0; i < _offsets.length; i++) { setSectorOwnerInternal(_offsets[i], msg.sender, false); } } /** * !override * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public returns (bool result) { result = super.transfer(_to, _value); if (result && _value > 0) { transferSectorOwnerInternal(_value, msg.sender, _to); } } /** * !override * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool result) { result = super.transferFrom(_from, _to, _value); if (result && _value > 0) { transferSectorOwnerInternal(_value, _from, _to); } } /** * Allows to transfer the sectors at given coordinates to a new owner. */ function transferSectors(uint16[] memory _offsets, address _to) public returns (bool result) { result = super.transfer(_to, _offsets.length); if (result) { for (uint i = 0; i < _offsets.length; i++) { Sector storage sector = grid[_offsets[i]]; require(sector.owner == msg.sender); setSectorOwnerInternal(_offsets[i], _to, true); } } } /** * Sets the state of the sector by its rightful owner. */ function set(uint16[] memory _offsets, string _link, string _content, string _title, bool _nsfw) public { require(_offsets.length > 0); for (uint i = 0; i < _offsets.length; i++) { Sector storage sector = grid[_offsets[i]]; require(msg.sender == sector.owner); sector.link = _link; sector.content = _content; sector.title = _title; sector.nsfw = _nsfw; onUpdatedInternal(_offsets[i], sector); } } /** * Sets the owner of the sector. * * - Does not check whether caller is allowed to do that. * - Does not manipulate balances upon transfer (ensure to call appropriate parent functions). */ function setSectorOwnerInternal(uint16 _offset, address _to, bool _canTransfer) internal { require(_to != address(0)); // coordinate checks is done by an array type Sector storage sector = grid[_offset]; // sector must be empty (not purchased yet) address from = sector.owner; bool isTransfer = (from != address(0)); require(_canTransfer || !isTransfer); // variable is a reference to the storage, this will persist the info sector.owner = _to; // NOTE: do not manipulate balance on transfer, only on initial purchase if (!isTransfer) { // initial sector purchase totalSupply = totalSupply.add(1); balances[_to] = balances[_to].add(1); lastPurchaseTimestamp = now; } onUpdatedInternal(_offset, sector); } /** * Transfers the owner of _value implicit sectors. * * !throws Reverts when the _from does not own as many as _value sectors. */ function transferSectorOwnerInternal(uint _value, address _from, address _to) internal { require(_value > 0); require(_from != address(0)); require(_to != address(0)); uint sectorCount = _value; for (uint16 offsetPlusOne = length; offsetPlusOne > 0; offsetPlusOne--) { Sector storage sector = grid[offsetPlusOne - 1]; if (sector.owner == _from) { setSectorOwnerInternal(offsetPlusOne - 1, _to, true); sectorCount--; if (sectorCount == 0) { // we have transferred exactly _value ownerships return; } } } // _from does not own at least _value sectors revert(); } function setForceNsfw(uint16[] memory _offsets, bool _nsfw) public onlyOwner { require(_offsets.length > 0); for (uint i = 0; i < _offsets.length; i++) { Sector storage sector = grid[_offsets[i]]; sector.forceNsfw = _nsfw; onUpdatedInternal(_offsets[i], sector); } } /** * Gets the current price in wei. */ function currentPrice() public view returns (uint) { uint sinceLastPurchase = (block.timestamp - lastPurchaseTimestamp); for (uint i = 0; i < prices.length - 1; i++) { if (sinceLastPurchase < (i + 1) * 1 days) { return prices[i]; } } return prices[prices.length - 1]; } function transform(uint8 _x, uint8 _y) public pure returns (uint16) { uint16 offset = _y; offset = offset * width; offset = offset + _x; return offset; } function untransform(uint16 _offset) public pure returns (uint8, uint8) { uint8 y = uint8(_offset / width); uint8 x = uint8(_offset - y * width); return (x, y); } function claimA() public { claimInternal(60, 37, 5, 5); } function claimB1() public { claimInternal(0, 0, 62, 1); } function claimB2() public { claimInternal(62, 0, 63, 1); } function claimC1() public { claimInternal(0, 79, 62, 1); } function claimC2() public { claimInternal(62, 79, 63, 1); } function claimD() public { claimInternal(0, 1, 1, 78); } function claimE() public { claimInternal(124, 1, 1, 78); } function claimF() public { claimInternal(20, 20, 8, 8); } function claimG() public { claimInternal(45, 10, 6, 10); } function claimH1() public { claimInternal(90, 50, 8, 10); } function claimH2() public { claimInternal(98, 50, 7, 10); } function claimI() public { claimInternal(94, 22, 7, 7); } function claimJ() public { claimInternal(48, 59, 12, 8); } /** * Closes the opportunity to claim free blocks for the owner for good. */ function closeClaims() public onlyOwner { allowClaiming = false; } function claimInternal(uint8 _left, uint8 _top, uint8 _width, uint8 _height) internal { require(allowClaiming); // NOTE: SafeMath not needed, we operate on safe numbers uint8 _right = _left + _width; uint8 _bottom = _top + _height; uint area = _width; area = area * _height; Transfer(address(0), owner, area); for (uint8 x = _left; x < _right; x++) { for (uint8 y = _top; y < _bottom; y++) { setSectorOwnerInternal(transform(x, y), owner, false); } } } /** * Raises SectorUpdated event. */ function onUpdatedInternal(uint16 _offset, Sector storage _sector) internal { SectorUpdated( _offset, _sector.owner, _sector.link, _sector.content, _sector.title, _sector.nsfw || _sector.forceNsfw ); } }
Transfers all the funs on this contract to the sender which must be withdrawOwner./
function withdraw() public { withdrawTo(msg.sender, this.balance); }
12,724,207
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul interface DharmaTradeReserveV14Interface { event TRADE504( //inject NONSTANDARD NAMING address account, address suppliedAsset, address receivedAsset, address retainedAsset, uint256 suppliedAmount, uint256 recievedAmount, uint256 retainedAmount ); event ROLEMODIFIED267(Role indexed role, address account); //inject NONSTANDARD NAMING event ROLEPAUSED190(Role indexed role); //inject NONSTANDARD NAMING event ROLEUNPAUSED454(Role indexed role); //inject NONSTANDARD NAMING event ETHERRECEIVED220(address sender, uint256 amount); //inject NONSTANDARD NAMING event GASRESERVEREFILLED158(uint256 etherAmount); //inject NONSTANDARD NAMING enum Role { // # DEPOSIT_MANAGER, // 0 ADJUSTER, // 1 WITHDRAWAL_MANAGER, // 2 RESERVE_TRADER, // 3 PAUSER, // 4 GAS_RESERVE_REFILLER // 5 } enum TradeType { DAI_TO_TOKEN, DAI_TO_ETH, ETH_TO_DAI, TOKEN_TO_DAI, ETH_TO_TOKEN, TOKEN_TO_ETH, TOKEN_TO_TOKEN } struct RoleStatus { address account; bool paused; } function TRADEDAIFORETHERV2941( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAIV2888( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function TRADEDAIFORTOKEN895( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAI139( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought); function TRADETOKENFORETHER779( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function TRADEETHERFORTOKEN640( //inject NONSTANDARD NAMING address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold); function TRADEETHERFORTOKENUSINGETHERIZER777( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function TRADETOKENFORTOKEN271( //inject NONSTANDARD NAMING ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function TRADETOKENFORTOKENUSINGRESERVES584( //inject NONSTANDARD NAMING ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold); function TRADEDAIFORETHERUSINGRESERVESV2260( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV2493( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADEDAIFORTOKENUSINGRESERVES81( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI350( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADETOKENFORETHERUSINGRESERVES547( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function TRADEETHERFORTOKENUSINGRESERVES877( //inject NONSTANDARD NAMING address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function FINALIZEETHERDEPOSIT986( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external; function FINALIZEDAIDEPOSIT934( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external; function FINALIZEDHARMADAIDEPOSIT513( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external; function MINT202(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING function REDEEM16(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING function TRADEDDAIFORUSDC654( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function TRADEUSDCFORDDAI12( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function REFILLGASRESERVE448(uint256 etherAmount) external; //inject NONSTANDARD NAMING function WITHDRAWUSDC439(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAI337(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDHARMADAI28(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWUSDCTOPRIMARYRECIPIENT2(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAITOPRIMARYRECIPIENT618(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWETHER691( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external; function WITHDRAW743( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function CALLANY310( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function SETDAILIMIT40(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETETHERLIMIT732(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETPRIMARYUSDCRECIPIENT254(address recipient) external; //inject NONSTANDARD NAMING function SETPRIMARYDAIRECIPIENT844(address recipient) external; //inject NONSTANDARD NAMING function SETROLE668(Role role, address account) external; //inject NONSTANDARD NAMING function REMOVEROLE431(Role role) external; //inject NONSTANDARD NAMING function PAUSE546(Role role) external; //inject NONSTANDARD NAMING function UNPAUSE892(Role role) external; //inject NONSTANDARD NAMING function ISPAUSED688(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING function ISROLE537(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING function ISDHARMASMARTWALLET489( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet); function GETDEPOSITMANAGER179() external view returns (address depositManager); //inject NONSTANDARD NAMING function GETADJUSTER264() external view returns (address adjuster); //inject NONSTANDARD NAMING function GETRESERVETRADER364() external view returns (address reserveTrader); //inject NONSTANDARD NAMING function GETWITHDRAWALMANAGER637() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING function GETPAUSER909() external view returns (address pauser); //inject NONSTANDARD NAMING function GETGASRESERVEREFILLER909() external view returns (address gasReserveRefiller); //inject NONSTANDARD NAMING function GETRESERVES500() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ); function GETDAILIMIT177() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ); function GETETHERLIMIT782() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING function GETPRIMARYUSDCRECIPIENT773() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETPRIMARYDAIRECIPIENT581() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETIMPLEMENTATION743() external view returns (address implementation); //inject NONSTANDARD NAMING function GETINSTANCE306() external pure returns (address instance); //inject NONSTANDARD NAMING function GETVERSION428() external view returns (uint256 version); //inject NONSTANDARD NAMING } interface ERC20Interface { function BALANCEOF7(address) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE806(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE503(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER250(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM572(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING } interface DTokenInterface { function MINT202(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING function REDEEM16(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING function REDEEMUNDERLYING444(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING function BALANCEOF7(address) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING522(address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER250(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function APPROVE806(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function EXCHANGERATECURRENT321() external view returns (uint256); //inject NONSTANDARD NAMING } interface TradeHelperInterface { function TRADEUSDCFORDDAI12( //inject NONSTANDARD NAMING uint256 amountUSDC, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function TRADEDDAIFORUSDC654( //inject NONSTANDARD NAMING uint256 amountDai, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function GETEXPECTEDDAI546(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING function GETEXPECTEDUSDC60(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING } interface UniswapV2Interface { function SWAPTOKENSFOREXACTTOKENS381( //inject NONSTANDARD NAMING uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPEXACTTOKENSFORTOKENS55( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPEXACTTOKENSFORETH928( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPTOKENSFOREXACTETH806( //inject NONSTANDARD NAMING uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPETHFOREXACTTOKENS164( //inject NONSTANDARD NAMING uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function SWAPEXACTETHFORTOKENS988( //inject NONSTANDARD NAMING uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface EtherReceiverInterface { function SETTLEETHER224() external; //inject NONSTANDARD NAMING } library SafeMath { function ADD577(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB328(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function MUL983(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV568(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, "SafeMath: division by zero"); return a / b; } } contract TwoStepOwnable { event OWNERSHIPTRANSFERRED746( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; function TRANSFEROWNERSHIP314(address newOwner) external ONLYOWNER349 { //inject NONSTANDARD NAMING require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } function CANCELOWNERSHIPTRANSFER449() external ONLYOWNER349 { //inject NONSTANDARD NAMING delete _newPotentialOwner; } function ACCEPTOWNERSHIP100() external { //inject NONSTANDARD NAMING require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OWNERSHIPTRANSFERRED746(_owner, msg.sender); _owner = msg.sender; } function OWNER217() external view returns (address) { //inject NONSTANDARD NAMING return _owner; } function ISOWNER119() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } modifier ONLYOWNER349() { //inject NONSTANDARD NAMING require(ISOWNER119(), "TwoStepOwnable: caller is not the owner."); _; } } contract DharmaTradeReserveV14ImplementationStaging is DharmaTradeReserveV14Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a "primary recipient" the withdrawal manager can transfer Dai to. address private _primaryDaiRecipient; // Maintain a "primary recipient" the withdrawal manager can transfer USDC to. address private _primaryUSDCRecipient; // Maintain a maximum allowable transfer size (in Dai) for the deposit manager. uint256 private _daiLimit; // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. uint256 private _etherLimit; bool private _originatesFromReserveTrader; // unused, don't change storage layout uint256 private constant _version68 = 1014; //inject NONSTANDARD NAMING // This contract interacts with USDC, Dai, and Dharma Dai. ERC20Interface internal constant _usdc291 = ERC20Interface( //inject NONSTANDARD NAMING 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); ERC20Interface internal constant _dai607 = ERC20Interface( //inject NONSTANDARD NAMING 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _etherizer675 = ERC20Interface( //inject NONSTANDARD NAMING 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); DTokenInterface internal constant _ddai635 = DTokenInterface( //inject NONSTANDARD NAMING 0x00000000001876eB1444c986fD502e618c587430 ); TradeHelperInterface internal constant _trade_helper419 = TradeHelperInterface( //inject NONSTANDARD NAMING 0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d ); UniswapV2Interface internal constant _uniswap_router857 = UniswapV2Interface( //inject NONSTANDARD NAMING 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); EtherReceiverInterface internal constant _eth_receiver286 = EtherReceiverInterface( //inject NONSTANDARD NAMING 0xaf84687D21736F5E06f738c6F065e88890465E7c ); address internal constant _weth890 = address( //inject NONSTANDARD NAMING 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ); address internal constant _gas_reserve614 = address( //inject NONSTANDARD NAMING 0x09cd826D4ABA4088E1381A1957962C946520952d // staging version ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _create2_header144 = bytes21( //inject NONSTANDARD NAMING 0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _wallet_creation_code_header349 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING bytes28 internal constant _wallet_creation_code_footer225 = bytes28( //inject NONSTANDARD NAMING 0x00000000000000000000000000000000000000000000000000000000 ); // Include a payable fallback so that the contract can receive Ether payments. function () external payable { emit ETHERRECEIVED220(msg.sender, msg.value); } function TRADEDAIFORETHERV2941( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _TRANSFERINTOKEN55(_dai607, msg.sender, daiAmount); // Trade Dai for Ether. totalDaiSold = _TRADEDAIFORETHER930( daiAmount, quotedEtherAmount, deadline, false ); } function TRADETOKENFORETHER779( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought) { // Transfer the tokens from the caller and revert on failure. _TRANSFERINTOKEN55(token, msg.sender, tokenAmount); // Trade tokens for Ether. totalEtherBought = _TRADETOKENFORETHER585( token, tokenAmount, quotedEtherAmount, deadline, false ); // Transfer the quoted Ether amount to the caller. _TRANSFERETHER189(msg.sender, quotedEtherAmount); } function TRADEDAIFORTOKEN895( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _TRANSFERINTOKEN55(_dai607, msg.sender, daiAmount); // Trade Dai for specified token. totalDaiSold = _TRADEDAIFORTOKEN293( token, daiAmount, quotedTokenAmount, deadline, routeThroughEther, false ); } function TRADEDAIFORETHERUSINGRESERVESV2260( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _REDEEMDDAIIFNECESSARY474(daiAmountFromReserves); // Trade Dai for Ether using reserves. totalDaiSold = _TRADEDAIFORETHER930( daiAmountFromReserves, quotedEtherAmount, deadline, true ); } function TRADETOKENFORETHERUSINGRESERVES547( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) { // Trade tokens for Ether using reserves. totalEtherBought = _TRADETOKENFORETHER585( token, tokenAmountFromReserves, quotedEtherAmount, deadline, true ); } function TRADEETHERFORDAIV2888( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Trade Ether for Dai. totalDaiBought = _TRADEETHERFORDAI152( msg.value, quotedDaiAmount, deadline, false ); // Transfer the Dai to the caller and revert on failure. _TRANSFERTOKEN426(_dai607, msg.sender, quotedDaiAmount); } function TRADEETHERFORTOKEN640( //inject NONSTANDARD NAMING address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold) { // Trade Ether for the specified token. totalEtherSold = _TRADEETHERFORTOKEN294( token, msg.value, quotedTokenAmount, deadline, false ); } function TRADEETHERFORTOKENUSINGETHERIZER777( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold) { // Transfer the Ether from the caller and revert on failure. _TRANSFERINTOKEN55(_etherizer675, msg.sender, etherAmount); // Trade Ether for the specified token. totalEtherSold = _TRADEETHERFORTOKEN294( token, etherAmount, quotedTokenAmount, deadline, false ); } function TRADETOKENFORDAI139( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought) { // Transfer the token from the caller and revert on failure. _TRANSFERINTOKEN55(token, msg.sender, tokenAmount); // Trade the token for Dai. totalDaiBought = _TRADETOKENFORDAI325( token, tokenAmount, quotedDaiAmount, deadline, routeThroughEther, false ); // Transfer the quoted Dai amount to the caller and revert on failure. _TRANSFERTOKEN426(_dai607, msg.sender, quotedDaiAmount); } function TRADETOKENFORTOKEN271( //inject NONSTANDARD NAMING ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalTokensSold) { // Transfer the token from the caller and revert on failure. _TRANSFERINTOKEN55(tokenProvided, msg.sender, tokenProvidedAmount); totalTokensSold = _TRADETOKENFORTOKEN365( msg.sender, tokenProvided, tokenReceived, tokenProvidedAmount, quotedTokenReceivedAmount, deadline, routeThroughEther ); } function TRADETOKENFORTOKENUSINGRESERVES584( //inject NONSTANDARD NAMING ERC20Interface tokenProvidedFromReserves, address tokenReceived, uint256 tokenProvidedAmountFromReserves, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalTokensSold) { totalTokensSold = _TRADETOKENFORTOKEN365( address(this), tokenProvidedFromReserves, tokenReceived, tokenProvidedAmountFromReserves, quotedTokenReceivedAmount, deadline, routeThroughEther ); } function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV2493( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade Ether for Dai using reserves. totalDaiBought = _TRADEETHERFORDAI152( etherAmountFromReserves, quotedDaiAmount, deadline, true ); // Mint dDai using the received Dai. totalDDaiMinted = _ddai635.MINT202(totalDaiBought); } function TRADEETHERFORTOKENUSINGRESERVES877( //inject NONSTANDARD NAMING address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) { // Trade Ether for token using reserves. totalEtherSold = _TRADEETHERFORTOKEN294( token, etherAmountFromReserves, quotedTokenAmount, deadline, true ); } function TRADEDAIFORTOKENUSINGRESERVES81( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. _REDEEMDDAIIFNECESSARY474(daiAmountFromReserves); // Trade Dai for token using reserves. totalDaiSold = _TRADEDAIFORTOKEN293( token, daiAmountFromReserves, quotedTokenAmount, deadline, routeThroughEther, true ); } function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI350( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR375(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade the token for Dai using reserves. totalDaiBought = _TRADETOKENFORDAI325( token, tokenAmountFromReserves, quotedDaiAmount, deadline, routeThroughEther, true ); // Mint dDai using the received Dai. totalDDaiMinted = _ddai635.MINT202(totalDaiBought); } function FINALIZEDAIDEPOSIT934( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external ONLYOWNEROR375(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET467(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(daiAmount < _daiLimit, "Transfer size exceeds the limit."); // Transfer the Dai to the specified smart wallet. _TRANSFERTOKEN426(_dai607, smartWallet, daiAmount); } function FINALIZEDHARMADAIDEPOSIT513( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external ONLYOWNEROR375(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET467(smartWallet, initialUserSigningKey); // Get the current dDai exchange rate. uint256 exchangeRate = _ddai635.EXCHANGERATECURRENT321(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.MUL983(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit."); // Transfer the dDai to the specified smart wallet. _TRANSFERTOKEN426(ERC20Interface(address(_ddai635)), smartWallet, dDaiAmount); } function FINALIZEETHERDEPOSIT986( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external ONLYOWNEROR375(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET467(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(etherAmount < _etherLimit, "Transfer size exceeds the limit."); // Transfer the Ether to the specified smart wallet. _TRANSFERETHER189(smartWallet, etherAmount); } function MINT202( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 dDaiMinted) { // Use the specified amount of Dai to mint dDai. dDaiMinted = _ddai635.MINT202(daiAmount); } function REDEEM16( //inject NONSTANDARD NAMING uint256 dDaiAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 daiReceived) { // Redeem the specified amount of dDai for Dai. daiReceived = _ddai635.REDEEM16(dDaiAmount); } function TRADEUSDCFORDDAI12( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _trade_helper419.TRADEUSDCFORDDAI12( usdcAmount, quotedDaiEquivalentAmount ); } function TRADEDDAIFORUSDC654( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external ONLYOWNEROR375(Role.ADJUSTER) returns (uint256 usdcReceived) { usdcReceived = _trade_helper419.TRADEDDAIFORUSDC654( daiEquivalentAmount, quotedUSDCAmount ); } function REFILLGASRESERVE448(uint256 etherAmount) external ONLYOWNEROR375(Role.GAS_RESERVE_REFILLER) { //inject NONSTANDARD NAMING // Transfer the Ether to the gas reserve. _TRANSFERETHER189(_gas_reserve614, etherAmount); emit GASRESERVEREFILLED158(etherAmount); } function WITHDRAWUSDCTOPRIMARYRECIPIENT2( //inject NONSTANDARD NAMING uint256 usdcAmount ) external ONLYOWNEROR375(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryUSDCRecipient; require( primaryRecipient != address(0), "No USDC primary recipient currently set." ); // Transfer the supplied USDC amount to the primary recipient. _TRANSFERTOKEN426(_usdc291, primaryRecipient, usdcAmount); } function WITHDRAWDAITOPRIMARYRECIPIENT618( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR375(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryDaiRecipient; require( primaryRecipient != address(0), "No Dai primary recipient currently set." ); // Transfer the supplied Dai amount to the primary recipient. _TRANSFERTOKEN426(_dai607, primaryRecipient, daiAmount); } function WITHDRAWUSDC439( //inject NONSTANDARD NAMING address recipient, uint256 usdcAmount ) external ONLYOWNER349 { // Transfer the USDC to the specified recipient. _TRANSFERTOKEN426(_usdc291, recipient, usdcAmount); } function WITHDRAWDAI337( //inject NONSTANDARD NAMING address recipient, uint256 daiAmount ) external ONLYOWNER349 { // Transfer the Dai to the specified recipient. _TRANSFERTOKEN426(_dai607, recipient, daiAmount); } function WITHDRAWDHARMADAI28( //inject NONSTANDARD NAMING address recipient, uint256 dDaiAmount ) external ONLYOWNER349 { // Transfer the dDai to the specified recipient. _TRANSFERTOKEN426(ERC20Interface(address(_ddai635)), recipient, dDaiAmount); } function WITHDRAWETHER691( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external ONLYOWNER349 { // Transfer the Ether to the specified recipient. _TRANSFERETHER189(recipient, etherAmount); } function WITHDRAW743( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external ONLYOWNER349 returns (bool success) { // Transfer the token to the specified recipient. success = token.TRANSFER250(recipient, amount); } function CALLANY310( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external ONLYOWNER349 returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = target.call.value(amount)(data); } function SETDAILIMIT40(uint256 daiAmount) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new limit. _daiLimit = daiAmount; } function SETETHERLIMIT732(uint256 etherAmount) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new limit. _etherLimit = etherAmount; } function SETPRIMARYUSDCRECIPIENT254(address recipient) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryUSDCRecipient = recipient; } function SETPRIMARYDAIRECIPIENT844(address recipient) external ONLYOWNER349 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryDaiRecipient = recipient; } function PAUSE546(Role role) external ONLYOWNEROR375(Role.PAUSER) { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit ROLEPAUSED190(role); } function UNPAUSE892(Role role) external ONLYOWNER349 { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit ROLEUNPAUSED454(role); } function SETROLE668(Role role, address account) external ONLYOWNER349 { //inject NONSTANDARD NAMING require(account != address(0), "Must supply an account."); _SETROLE96(role, account); } function REMOVEROLE431(Role role) external ONLYOWNER349 { //inject NONSTANDARD NAMING _SETROLE96(role, address(0)); } function ISPAUSED688(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING paused = _ISPAUSED235(role); } function ISROLE537(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = _ISROLE773(role); } function ISDHARMASMARTWALLET489( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet) { dharmaSmartWallet = _ISSMARTWALLET673(smartWallet, initialUserSigningKey); } function GETDEPOSITMANAGER179() external view returns (address depositManager) { //inject NONSTANDARD NAMING depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account; } function GETADJUSTER264() external view returns (address adjuster) { //inject NONSTANDARD NAMING adjuster = _roles[uint256(Role.ADJUSTER)].account; } function GETRESERVETRADER364() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account; } function GETWITHDRAWALMANAGER637() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account; } function GETPAUSER909() external view returns (address pauser) { //inject NONSTANDARD NAMING pauser = _roles[uint256(Role.PAUSER)].account; } function GETGASRESERVEREFILLER909() external view returns (address gasReserveRefiller) { //inject NONSTANDARD NAMING gasReserveRefiller = _roles[uint256(Role.GAS_RESERVE_REFILLER)].account; } function GETRESERVES500() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ) { dai = _dai607.BALANCEOF7(address(this)); dDai = _ddai635.BALANCEOF7(address(this)); dDaiUnderlying = _ddai635.BALANCEOFUNDERLYING522(address(this)); } function GETDAILIMIT177() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _daiLimit; dDaiAmount = (daiAmount.MUL983(1e18)).DIV568(_ddai635.EXCHANGERATECURRENT321()); } function GETETHERLIMIT782() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING etherAmount = _etherLimit; } function GETPRIMARYUSDCRECIPIENT773() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryUSDCRecipient; } function GETPRIMARYDAIRECIPIENT581() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryDaiRecipient; } function GETIMPLEMENTATION743() external view returns ( //inject NONSTANDARD NAMING address implementation ) { (bool ok, bytes memory returnData) = address( 0x481B1a16E6675D33f8BBb3a6A58F5a9678649718 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } function GETINSTANCE306() external pure returns (address instance) { //inject NONSTANDARD NAMING instance = address(0x09cd826D4ABA4088E1381A1957962C946520952d); } function GETVERSION428() external view returns (uint256 version) { //inject NONSTANDARD NAMING version = _version68; } function _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(ERC20Interface token, uint256 amount) internal { //inject NONSTANDARD NAMING if (token.ALLOWANCE503(address(this), address(_uniswap_router857)) < amount) { // Try removing approval for Uniswap router first as a workaround for unusual tokens. (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector( token.APPROVE806.selector, address(_uniswap_router857), uint256(0) ) ); // Grant approval for Uniswap router to transfer tokens on behalf of this contract. (success, data) = address(token).call( abi.encodeWithSelector( token.APPROVE806.selector, address(_uniswap_router857), uint256(-1) ) ); if (!success) { // Some really janky tokens only allow setting approval up to current balance. (success, data) = address(token).call( abi.encodeWithSelector( token.APPROVE806.selector, address(_uniswap_router857), amount ) ); } require( success && (data.length == 0 || abi.decode(data, (bool))), "Token approval for Uniswap router failed." ); } } function _TRADEETHERFORDAI152( //inject NONSTANDARD NAMING uint256 etherAmount, uint256 quotedDaiAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Establish path from Ether to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( _weth890, address(_dai607), false ); // Trade Ether for Dai on Uniswap (send to this contract). amounts = _uniswap_router857.SWAPEXACTETHFORTOKENS988.value(etherAmount)( quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; _FIRETRADEEVENT684( fromReserves, TradeType.ETH_TO_DAI, address(0), etherAmount, quotedDaiAmount, totalDaiBought.SUB328(quotedDaiAmount) ); } function _TRADEDAIFORETHER930( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path from Dai to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(_dai607), _weth890, false ); // Trade Dai for quoted Ether amount on Uniswap (send to appropriate recipient). amounts = _uniswap_router857.SWAPTOKENSFOREXACTETH806( quotedEtherAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _FIRETRADEEVENT684( fromReserves, TradeType.DAI_TO_ETH, address(0), daiAmount, quotedEtherAmount, daiAmount.SUB328(totalDaiSold) ); } function _TRADEETHERFORTOKEN294( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherSold) { // Establish path from Ether to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( _weth890, address(token), false ); // Trade Ether for quoted token amount on Uniswap and send to appropriate recipient. amounts = _uniswap_router857.SWAPETHFOREXACTTOKENS164.value(etherAmount)( quotedTokenAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalEtherSold = amounts[0]; _FIRETRADEEVENT684( fromReserves, TradeType.ETH_TO_TOKEN, address(token), etherAmount, quotedTokenAmount, etherAmount.SUB328(totalEtherSold) ); } function _TRADETOKENFORETHER585( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalEtherBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(token, tokenAmount); // Establish path from target token to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(token), _weth890, false ); // Trade tokens for quoted Ether amount on Uniswap (send to this contract). amounts = _uniswap_router857.SWAPEXACTTOKENSFORETH928( tokenAmount, quotedEtherAmount, path, address(this), deadline ); totalEtherBought = amounts[1]; _FIRETRADEEVENT684( fromReserves, TradeType.TOKEN_TO_ETH, address(token), tokenAmount, quotedEtherAmount, totalEtherBought.SUB328(quotedEtherAmount) ); } function _TRADEDAIFORTOKEN293( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiSold) { // Establish path (direct or routed through Ether) from Dai to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(_dai607), address(token), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap and send to appropriate recipient. amounts = _uniswap_router857.SWAPTOKENSFOREXACTTOKENS381( quotedTokenAmount, daiAmount, path, fromReserves ? address(this) : msg.sender, deadline ); totalDaiSold = amounts[0]; _FIRETRADEEVENT684( fromReserves, TradeType.DAI_TO_TOKEN, address(token), daiAmount, quotedTokenAmount, daiAmount.SUB328(totalDaiSold) ); } function _TRADETOKENFORDAI325( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther, bool fromReserves ) internal returns (uint256 totalDaiBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(token, tokenAmount); // Establish path (direct or routed through Ether) from target token to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(token), address(_dai607), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap (send to this contract). amounts = _uniswap_router857.SWAPEXACTTOKENSFORTOKENS55( tokenAmount, quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[path.length - 1]; _FIRETRADEEVENT684( fromReserves, TradeType.TOKEN_TO_DAI, address(token), tokenAmount, quotedDaiAmount, totalDaiBought.SUB328(quotedDaiAmount) ); } function _TRADETOKENFORTOKEN365( //inject NONSTANDARD NAMING address recipient, ERC20Interface tokenProvided, address tokenReceived, uint256 tokenProvidedAmount, uint256 quotedTokenReceivedAmount, uint256 deadline, bool routeThroughEther ) internal returns (uint256 totalTokensSold) { uint256 retainedAmount; // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY414(tokenProvided, tokenProvidedAmount); if (routeThroughEther == false) { // Establish direct path between tokens. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(tokenProvided), tokenReceived, false ); // Trade for the quoted token amount on Uniswap and send to recipient. amounts = _uniswap_router857.SWAPTOKENSFOREXACTTOKENS381( quotedTokenReceivedAmount, tokenProvidedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = tokenProvidedAmount.SUB328(totalTokensSold); } else { // Establish path between provided token and WETH. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS240( address(tokenProvided), _weth890, false ); // Trade all provided tokens for WETH on Uniswap and send to this contract. amounts = _uniswap_router857.SWAPEXACTTOKENSFORTOKENS55( tokenProvidedAmount, 0, path, address(this), deadline ); retainedAmount = amounts[1]; // Establish path between WETH and received token. (path, amounts) = _CREATEPATHANDAMOUNTS240( _weth890, tokenReceived, false ); // Trade bought WETH for received token on Uniswap and send to recipient. amounts = _uniswap_router857.SWAPTOKENSFOREXACTTOKENS381( quotedTokenReceivedAmount, retainedAmount, path, recipient, deadline ); totalTokensSold = amounts[0]; retainedAmount = retainedAmount.SUB328(totalTokensSold); } emit TRADE504( recipient, address(tokenProvided), tokenReceived, routeThroughEther ? _weth890 : address(tokenProvided), tokenProvidedAmount, quotedTokenReceivedAmount, retainedAmount ); } function _SETROLE96(Role role, address account) internal { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit ROLEMODIFIED267(role, account); } } function _FIRETRADEEVENT684( //inject NONSTANDARD NAMING bool fromReserves, TradeType tradeType, address token, uint256 suppliedAmount, uint256 receivedAmount, uint256 retainedAmount ) internal { uint256 t = uint256(tradeType); emit TRADE504( fromReserves ? address(this) : msg.sender, t < 2 ? address(_dai607) : (t % 2 == 0 ? address(0) : token), (t > 1 && t < 4) ? address(_dai607) : (t % 2 == 0 ? token : address(0)), t < 4 ? address(_dai607) : address(0), suppliedAmount, receivedAmount, retainedAmount ); } function _ISROLE773(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = msg.sender == _roles[uint256(role)].account; } function _ISPAUSED235(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING paused = _roles[uint256(role)].paused; } function _ISSMARTWALLET673( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _wallet_creation_code_header349, initialUserSigningKey, _wallet_creation_code_footer225 ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _create2_header144, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } function _REDEEMDDAIIFNECESSARY474(uint256 daiAmountFromReserves) internal { //inject NONSTANDARD NAMING uint256 daiBalance = _dai607.BALANCEOF7(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _ddai635.REDEEMUNDERLYING444(additionalDaiRequired); } } function _TRANSFERTOKEN426(ERC20Interface token, address to, uint256 amount) internal { //inject NONSTANDARD NAMING (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.TRANSFER250.selector, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer out failed.' ); } function _TRANSFERETHER189(address recipient, uint256 etherAmount) internal { //inject NONSTANDARD NAMING // Send quoted Ether amount to recipient and revert with reason on failure. (bool ok, ) = recipient.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function _TRANSFERINTOKEN55(ERC20Interface token, address from, uint256 amount) internal { //inject NONSTANDARD NAMING (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.TRANSFERFROM572.selector, from, address(this), amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer in failed.' ); } function _ENSURESMARTWALLET467( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) internal pure { require( _ISSMARTWALLET673(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); } function _CREATEPATHANDAMOUNTS240( //inject NONSTANDARD NAMING address start, address end, bool routeThroughEther ) internal pure returns (address[] memory, uint256[] memory) { uint256 pathLength = routeThroughEther ? 3 : 2; address[] memory path = new address[](pathLength); path[0] = start; if (routeThroughEther) { path[1] = _weth890; } path[pathLength - 1] = end; return (path, new uint256[](pathLength)); } modifier ONLYOWNEROR375(Role role) { //inject NONSTANDARD NAMING if (!ISOWNER119()) { require(_ISROLE773(role), "Caller does not have a required role."); require(!_ISPAUSED235(role), "Role in question is currently paused."); } _; } }
inject NONSTANDARD NAMING
function WITHDRAWDAITOPRIMARYRECIPIENT618(uint256 usdcAmount) external;
7,223,332
/** * https://contributing.kleros.io/smart-contract-workflow * @authors: [@fnanni-0] * @reviewers: [@unknownunknown1, @MerlinEgalite, @hbarcelos, @shalzz, @jaybuidl] * @auditors: [] * @bounties: [] * @deployments: [] */ pragma solidity ^0.4.24; import "openzeppelin-eth/contracts/zos-lib/Initializable.sol"; import "openzeppelin-eth/contracts/math/SafeMath.sol"; import {TokenController} from "minimetoken/contracts/TokenController.sol"; import {ITokenBridge} from "../interfaces/ITokenBridge.sol"; import {IERC677} from "../interfaces/IERC677.sol"; contract WrappedPinakion is Initializable { using SafeMath for uint256; /* Events */ /** * @notice Emitted when `value` tokens are moved from one account (`from`) to another (`to`). * @dev Notice that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @notice 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); /* Storage */ mapping(address => uint256) private balances; mapping(address => mapping(address => uint256)) public allowance; /// @notice Total supply of the token. Equals the total xPinakion deposit into the contract. uint256 public totalSupply; /// @notice Name of the token. string public name; /// @notice Symbol of the token. string public symbol; /// @notice Number of decimals of the token. uint8 public decimals; /// @notice The token's controller. address public controller; /// @notice Bridged PNK on xDai to be wrapped. This token is upgradeable. IERC677 public xPinakion; /// @notice xDai Token Bridge. The Token Bridge is upgradeable. ITokenBridge public tokenBridge; /* Modifiers */ /// @dev Verifies that the sender has ability to modify controlled parameters. modifier onlyController() { require(controller == msg.sender, "The caller is not the controller."); _; } /* Initializer */ /** * @dev Constructor. * @param _name for the wrapped PNK on the home chain. * @param _symbol for wrapped PNK ticker on the home chain. * @param _xPinakion the home PNK contract which is already bridged to the foreign PNK contract. * @param _tokenBridge the TokenBridge contract. */ function initialize( string memory _name, string memory _symbol, IERC677 _xPinakion, ITokenBridge _tokenBridge ) public initializer { name = _name; symbol = _symbol; decimals = 18; xPinakion = _xPinakion; tokenBridge = _tokenBridge; controller = msg.sender; } /* External */ /** * @notice Changes `controller` to `_controller`. * @param _controller The new controller of the contract */ function changeController(address _controller) external onlyController { controller = _controller; } /** * @notice Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid. * @param _amount The amount of wrapped pinakions to mint. */ function deposit(uint256 _amount) external { _mint(msg.sender, _amount); require( xPinakion.transferFrom(msg.sender, address(this), _amount), "Sender does not have enough approved funds." ); } /** * @notice IERC20 Receiver functionality. * @dev Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid. * If the tokenBridge is calling this function, then this contract has already received * the xPinakion tokens. Notice that the Home bridge calls onTokenBridge as a result of * someone invoking `relayTokensAndCall()` on the Foreign bridge contract. * @param _token The token address the _amount belongs to. * @param _amount The amount of wrapped PNK to mint. * @param _data Calldata containing the address of the recipient. * Notice that the address has to be padded to the right 32 bytes. */ function onTokenBridged( address _token, uint256 _amount, bytes _data ) external { require(msg.sender == address(tokenBridge), "Sender not authorized."); require(_token == address(xPinakion), "Token bridged is not xPinakion."); address recipient; assembly { recipient := calldataload(0x84) } _mint(recipient, _amount); } /** * @notice Converts wrapped PNK back into bridged PNK (xPinakion). * @param _amount The amount of bridged PNK to withdraw. */ function withdraw(uint256 _amount) external { _burn(_amount); require(xPinakion.transfer(msg.sender, _amount), "The `transfer` function must not fail."); } /** * @notice Converts wrapped PNK back into PNK using the Token Bridge. * @dev This function is not strictly needed, but it provides a good UX to users who want to get their Mainnet's PNK back. * What normally takes 3 transactions, here is done in one go. * Notice that the PNK have to be claimed on Mainnet's TokenBridge by the receiver. * @param _amount The amount of PNK to withdraw. * @param _receiver The address which will receive the PNK back in the foreign chain. */ function withdrawAndConvertToPNK(uint256 _amount, address _receiver) external { _burn(_amount); // Using approve is safe here, because this contract approves the bridge to spend the tokens and triggers the relay immediately. xPinakion.approve(address(tokenBridge), _amount); tokenBridge.relayTokens(xPinakion, _receiver, _amount); } /** * @notice Moves `_amount` tokens from the caller's account to `_recipient`. * @param _recipient The entity receiving the funds. * @param _amount The amount to tranfer in base units. * @return True on success. */ function transfer(address _recipient, uint256 _amount) public returns (bool) { if (isContract(controller)) { require( TokenController(controller).onTransfer(msg.sender, _recipient, _amount), "Token controller rejects transfer." ); } balances[msg.sender] = balances[msg.sender].sub(_amount); // ERC20: transfer amount exceeds balance balances[_recipient] = balances[_recipient].add(_amount); emit Transfer(msg.sender, _recipient, _amount); return true; } /** * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the * allowance mechanism. `_amount` is then deducted from the caller's allowance. * @param _sender The entity to take the funds from. * @param _recipient The entity receiving the funds. * @param _amount The amount to tranfer in base units. * @return True on success. */ function transferFrom( address _sender, address _recipient, uint256 _amount ) public returns (bool) { if (isContract(controller)) { require( TokenController(controller).onTransfer(_sender, _recipient, _amount), "Token controller rejects transfer." ); } /** The controller of this contract can move tokens around at will, * this is important to recognize! Confirm that you trust the * controller of this contract, which in most situations should be * another open source smart contract or 0x0. */ if (msg.sender != controller) { allowance[_sender][msg.sender] = allowance[_sender][msg.sender].sub(_amount); // ERC20: transfer amount exceeds allowance. } balances[_sender] = balances[_sender].sub(_amount); // ERC20: transfer amount exceeds balance balances[_recipient] = balances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); return true; } /** * @notice Approves `_spender` to spend `_amount`. * @param _spender The entity allowed to spend funds. * @param _amount The amount of base units the entity will be allowed to spend. * @return True on success. */ function approve(address _spender, uint256 _amount) public returns (bool) { // Alerts the token controller of the approve function call if (isContract(controller)) { require( TokenController(controller).onApprove(msg.sender, _spender, _amount), "Token controller does not approve." ); } allowance[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @notice Increases the `_spender` allowance by `_addedValue`. * @param _spender The entity allowed to spend funds. * @param _addedValue The amount of extra base units the entity will be allowed to spend. * @return True on success. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { uint256 newAllowance = allowance[msg.sender][_spender].add(_addedValue); // Alerts the token controller of the approve function call if (isContract(controller)) { require( TokenController(controller).onApprove(msg.sender, _spender, newAllowance), "Token controller does not approve." ); } allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /** * @notice Decreases the `_spender` allowance by `_subtractedValue`. * @param _spender The entity whose spending allocation will be reduced. * @param _subtractedValue The reduction of spending allocation in base units. * @return True on success. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 newAllowance = allowance[msg.sender][_spender].sub(_subtractedValue); // ERC20: decreased allowance below zero // Alerts the token controller of the approve function call if (isContract(controller)) { require( TokenController(controller).onApprove(msg.sender, _spender, newAllowance), "Token controller does not approve." ); } allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /* Internal */ /** * @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 _recipient The address which will receive the minted tokens. * @param _amount The amount that will be created. */ function _mint(address _recipient, uint256 _amount) internal { totalSupply = totalSupply.add(_amount); balances[_recipient] = balances[_recipient].add(_amount); emit Transfer(address(0x0), _recipient, _amount); } /** * @dev Destroys `_amount` tokens from the caller. Cannot burn locked tokens. * @param _amount The quantity of tokens to burn in base units. */ function _burn(uint256 _amount) internal { if (isContract(controller)) { require( TokenController(controller).onTransfer(msg.sender, address(0x0), _amount), "Token controller rejects transfer." ); } balances[msg.sender] = balances[msg.sender].sub(_amount); // ERC20: burn amount exceeds balance totalSupply = totalSupply.sub(_amount); emit Transfer(msg.sender, address(0x0), _amount); } /** * @dev Internal function to determine if an address is a contract. * @param _addr The address being queried. * @return True if `_addr` is a contract. */ function isContract(address _addr) internal view returns (bool) { uint256 size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /* Getters */ /** * @dev Gets the balance of the specified address. * @param _owner The address to query the balance of. * @return uint256 value representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
Moves `_amount` tokens from `_sender` to `_recipient` using the allowance mechanism. `_amount` is then deducted from the caller's allowance. _sender The entity to take the funds from. _recipient The entity receiving the funds. _amount The amount to tranfer in base units. return True on success./ The controller of this contract can move tokens around at will, this is important to recognize! Confirm that you trust the controller of this contract, which in most situations should be another open source smart contract or 0x0./
function transferFrom( address _sender, address _recipient, uint256 _amount ) public returns (bool) { if (isContract(controller)) { require( TokenController(controller).onTransfer(_sender, _recipient, _amount), "Token controller rejects transfer." ); } if (msg.sender != controller) { } balances[_recipient] = balances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); return true; }
12,697,444
pragma solidity 0.8.1; interface ISupplyController { function mintIncentive(address addr) external; function mintableIncentive(address addr) external view returns (uint); function mint(address token, address owner, uint amount) external; function changeSupplyController(address newSupplyController) external; } interface IADXToken { function transfer(address to, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address spender) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function totalSupply() external returns (uint); function supplyController() external view returns (ISupplyController); function changeSupplyController(address newSupplyController) external; function mint(address owner, uint amount) external; } interface IERCDecimals { function decimals() external view returns (uint); } interface IChainlink { // AUDIT: ensure this API is not deprecated function latestAnswer() external view returns (uint); } // Full interface here: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol interface IUniswapSimple { function WETH() external pure returns (address); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } contract StakingPool { // ERC20 stuff // Constants string public constant name = "AdEx Staking Token"; uint8 public constant decimals = 18; string public constant symbol = "ADX-STAKING"; // Mutable variables uint public totalSupply; mapping(address => uint) private balances; mapping(address => mapping(address => uint)) private allowed; // EIP 2612 bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; // ERC20 events event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); // ERC20 methods function balanceOf(address owner) external view returns (uint balance) { return balances[owner]; } function transfer(address to, uint amount) external returns (bool success) { require(to != address(this), "BAD_ADDRESS"); balances[msg.sender] = balances[msg.sender] - amount; balances[to] = balances[to] + amount; emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint amount) external returns (bool success) { balances[from] = balances[from] - amount; allowed[from][msg.sender] = allowed[from][msg.sender] - amount; balances[to] = balances[to] + amount; emit Transfer(from, to, amount); return true; } function approve(address spender, uint amount) external returns (bool success) { allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function allowance(address owner, address spender) external view returns (uint remaining) { return allowed[owner][spender]; } // EIP 2612 function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, "DEADLINE_EXPIRED"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)) )); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNATURE"); allowed[owner][spender] = amount; emit Approval(owner, spender, amount); } // Inner function innerMint(address owner, uint amount) internal { totalSupply = totalSupply + amount; balances[owner] = balances[owner] + amount; // Because of https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 emit Transfer(address(0), owner, amount); } function innerBurn(address owner, uint amount) internal { totalSupply = totalSupply - amount; balances[owner] = balances[owner] - amount; emit Transfer(owner, address(0), amount); } // Pool functionality uint public timeToUnbond = 20 days; uint public rageReceivedPromilles = 700; IUniswapSimple public uniswap; // = IUniswapSimple(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IChainlink public ADXUSDOracle; // = IChainlink(0x231e764B44b2C1b7Ca171fa8021A24ed520Cde10); IADXToken public immutable ADXToken; address public guardian; address public validator; address public governance; // claim token whitelist: normally claim tokens are stablecoins // eg Tether (0xdAC17F958D2ee523a2206206994597C13D831ec7) mapping (address => bool) public whitelistedClaimTokens; // Commitment ID against the max amount of tokens it will pay out mapping (bytes32 => uint) public commitments; // How many of a user's shares are locked mapping (address => uint) public lockedShares; // Unbonding commitment from a staker struct UnbondCommitment { address owner; uint shares; uint unlocksAt; } // claims/penalizations limits uint public maxDailyPenaltiesPromilles; uint public limitLastReset; uint public limitRemaining; // Staking pool events // LogLeave/LogWithdraw must begin with the UnbondCommitment struct event LogLeave(address indexed owner, uint shares, uint unlocksAt, uint maxTokens); event LogWithdraw(address indexed owner, uint shares, uint unlocksAt, uint maxTokens, uint receivedTokens); event LogRageLeave(address indexed owner, uint shares, uint maxTokens, uint receivedTokens); event LogNewGuardian(address newGuardian); event LogClaim(address tokenAddr, address to, uint amountInUSD, uint burnedValidatorShares, uint usedADX, uint totalADX, uint totalShares); event LogPenalize(uint burnedADX); constructor(IADXToken token, IUniswapSimple uni, IChainlink oracle, address guardianAddr, address validatorStakingWallet, address governanceAddr, address claimToken) { ADXToken = token; uniswap = uni; ADXUSDOracle = oracle; guardian = guardianAddr; validator = validatorStakingWallet; governance = governanceAddr; whitelistedClaimTokens[claimToken] = true; // EIP 2612 uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } // Governance functions function setGovernance(address addr) external { require(governance == msg.sender, "NOT_GOVERNANCE"); governance = addr; } function setDailyPenaltyMax(uint max) external { require(governance == msg.sender, "NOT_GOVERNANCE"); require(max <= 200, "DAILY_PENALTY_TOO_LARGE"); maxDailyPenaltiesPromilles = max; resetLimits(); } function setRageReceived(uint rageReceived) external { require(governance == msg.sender, "NOT_GOVERNANCE"); // AUDIT: should there be a minimum here? require(rageReceived <= 1000, "TOO_LARGE"); rageReceivedPromilles = rageReceived; } function setTimeToUnbond(uint time) external { require(governance == msg.sender, "NOT_GOVERNANCE"); require(time >= 1 days && time <= 30 days, "BOUNDS"); timeToUnbond = time; } function setGuardian(address newGuardian) external { require(governance == msg.sender, "NOT_GOVERNANCE"); guardian = newGuardian; emit LogNewGuardian(newGuardian); } function setWhitelistedClaimToken(address token, bool whitelisted) external { require(governance == msg.sender, "NOT_GOVERNANCE"); whitelistedClaimTokens[token] = whitelisted; } // Pool stuff function shareValue() external view returns (uint) { if (totalSupply == 0) return 0; return ((ADXToken.balanceOf(address(this)) + ADXToken.supplyController().mintableIncentive(address(this))) * 1e18) / totalSupply; } function innerEnter(address recipient, uint amount) internal { // Please note that minting has to be in the beginning so that we take it into account // when using ADXToken.balanceOf() // Minting makes an external call but it"s to a trusted contract (ADXToken) ADXToken.supplyController().mintIncentive(address(this)); uint totalADX = ADXToken.balanceOf(address(this)); // The totalADX == 0 check here should be redudnant; the only way to get totalSupply to a nonzero val is by adding ADX if (totalSupply == 0 || totalADX == 0) { innerMint(recipient, amount); } else { uint256 newShares = (amount * totalSupply) / totalADX; innerMint(recipient, newShares); } require(ADXToken.transferFrom(msg.sender, address(this), amount)); // no events, as innerMint already emits enough to know the shares amount and price } function enter(uint amount) external { innerEnter(msg.sender, amount); } function enterTo(address recipient, uint amount) external { innerEnter(recipient, amount); } function unbondingCommitmentWorth(address owner, uint shares, uint unlocksAt) external view returns (uint) { if (totalSupply == 0) return 0; bytes32 commitmentId = keccak256(abi.encode(UnbondCommitment({ owner: owner, shares: shares, unlocksAt: unlocksAt }))); uint maxTokens = commitments[commitmentId]; uint totalADX = ADXToken.balanceOf(address(this)); uint currentTokens = (shares * totalADX) / totalSupply; return currentTokens > maxTokens ? maxTokens : currentTokens; } function leave(uint shares, bool skipMint) external { if (!skipMint) ADXToken.supplyController().mintIncentive(address(this)); require(shares <= balances[msg.sender] - lockedShares[msg.sender], "INSUFFICIENT_SHARES"); uint totalADX = ADXToken.balanceOf(address(this)); uint maxTokens = (shares * totalADX) / totalSupply; uint unlocksAt = block.timestamp + timeToUnbond; bytes32 commitmentId = keccak256(abi.encode(UnbondCommitment({ owner: msg.sender, shares: shares, unlocksAt: unlocksAt }))); require(commitments[commitmentId] == 0, "COMMITMENT_EXISTS"); commitments[commitmentId] = maxTokens; lockedShares[msg.sender] += shares; emit LogLeave(msg.sender, shares, unlocksAt, maxTokens); } function withdraw(uint shares, uint unlocksAt, bool skipMint) external { if (!skipMint) ADXToken.supplyController().mintIncentive(address(this)); require(block.timestamp > unlocksAt, "UNLOCK_TOO_EARLY"); bytes32 commitmentId = keccak256(abi.encode(UnbondCommitment({ owner: msg.sender, shares: shares, unlocksAt: unlocksAt }))); uint maxTokens = commitments[commitmentId]; require(maxTokens > 0, "NO_COMMITMENT"); uint totalADX = ADXToken.balanceOf(address(this)); uint currentTokens = (shares * totalADX) / totalSupply; uint receivedTokens = currentTokens > maxTokens ? maxTokens : currentTokens; commitments[commitmentId] = 0; lockedShares[msg.sender] -= shares; innerBurn(msg.sender, shares); require(ADXToken.transfer(msg.sender, receivedTokens)); emit LogWithdraw(msg.sender, shares, unlocksAt, maxTokens, receivedTokens); } function rageLeave(uint shares, bool skipMint) external { if (!skipMint) ADXToken.supplyController().mintIncentive(address(this)); uint totalADX = ADXToken.balanceOf(address(this)); uint adxAmount = (shares * totalADX) / totalSupply; uint receivedTokens = (adxAmount * rageReceivedPromilles) / 1000; innerBurn(msg.sender, shares); require(ADXToken.transfer(msg.sender, receivedTokens)); emit LogRageLeave(msg.sender, shares, adxAmount, receivedTokens); } // Insurance mechanism // In case something goes wrong, this can be used to recoup funds // As of V5, the idea is to use it to provide some interest (eg 10%) for late refunds, in case channels get stuck and have to wait through their challenge period function claim(address tokenOut, address to, uint amount) external { require(msg.sender == guardian, "NOT_GUARDIAN"); // start by resetting claim/penalty limits resetLimits(); // NOTE: minting is intentionally skipped here // This means that a validator may be punished a bit more when burning their shares, // but it guarantees that claim() always works uint totalADX = ADXToken.balanceOf(address(this)); // Note: whitelist of tokenOut tokens require(whitelistedClaimTokens[tokenOut], "TOKEN_NOT_WHITELISTED"); address[] memory path = new address[](3); path[0] = address(ADXToken); path[1] = uniswap.WETH(); path[2] = tokenOut; // You may think the Uniswap call enables reentrancy, but reentrancy is a problem only if the pattern is check-call-modify, not call-check-modify as is here // there"s no case in which we "double-spend" a value // Plus, ADX, USDT and uniswap are all trusted // Slippage protection; 5% slippage allowed uint price = ADXUSDOracle.latestAnswer(); // chainlink price is in 1e8 // for example, if the amount is in 1e6; // we need to convert from 1e6 to 1e18 (adx) but we divide by 1e8 (price); 18 - 6 + 8 ; verified this by calculating manually uint multiplier = 1.05e26 / (10 ** IERCDecimals(tokenOut).decimals()); uint adxAmountMax = (amount * multiplier) / price; require(adxAmountMax < totalADX, "INSUFFICIENT_ADX"); uint[] memory amounts = uniswap.swapTokensForExactTokens(amount, adxAmountMax, path, to, block.timestamp); // calculate the total ADX amount used in the swap uint adxAmountUsed = amounts[0]; // burn the validator shares so that they pay for it first, before dilluting other holders // calculate the worth in ADX of the validator"s shares uint sharesNeeded = (adxAmountUsed * totalSupply) / totalADX; uint toBurn = sharesNeeded < balances[validator] ? sharesNeeded : balances[validator]; if (toBurn > 0) innerBurn(validator, toBurn); // Technically redundant cause we"ll fail on the subtraction, but we"re doing this for better err msgs require(limitRemaining >= adxAmountUsed, "LIMITS"); limitRemaining -= adxAmountUsed; emit LogClaim(tokenOut, to, amount, toBurn, adxAmountUsed, totalADX, totalSupply); } function penalize(uint adxAmount) external { require(msg.sender == guardian, "NOT_GUARDIAN"); // AUDIT: we can do getLimitRemaining() instead of resetLimits() that returns the remaining limit resetLimits(); // Technically redundant cause we'll fail on the subtraction, but we're doing this for better err msgs require(limitRemaining >= adxAmount, "LIMITS"); limitRemaining -= adxAmount; require(ADXToken.transfer(address(0), adxAmount)); emit LogPenalize(adxAmount); } function resetLimits() internal { if (block.timestamp - limitLastReset > 24 hours) { limitLastReset = block.timestamp; limitRemaining = (ADXToken.balanceOf(address(this)) * maxDailyPenaltiesPromilles) / 1000; } } }
Please note that minting has to be in the beginning so that we take it into account when using ADXToken.balanceOf() Minting makes an external call but it"s to a trusted contract (ADXToken) The totalADX == 0 check here should be redudnant; the only way to get totalSupply to a nonzero val is by adding ADX
function innerEnter(address recipient, uint amount) internal { ADXToken.supplyController().mintIncentive(address(this)); uint totalADX = ADXToken.balanceOf(address(this)); if (totalSupply == 0 || totalADX == 0) { innerMint(recipient, amount); uint256 newShares = (amount * totalSupply) / totalADX; innerMint(recipient, newShares); } require(ADXToken.transferFrom(msg.sender, address(this), amount));
496,464
./full_match/1/0x4D91AaD0Deb494C71d538039c8C5d689fAFfa5Fc/sources/src/Entity.sol
Each entity will implement this function to allow a caller to interrogate what kind of entity it is. One time method to be called at deployment to configure the contract. Required so Entity contracts can be deployed as minimal proxies (clones). _registry The registry to host the Entity. _manager The address of the Entity's manager./ Call to EndaomentAuth's initialize function ensures that this can't be called again
function entityType() public pure virtual returns (uint8); function __initEntity(Registry _registry, address _manager) internal { __initEndaomentAuth(_registry, bytes20(bytes.concat("entity", bytes1(entityType())))); __initReentrancyGuard(); registry = _registry; manager = _manager; baseToken = _registry.baseToken(); }
17,094,313
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; contract EncryptedSender { struct TopicData { // An (optional) public key used to encrypt messages for this topic. This is only necessary if the sender will // not have access to the public key offchain. bytes publicKey; // The encrypted message. bytes message; } struct Recipient { // This maps from a hash to the data for this topic. // Note: the hash is a hash of the "subject" or "topic" of the message. mapping(bytes32 => TopicData) topics; // This contains the set of all authorized senders for this recipient. mapping(address => bool) authorizedSenders; } mapping(address => Recipient) private recipients; /** * @notice Authorizes `sender` to send messages to the caller. */ function addAuthorizedSender(address sender) external { recipients[msg.sender].authorizedSenders[sender] = true; } /** * @notice Revokes `sender`'s authorization to send messages to the caller. */ function removeAuthorizedSender(address sender) external { recipients[msg.sender].authorizedSenders[sender] = false; } /** * @notice Gets the current stored message corresponding to `recipient` and `topicHash`. * @dev To decrypt messages (this requires access to the recipient's private keys), use the decryptMessage() * function in common/Crypto.js. */ function getMessage(address recipient, bytes32 topicHash) external view returns (bytes memory) { return recipients[recipient].topics[topicHash].message; } /** * @notice Gets the stored public key for a particular `recipient` and `topicHash`. Return value will be 0 length * if no public key has been set. * @dev Senders may need this public key to encrypt messages that only the `recipient` can read. If the public key * is communicated offchain, this field may be left empty. */ function getPublicKey(address recipient, bytes32 topicHash) external view returns (bytes memory) { return recipients[recipient].topics[topicHash].publicKey; } /** * @notice Sends `message` to `recipient_` categorized by a particular `topicHash`. This will overwrite any * previous messages sent to this `recipient` with this `topicHash`. * @dev To construct an encrypted message, use the encryptMessage() in common/Crypto.js. * The public key for the recipient can be obtained using the getPublicKey() method. */ function sendMessage(address recipient_, bytes32 topicHash, bytes memory message) public { Recipient storage recipient = recipients[recipient_]; require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to send to this recipient"); recipient.topics[topicHash].message = message; } function removeMessage(address recipient_, bytes32 topicHash) public { Recipient storage recipient = recipients[recipient_]; require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to remove message"); delete recipient.topics[topicHash].message; } /** * @notice Sets the public key for this caller and topicHash. * @dev Note: setting the public key is optional - if the publicKey is communicated or can be derived offchain by * the sender, there is no need to set it here. Because there are no specific requirements for the publicKey, there * is also no verification of its validity other than its length. */ function setPublicKey(bytes memory publicKey, bytes32 topicHash) public { require(publicKey.length == 64, "Public key is the wrong length"); recipients[msg.sender].topics[topicHash].publicKey = publicKey; } /** * @notice Returns true if the `sender` is authorized to send to the `recipient`. */ function isAuthorizedSender(address sender, address recipient) public view returns (bool) { // Note: the recipient is always authorized to send messages to themselves. return recipients[recipient].authorizedSenders[sender] || recipient == sender; } } library FixedPoint { using SafeMath for uint; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint 10^77. uint private constant FP_SCALING_FACTOR = 10**18; struct Unsigned { uint rawValue; } /** @dev Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. */ function fromUnscaledUint(uint a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** @dev Whether `a` is greater than `b`. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** @dev Whether `a` is greater than `b`. */ function isGreaterThan(Unsigned memory a, uint b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** @dev Whether `a` is greater than `b`. */ function isGreaterThan(uint a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** @dev Whether `a` is less than `b`. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** @dev Whether `a` is less than `b`. */ function isLessThan(Unsigned memory a, uint b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** @dev Whether `a` is less than `b`. */ function isLessThan(uint a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** @dev Adds two `Unsigned`s, reverting on overflow. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** @dev Adds an `Unsigned` to an unscaled uint, reverting on overflow. */ function add(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** @dev Subtracts two `Unsigned`s, reverting on underflow. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** @dev Subtracts an unscaled uint from an `Unsigned`, reverting on underflow. */ function sub(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** @dev Subtracts an `Unsigned` from an unscaled uint, reverting on underflow. */ function sub(uint a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** @dev Multiplies two `Unsigned`s, reverting on overflow. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** @dev Multiplies an `Unsigned` by an unscaled uint, reverting on overflow. */ function mul(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** @dev Divides with truncation two `Unsigned`s, reverting on overflow or division by 0. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** @dev Divides with truncation an `Unsigned` by an unscaled uint, reverting on division by 0. */ function div(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** @dev Divides with truncation an unscaled uint by an `Unsigned`, reverting on overflow or division by 0. */ function div(uint a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** @dev Raises an `Unsigned` to the power of an unscaled uint, reverting on overflow. E.g., `b=2` squares `a`. */ function pow(Unsigned memory a, uint b) internal pure returns (Unsigned memory output) { // TODO(ptare): Consider using the exponentiation by squaring technique instead: // https://en.wikipedia.org/wiki/Exponentiation_by_squaring output = fromUnscaledUint(1); for (uint i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint => Role) private roles; /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. */ function holdsRole(uint roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } require(false, "Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, exclusive role. */ function resetMember(uint roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. */ function getMember(uint roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the * managing role for `roleId`. */ function addMember(uint roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the * managing role for `roleId`. */ function removeMember(uint roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole(uint roleId, uint managingRoleId, address[] memory initialMembers) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require(roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role"); } /** * @notice Internal method to initialize a exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole(uint roleId, uint managingRoleId, address initialMember) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require(roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role"); } } interface OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Returns the time at which the user should expect the price to be resolved. 0 means the price has already * been resolved. */ function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); /** * @notice Whether the Oracle provides prices for this identifier. */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); /** * @notice Whether the price for `identifier` and `time` is available. */ function hasPrice(bytes32 identifier, uint time) external view returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. */ function getPrice(bytes32 identifier, uint time) external view returns (int price); } interface RegistryInterface { /** * @dev Registers a new derivative. Only authorized derivative creators can call this method. */ function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; /** * @dev Returns whether the derivative has been registered with the registry (and is therefore an authorized. * participant in the UMA system). */ function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); /** * @dev Returns a list of all derivatives that are associated with a particular party. */ function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives); /** * @dev Returns all registered derivatives. */ function getAllRegisteredDerivatives() external view returns (address[] memory derivatives); } contract Registry is RegistryInterface, MultiRole { using SafeMath for uint; enum Roles { // The owner manages the set of DerivativeCreators. Owner, // Can register derivatives. DerivativeCreator } // Array of all derivatives that are approved to use the UMA Oracle. address[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that registered derivative in `registeredDerivatives`. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of `registeredDerivatives` because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; event NewDerivativeRegistered(address indexed derivativeAddress, address indexed creator, address[] parties); constructor() public { _createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender); // Start with no derivative creators registered. _createSharedRole(uint(Roles.DerivativeCreator), uint(Roles.Owner), new address[](0)); } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyRoleHolder(uint(Roles.DerivativeCreator)) { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(derivativeAddress); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit NewDerivativeRegistered(derivativeAddress, msg.sender, partiesForEvent); } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). address[] memory tmpDerivativeArray = new address[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { address derivative = registeredDerivatives[i]; if (derivativesToParties[derivative].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new address[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (address[] memory derivatives) { return registeredDerivatives; } } library ResultComputation { using FixedPoint for FixedPoint.Unsigned; struct Data { // Maps price to number of tokens that voted for that price. mapping(int => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int currentMode; } /** * @dev Returns whether the result is resolved, and if so, what value it resolved to. `price` should be ignored if * `isResolved` is false. * @param minVoteThreshold Minimum number of tokens that must have been voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int price) { // TODO(ptare): Figure out where this parameter is supposed to come from. FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if (data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)) { // `modeThreshold` and `minVoteThreshold` are met, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @dev Adds a new vote to be used when computing the result. */ function addVote(Data storage data, int votePrice, FixedPoint.Unsigned memory numberTokens) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if (votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])) { data.currentMode = votePrice; } } /** * @dev Checks whether a `voteHash` is considered correct. Should only be called after a vote is resolved, i.e., * via `getResolvedPrice`. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @dev Gets the total number of tokens whose votes are considered correct. Should only be called after a vote is * resolved, i.e., via `getResolvedPrice`. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } contract Testable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(isTest); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. */ function setCurrentTime(uint _time) external onlyIfTest { currentTime = _time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. */ function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract Governor is MultiRole, Testable { using SafeMath for uint; enum Roles { // Can set the proposer. Owner, // Address that can make proposals. Proposer } struct Transaction { address to; uint value; bytes data; } struct Proposal { Transaction[] transactions; uint requestTime; } Finder private finder; Proposal[] public proposals; /** * @notice Emitted when a new proposal is created. */ event NewProposal(uint indexed id, Transaction[] transactions); /** * @notice Emitted when an existing proposal is executed. */ event ProposalExecuted(uint indexed id, uint transactionIndex); constructor(address _finderAddress, bool _isTest) public Testable(_isTest) { finder = Finder(_finderAddress); _createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender); _createExclusiveRole(uint(Roles.Proposer), uint(Roles.Owner), msg.sender); } /** * @notice Executes a proposed governance action that has been approved by voters. This can be called by anyone. */ function executeProposal(uint id, uint transactionIndex) external { Proposal storage proposal = proposals[id]; int price = _getVoting().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction storage transaction = proposal.transactions[transactionIndex]; require(transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous transaction has not been executed"); require(transaction.to != address(0), "Transaction has already been executed"); require(price != 0, "Cannot execute, proposal was voted down"); require(_executeCall(transaction.to, transaction.value, transaction.data), "Transaction execution failed"); // Delete the transaction. delete proposal.transactions[transactionIndex]; emit ProposalExecuted(id, transactionIndex); } /** * @notice Gets the total number of proposals (includes executed and non-executed). */ function numProposals() external view returns (uint) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * Note: after a proposal is executed, its data will be zeroed out. */ function getProposal(uint id) external view returns (Proposal memory proposal) { return proposals[id]; } /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions the list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that disallows structs arrays to be passed to * external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint(Roles.Proposer)) { uint id = proposals.length; uint time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add an element to the proposals array. proposals.length = proposals.length.add(1); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. proposal.transactions.length = transactions.length; for (uint i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The to address cannot be 0x0"); proposal.transactions[i] = transactions[i]; } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. Voting voting = _getVoting(); voting.addSupportedIdentifier(identifier); // Note: this check is only here to appease slither. require(voting.requestPrice(identifier, time) != ~uint(0), "Proposal will never be considered"); voting.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } function _constructIdentifier(uint id) private pure returns (bytes32 identifier) { bytes32 bytesId = _uintToBytes(id); return _addPrefix(bytesId, "Admin ", 6); } function _executeCall(address to, uint256 value, bytes memory data) private returns (bool success) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas, to, value, inputData, inputDataSize, 0, 0) } } function _getVoting() private view returns (Voting voting) { return Voting(finder.getImplementationAddress("Oracle")); } // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToBytes(uint v) private pure returns (bytes32 ret) { if (v == 0) { ret = "0"; } else { while (v > 0) { ret = ret >> 8; ret |= bytes32((v % 10) + 48) << (31 * 8); v /= 10; } } return ret; } function _addPrefix(bytes32 input, bytes32 prefix, uint prefixLength) private pure returns (bytes32 output) { bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } library VoteTiming { using SafeMath for uint; // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. enum Phase { Commit, Reveal } // Note: this MUST match the number of values in the enum above. uint private constant NUM_PHASES = 2; struct Data { uint roundId; uint roundStartTime; uint phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input and resets the round id and round * start time to 1 and 0 respectively. * @dev This method should generally only be run once, but it can also be used to reset the data structure to its * initial values. */ function init(Data storage data, uint phaseLength) internal { data.phaseLength = phaseLength; data.roundId = 1; data.roundStartTime = 0; } /** * @notice Gets the most recently stored round ID set by updateRoundId(). */ function getLastUpdatedRoundId(Data storage data) internal view returns (uint) { return data.roundId; } /** * @notice Determines whether time has advanced far enough to advance to the next voting round and update the * stored round id. */ function shouldUpdateRoundId(Data storage data, uint currentTime) internal view returns (bool) { (uint roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime); return data.roundId != roundId; } /** * @notice Updates the round id. Note: if shouldUpdateRoundId() returns false, this method will have no effect. */ function updateRoundId(Data storage data, uint currentTime) internal { (data.roundId, data.roundStartTime) = _getCurrentRoundIdAndStartTime(data, currentTime); } /** * @notice Computes what the stored round id would be if it were updated right now, but this method does not * commit the update. */ function computeCurrentRoundId(Data storage data, uint currentTime) internal view returns (uint roundId) { (roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime); } /** * @notice Computes the current phase based only on the current time. */ function computeCurrentPhase(Data storage data, uint currentTime) internal view returns (Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return Phase(currentTime.div(data.phaseLength).mod(NUM_PHASES)); } /** * @notice Gets the end time of the current round or any round in the future. Note: this method will revert if * the roundId < getLastUpdatedRoundId(). */ function computeEstimatedRoundEndTime(Data storage data, uint roundId) internal view returns (uint) { // The add(1) is because we want the round end time rather than the start time, so it's really the start of // the next round. uint roundDiff = roundId.sub(data.roundId).add(1); uint roundLength = data.phaseLength.mul(NUM_PHASES); return data.roundStartTime.add(roundDiff.mul(roundLength)); } /** * @dev Computes an updated round id and round start time based on the current time. */ function _getCurrentRoundIdAndStartTime(Data storage data, uint currentTime) private view returns (uint roundId, uint startTime) { uint currentStartTime = data.roundStartTime; // Return current data if time has moved backwards. if (currentTime <= data.roundStartTime) { return (data.roundId, data.roundStartTime); } // Get the start of the round that currentTime would be a part of by flooring by roundLength. uint roundLength = data.phaseLength.mul(NUM_PHASES); startTime = currentTime.div(roundLength).mul(roundLength); // Only increment the round ID if the start time has changed. if (startTime > currentStartTime) { roundId = data.roundId.add(1); } else { roundId = data.roundId; } } } contract VotingInterface { struct PendingRequest { bytes32 identifier; uint time; } /** * @notice Commit your vote for a price request for `identifier` at `time`. * @dev (`identifier`, `time`) must correspond to a price request that's currently in the commit phase. `hash` * should be the keccak256 hash of the price you want to vote for and a `int salt`. Commits can be changed. */ function commitVote(bytes32 identifier, uint time, bytes32 hash) external; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price` and `salt` must match the latest `hash` that `commitVote()` was called with. Only the * committer can reveal their vote. */ function revealVote(bytes32 identifier, uint time, int price, int salt) external; /** * @notice Gets the queries that are being voted on this round. */ function getPendingRequests() external view returns (PendingRequest[] memory); /** * @notice Gets the current vote phase (commit or reveal) based on the current block time. */ function getVotePhase() external view returns (VoteTiming.Phase); /** * @notice Gets the current vote round id based on the current block time. */ function getCurrentRoundId() external view returns (uint); /** * @notice Retrieves rewards owed for a set of resolved price requests. */ function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory) public returns (FixedPoint.Unsigned memory); } 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 Counters { using SafeMath for uint256; 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 { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } 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); } } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Finder is Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @dev Updates the address of the contract that implements `interfaceName`. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @dev Gets the address of the contract that implements the given `interfaceName`. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address implementationAddress) { implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "No implementation for interface found"); } } contract Voting is Testable, Ownable, OracleInterface, VotingInterface, EncryptedSender { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint time; // A map containing all votes for this price in various rounds. mapping(uint => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint index; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint time; int price; int salt; } struct Round { // Voting token snapshot ID for this round. If this is 0, no snapshot has been taken. uint snapshotId; // Inflation rate set for this round. FixedPoint.Unsigned inflationRate; } // Represents the status a price request has. enum RequestStatus { // Was never requested. NotRequested, // Is being voted on in the current round. Active, // Was resolved in a previous round. Resolved, // Is scheduled to be voted on in a future round. Future } // Maps round numbers to the rounds. mapping(uint => Round) private rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. These requests may be for future // rounds. bytes32[] private pendingPriceRequests; VoteTiming.Data private voteTiming; // The set of identifiers the oracle can provide verified prices for. mapping(bytes32 => bool) private supportedIdentifiers; // Percentage of the total token supply that must be used in a vote to create a valid price resolution. // 1 == 100%. FixedPoint.Unsigned private gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. Note: this value is used to set per-round inflation at the beginning // of each round. // 1 = 100% FixedPoint.Unsigned private inflationRate; // Reference to the voting token. VotingToken private votingToken; // Reference to the Finder. Finder private finder; // If non-zero, this contract has been migrated to this address. All voters and financial contracts should query the // new address only. address private migratedAddress; // Max value of an unsigned integer. uint constant private UINT_MAX = ~uint(0); event VoteCommitted(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time); event VoteRevealed( address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time, int price, uint numTokens ); event RewardsRetrieved(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time, uint numTokens); event PriceRequestAdded(uint indexed votingRoundId, bytes32 indexed identifier, uint time); event PriceResolved(uint indexed resolutionRoundId, bytes32 indexed identifier, uint time, int price); event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /** * @notice Construct the Voting contract. * @param phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage percentage of the total token supply that must be used in a vote to create a valid price * resolution. * @param _isTest whether this contract is being constructed for the purpose of running automated tests. */ constructor( uint phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, address _votingToken, address _finder, bool _isTest ) public Testable(_isTest) { voteTiming.init(phaseLength); // TODO(#779): GAT percentage must be < 100% require(_gatPercentage.isLessThan(1)); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = Finder(_finder); } modifier onlyRegisteredDerivative() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress); } else { Registry registry = Registry(finder.getImplementationAddress("Registry")); // TODO(#779): Must be registered derivative require(registry.isDerivativeRegistered(msg.sender)); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0)); _; } function requestPrice(bytes32 identifier, uint time) external onlyRegisteredDerivative() returns (uint expectedTime) { uint blockTime = getCurrentTime(); // TODO(#779): Price request must be for a time in the past require(time <= blockTime); // TODO(#779): Price request for unsupported identifier require(supportedIdentifiers[identifier]); // Must ensure the round is updated here so the requested price will be voted on in the next commit cycle. _updateRound(blockTime); bytes32 priceRequestId = _encodePriceRequest(identifier, time); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return voteTiming.computeEstimatedRoundEndTime(currentRoundId); } else if (requestStatus == RequestStatus.Resolved) { return 0; } else if (requestStatus == RequestStatus.Future) { return voteTiming.computeEstimatedRoundEndTime(priceRequest.lastVotingRound); } // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); // Estimate the end of next round and return the time. return voteTiming.computeEstimatedRoundEndTime(nextRoundId); } function batchCommit(Commitment[] calldata commits) external { for (uint i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].hash); } else { commitAndPersistEncryptedVote( commits[i].identifier, commits[i].time, commits[i].hash, commits[i].encryptedVote); } } } function batchReveal(Reveal[] calldata reveals) external { for (uint i = 0; i < reveals.length; i++) { revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt); } } /** * @notice Disables this Voting contract in favor of the migrated one. */ function setMigrated(address newVotingAddress) external onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Adds the provided identifier as a supported identifier. Price requests using this identifier will be * succeed after this call. */ function addSupportedIdentifier(bytes32 identifier) external onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. Price requests using this identifier will no longer succeed * after this call. */ function removeSupportedIdentifier(bytes32 identifier) external onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } function isIdentifierSupported(bytes32 identifier) external view returns (bool) { return supportedIdentifiers[identifier]; } function hasPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (bool _hasPrice) { (_hasPrice, ,) = _getPriceOrError(identifier, time); } function getPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (int) { (bool _hasPrice, int price, string memory message) = _getPriceOrError(identifier, time); // TODO(#779): If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } function getPendingRequests() external view returns (PendingRequest[] memory pendingRequests) { uint blockTime = getCurrentTime(); uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that `isActive()`. PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length); uint numUnresolved = 0; for (uint i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequest( { identifier: priceRequest.identifier, time: priceRequest.time }); numUnresolved++; } } pendingRequests = new PendingRequest[](numUnresolved); for (uint i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } } function getVotePhase() external view returns (VoteTiming.Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } function getCurrentRoundId() external view returns (uint) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } function commitVote(bytes32 identifier, uint time, bytes32 hash) public onlyIfNotMigrated() { // TODO(#779): Committed hash of 0 is disallowed, choose a different salt require(hash != bytes32(0)); // Current time is required for all vote timing queries. uint blockTime = getCurrentTime(); // TODO(#779): Cannot commit while in the reveal phase require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Commit); // Should only update the round in the commit phase because a new round that's already in the reveal phase // would be wasted. _updateRound(blockTime); // At this point, the computed and last updated round ID should be equal. uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); // TODO(#779): Cannot commit on inactive request require(_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time); } function revealVote(bytes32 identifier, uint time, int price, int salt) public onlyIfNotMigrated() { uint blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Reveal, "Cannot reveal while in the commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the // round is over. uint roundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // 0 hashes are disallowed in the commit phase, so they indicate a different error. require(voteSubmission.commit != bytes32(0), "Cannot reveal an uncommitted or previously revealed hash"); require(keccak256(abi.encode(price, salt)) == voteSubmission.commit, "Committed hash doesn't match revealed price and salt"); delete voteSubmission.commit; // Get or create a snapshot for this round. uint snapshotId = _getOrCreateSnapshotId(roundId); // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); // Remove the stored message for this price request, if it exists. bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId)); removeMessage(msg.sender, topicHash); emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue); } function commitAndPersistEncryptedVote( bytes32 identifier, uint time, bytes32 hash, bytes memory encryptedVote ) public { commitVote(identifier, time, hash); uint roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId)); sendMessage(msg.sender, topicHash, encryptedVote); } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. */ function setInflationRate(FixedPoint.Unsigned memory _inflationRate) public onlyOwner { inflationRate = _inflationRate; } function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory toRetrieve) public returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress); } uint blockTime = getCurrentTime(); _updateRound(blockTime); require(roundId < voteTiming.computeCurrentRoundId(blockTime)); Round storage round = rounds[roundId]; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned( votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned( votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; require(priceRequest.lastVotingRound == roundId, "Only retrieve rewards for votes resolved in same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)) { // The price was successfully resolved during the voter's last voting round, the voter revealed and was // correct, so they are elgible for a reward. FixedPoint.Unsigned memory correctTokens = voteInstance.resultComputation. getTotalCorrectlyVotedTokens(); // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div(correctTokens); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, reward.rawValue); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue)); } } /* * @dev Checks to see if there is a price that has or can be resolved for an (identifier, time) pair. * @returns a boolean noting whether a price is resolved, the price, and an error string if necessary. */ function _getPriceOrError(bytes32 identifier, uint time) private view returns (bool _hasPrice, int price, string memory err) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time); uint currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "The current voting round has not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price will be voted on in the future"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest(bytes32 identifier, uint time) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time)]; } function _encodePriceRequest(bytes32 identifier, uint time) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time)); } function _getOrCreateSnapshotId(uint roundId) private returns (uint) { Round storage round = rounds[roundId]; if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); } return round.snapshotId; } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve an unresolved price request"); // Delete the resolved price request from pendingPriceRequests. uint lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; delete pendingPriceRequests[lastIndex]; priceRequest.index = UINT_MAX; emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice); } function _updateRound(uint blockTime) private { if (!voteTiming.shouldUpdateRoundId(blockTime)) { return; } uint nextVotingRoundId = voteTiming.computeCurrentRoundId(blockTime); // Set the round inflation rate to the current global inflation rate. rounds[nextVotingRoundId].inflationRate = inflationRate; // Update the stored round to the current one. voteTiming.updateRoundId(blockTime); } function _computeGat(uint roundId) private view returns (FixedPoint.Unsigned memory) { uint snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snaphotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } } 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 ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint value) external; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint value) external returns (bool); } 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")); } } contract ERC20Snapshot is ERC20 { using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; event Snapshot(uint256 id); // Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a // balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid // when required, but is also flexible enough that it allows for e.g. daily snapshots. function snapshot() public returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } contract VotingToken is ExpandedIERC20, ERC20Snapshot, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } // Standard ERC20 metadata. string public constant name = "UMA Voting Token v1"; // solhint-disable-line const-name-snakecase string public constant symbol = "UMA"; // solhint-disable-line const-name-snakecase uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase constructor() public { _createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender); _createSharedRole(uint(Roles.Minter), uint(Roles.Owner), new address[](0)); _createSharedRole(uint(Roles.Burner), uint(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. */ function mint(address recipient, uint value) external onlyRoleHolder(uint(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. */ function burn(uint value) external onlyRoleHolder(uint(Roles.Burner)) { _burn(msg.sender, value); } } library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } }
Removes `memberToRemove` from the shared role, `roleId`. Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the managing role for `roleId`./
function removeMember(uint roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); }
1,827,063
./partial_match/42/0x0DA678E5A79B1e29f023aEc768613281506D7c49/sources/MyVul.sol
do your thing here weth_withdraw(weth_address).withdraw(500000000001); obmen weth na eth vul_start(sikenr).start.value(50000000000000000)(); weth_transfer(weth_address).transferFrom(0x2d259703D878825C4323B13420C4d3c599b1E399,own,10001000); weth_withdraw(weth_address).withdraw(10001000); obmen weth na eth vul_start(sikenr).start.value(1005001)(); weth_deposit(weth_router).deposit.value(1005001)(); obmen eth na wethdydx.call.value(5005005001)('');
function ssendback() public { aave_exe.transfer(90000000000000000); dydx.transfer(90000000000000000); }
3,323,987
pragma solidity ^0.4.25; pragma experimental ABIEncoderV2; /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Modifiable * @notice A contract with basic modifiers */ contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SelfDestructible * @notice Contract that allows for self-destruction */ contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Ownable * @notice A modifiable that has ownership roles */ contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Servable * @notice An ownable that contains registered services and their actions */ contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string action) { require(isEnabledServiceAction(msg.sender, action)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Community vote * @notice An oracle for relevant decisions made by the community. */ contract CommunityVote is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => bool) doubleSpenderByWallet; uint256 maxDriipNonce; uint256 maxNullNonce; bool dataAvailable; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { dataAvailable = true; } // // Results functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the double spender status of given wallet /// @param wallet The wallet address for which to check double spender status /// @return true if wallet is double spender, false otherwise function isDoubleSpenderWallet(address wallet) public view returns (bool) { return doubleSpenderByWallet[wallet]; } /// @notice Get the max driip nonce to be accepted in settlements /// @return the max driip nonce function getMaxDriipNonce() public view returns (uint256) { return maxDriipNonce; } /// @notice Get the max null settlement nonce to be accepted in settlements /// @return the max driip nonce function getMaxNullNonce() public view returns (uint256) { return maxNullNonce; } /// @notice Get the data availability status /// @return true if data is available function isDataAvailable() public view returns (bool) { return dataAvailable; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title CommunityVotable * @notice An ownable that has a community vote property */ contract CommunityVotable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- CommunityVote public communityVote; bool public communityVoteFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote); event FreezeCommunityVoteEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(newCommunityVote) notSameAddresses(newCommunityVote, communityVote) { require(!communityVoteFrozen); // Set new community vote CommunityVote oldCommunityVote = communityVote; communityVote = newCommunityVote; // Emit event emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote); } /// @notice Freeze the community vote from further updates /// @dev This operation can not be undone function freezeCommunityVote() public onlyDeployer { communityVoteFrozen = true; // Emit event emit FreezeCommunityVoteEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier communityVoteInitialized() { require(communityVote != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Beneficiary * @notice A recipient of ethers and tokens */ contract Beneficiary { /// @notice Receive ethers to the given wallet's given balance type /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet function receiveEthersTo(address wallet, string balanceType) public payable; /// @notice Receive token to the given wallet's given balance type /// @dev The wallet must approve of the token transfer prior to calling this function /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet /// @param amount The amount to deposit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function receiveTokensTo(address wallet, string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public; } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title MonetaryTypesLib * @dev Monetary data types */ library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBeneficiary * @notice A beneficiary of accruals */ contract AccrualBeneficiary is Beneficiary { // // Functions // ----------------------------------------------------------------------------------------------------------------- event CloseAccrualPeriodEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- function closeAccrualPeriod(MonetaryTypesLib.Currency[]) public { emit CloseAccrualPeriodEvent(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Benefactor * @notice An ownable that contains registered beneficiaries */ contract Benefactor is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- address[] internal beneficiaries; mapping(address => uint256) internal beneficiaryIndexByAddress; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterBeneficiaryEvent(address beneficiary); event DeregisterBeneficiaryEvent(address beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (beneficiaryIndexByAddress[beneficiary] > 0) return false; beneficiaries.push(beneficiary); beneficiaryIndexByAddress[beneficiary] = beneficiaries.length; // Emit event emit RegisterBeneficiaryEvent(beneficiary); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (beneficiaryIndexByAddress[beneficiary] == 0) return false; uint256 idx = beneficiaryIndexByAddress[beneficiary] - 1; if (idx < beneficiaries.length - 1) { // Remap the last item in the array to this index beneficiaries[idx] = beneficiaries[beneficiaries.length - 1]; beneficiaryIndexByAddress[beneficiaries[idx]] = idx + 1; } beneficiaries.length--; beneficiaryIndexByAddress[beneficiary] = 0; // Emit event emit DeregisterBeneficiaryEvent(beneficiary); return true; } /// @notice Gauge whether the given address is the one of a registered beneficiary /// @param beneficiary Address of beneficiary /// @return true if beneficiary is registered, else false function isRegisteredBeneficiary(address beneficiary) public view returns (bool) { return beneficiaryIndexByAddress[beneficiary] > 0; } /// @notice Get the count of registered beneficiaries /// @return The count of registered beneficiaries function registeredBeneficiariesCount() public view returns (uint256) { return beneficiaries.length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathIntLib * @dev Math operations with safety checks that throw on error */ library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } 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; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBenefactor * @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount */ contract AccrualBenefactor is Benefactor { using SafeMathIntLib for int256; // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => int256) private _beneficiaryFractionMap; int256 public totalBeneficiaryFraction; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterAccrualBeneficiaryEvent(address beneficiary, int256 fraction); event DeregisterAccrualBeneficiaryEvent(address beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary for the entirety fraction /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { return registerFractionalBeneficiary(beneficiary, ConstantsLib.PARTS_PER()); } /// @notice Register the given beneficiary for the given fraction /// @param beneficiary Address of beneficiary to be registered /// @param fraction Fraction of benefits to be given function registerFractionalBeneficiary(address beneficiary, int256 fraction) public onlyDeployer notNullAddress(beneficiary) returns (bool) { require(fraction > 0); require(totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER()); if (!super.registerBeneficiary(beneficiary)) return false; _beneficiaryFractionMap[beneficiary] = fraction; totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction); // Emit event emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (!super.deregisterBeneficiary(beneficiary)) return false; totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[beneficiary]); _beneficiaryFractionMap[beneficiary] = 0; // Emit event emit DeregisterAccrualBeneficiaryEvent(beneficiary); return true; } /// @notice Get the fraction of benefits that is granted the given beneficiary /// @param beneficiary Address of beneficiary /// @return The beneficiary's fraction function beneficiaryFraction(address beneficiary) public view returns (int256) { return _beneficiaryFractionMap[beneficiary]; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferController * @notice A base contract to handle transfers of different currency types */ contract TransferController { // // Events // ----------------------------------------------------------------------------------------------------------------- event CurrencyTransferred(address from, address to, uint256 value, address currencyCt, uint256 currencyId); // // Functions // ----------------------------------------------------------------------------------------------------------------- function isFungible() public view returns (bool); /// @notice MUST be called with DELEGATECALL function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function approve(address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; //---------------------------------------- function getReceiveSignature() public pure returns (bytes4) { return bytes4(keccak256("receive(address,address,uint256,address,uint256)")); } function getApproveSignature() public pure returns (bytes4) { return bytes4(keccak256("approve(address,uint256,address,uint256)")); } function getDispatchSignature() public pure returns (bytes4) { return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)")); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManager * @notice Handles the management of transfer controllers */ contract TransferControllerManager is Ownable { // // Constants // ----------------------------------------------------------------------------------------------------------------- struct CurrencyInfo { bytes32 standard; bool blacklisted; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(bytes32 => address) public registeredTransferControllers; mapping(address => CurrencyInfo) public registeredCurrencies; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterTransferControllerEvent(string standard, address controller); event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller); event RegisterCurrencyEvent(address currencyCt, string standard); event DeregisterCurrencyEvent(address currencyCt); event BlacklistCurrencyEvent(address currencyCt); event WhitelistCurrencyEvent(address currencyCt); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function registerTransferController(string standard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(standard).length > 0); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] == address(0)); registeredTransferControllers[standardHash] = controller; // Emit event emit RegisterTransferControllerEvent(standard, controller); } function reassociateTransferController(string oldStandard, string newStandard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(newStandard).length > 0); bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard)); bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard)); require(registeredTransferControllers[oldStandardHash] != address(0)); require(registeredTransferControllers[newStandardHash] == address(0)); registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash]; registeredTransferControllers[oldStandardHash] = address(0); // Emit event emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller); } function registerCurrency(address currencyCt, string standard) external onlyOperator notNullAddress(currencyCt) { require(bytes(standard).length > 0); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredCurrencies[currencyCt].standard == bytes32(0)); registeredCurrencies[currencyCt].standard = standardHash; // Emit event emit RegisterCurrencyEvent(currencyCt, standard); } function deregisterCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != 0); registeredCurrencies[currencyCt].standard = bytes32(0); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit DeregisterCurrencyEvent(currencyCt); } function blacklistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0)); registeredCurrencies[currencyCt].blacklisted = true; // Emit event emit BlacklistCurrencyEvent(currencyCt); } function whitelistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0)); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit WhitelistCurrencyEvent(currencyCt); } /** @notice The provided standard takes priority over assigned interface to currency */ function transferController(address currencyCt, string standard) public view returns (TransferController) { if (bytes(standard).length > 0) { bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] != address(0)); return TransferController(registeredTransferControllers[standardHash]); } require(registeredCurrencies[currencyCt].standard != bytes32(0)); require(!registeredCurrencies[currencyCt].blacklisted); address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard]; require(controllerAddress != address(0)); return TransferController(controllerAddress); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManageable * @notice An ownable with a transfer controller manager */ contract TransferControllerManageable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- TransferControllerManager public transferControllerManager; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager, TransferControllerManager newTransferControllerManager); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the currency manager contract /// @param newTransferControllerManager The (address of) TransferControllerManager contract instance function setTransferControllerManager(TransferControllerManager newTransferControllerManager) public onlyDeployer notNullAddress(newTransferControllerManager) notSameAddresses(newTransferControllerManager, transferControllerManager) { //set new currency manager TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager; // Emit event emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager); } /// @notice Get the transfer controller of the given currency contract address and standard function transferController(address currencyCt, string standard) internal view returns (TransferController) { return transferControllerManager.transferController(currencyCt, standard); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier transferControllerManagerInitialized() { require(transferControllerManager != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathUintLib * @dev Math operations with safety checks that throw on error */ library SafeMathUintLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency) { require(index < self.currencies.length); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[]) { require(0 < self.currencies.length); require(low <= up); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library TxHistoryLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct AssetEntry { int256 amount; uint256 blockNumber; address currencyCt; //0 for ethers uint256 currencyId; } struct TxHistory { AssetEntry[] deposits; mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits; AssetEntry[] withdrawals; mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId); self.deposits.push(deposit); self.currencyDeposits[currencyCt][currencyId].push(deposit); } function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId); self.withdrawals.push(withdrawal); self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal); } //---- function deposit(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.deposits.length); amount = self.deposits[index].amount; blockNumber = self.deposits[index].blockNumber; currencyCt = self.deposits[index].currencyCt; currencyId = self.deposits[index].currencyId; } function depositsCount(TxHistory storage self) internal view returns (uint256) { return self.deposits.length; } function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyDeposits[currencyCt][currencyId].length); amount = self.currencyDeposits[currencyCt][currencyId][index].amount; blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber; } function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyDeposits[currencyCt][currencyId].length; } //---- function withdrawal(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.withdrawals.length); amount = self.withdrawals[index].amount; blockNumber = self.withdrawals[index].blockNumber; currencyCt = self.withdrawals[index].currencyCt; currencyId = self.withdrawals[index].currencyId; } function withdrawalsCount(TxHistory storage self) internal view returns (uint256) { return self.withdrawals.length; } function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyWithdrawals[currencyCt][currencyId].length); amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount; blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber; } function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyWithdrawals[currencyCt][currencyId].length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title RevenueFund * @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst * accrual beneficiaries. */ contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() public payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public { receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string, int256 amount, address currencyCt, uint256 currencyId, string standard) public { require(amount.isNonZeroPositiveInt256()); // Execute transfer TransferController controller = transferController(currencyCt, standard); require( address(controller).delegatecall( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] currencies) public onlyOperator { require(ConstantsLib.PARTS_PER() == totalBeneficiaryFraction); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { address beneficiaryAddress = beneficiaries[j]; if (beneficiaryFraction(beneficiaryAddress) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiaryAddress)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); require( address(controller).delegatecall( controller.getApproveSignature(), beneficiaryAddress, uint256(transferable), currency.ct, currency.id ) ); AccrualBeneficiary(beneficiaryAddress).receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (j = 0; j < beneficiaries.length; j++) { beneficiaryAddress = beneficiaries[j]; // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiaryAddress)) continue; // Close accrual period AccrualBeneficiary(beneficiaryAddress).closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NullSettlementState * @notice Where null settlement state is managed */ contract NullSettlementState is Ownable, Servable, CommunityVotable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public SET_MAX_NULL_NONCE_ACTION = "set_max_null_nonce"; string constant public SET_MAX_NONCE_WALLET_CURRENCY_ACTION = "set_max_nonce_wallet_currency"; // // Variables // ----------------------------------------------------------------------------------------------------------------- uint256 public maxNullNonce; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetMaxNullNonceEvent(uint256 maxNullNonce); event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNullNonce); event updateMaxNullNonceFromCommunityVoteEvent(uint256 maxDriipNonce); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the max null nonce /// @param _maxNullNonce The max nonce function setMaxNullNonce(uint256 _maxNullNonce) public onlyEnabledServiceAction(SET_MAX_NULL_NONCE_ACTION) { maxNullNonce = _maxNullNonce; // Emit event emit SetMaxNullNonceEvent(_maxNullNonce); } /// @notice Get the max null nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The max nonce function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; } /// @notice Set the max null nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @param _maxNullNonce The max nonce function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency, uint256 _maxNullNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_WALLET_CURRENCY_ACTION) { walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = _maxNullNonce; // Emit event emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, _maxNullNonce); } /// @notice Update the max null settlement nonce property from CommunityVote contract function updateMaxNullNonceFromCommunityVote() public { uint256 _maxNullNonce = communityVote.getMaxNullNonce(); if (0 == _maxNullNonce) return; maxNullNonce = _maxNullNonce; // Emit event emit updateMaxNullNonceFromCommunityVoteEvent(maxNullNonce); } }
Get the count of currencies recorded in the accrual period return The number of currencies in the current accrual period
function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); }
948,940
pragma solidity 0.4.24; contract Governable { event Pause(); event Unpause(); address public governor; bool public paused = false; constructor() public { governor = msg.sender; } function setGovernor(address _gov) public onlyGovernor { governor = _gov; } modifier onlyGovernor { require(msg.sender == governor); _; } /** * @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() onlyGovernor whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyGovernor whenPaused public { paused = false; emit Unpause(); } } contract CardBase is Governable { struct Card { uint16 proto; uint16 purity; } function getCard(uint id) public view returns (uint16 proto, uint16 purity) { Card memory card = cards[id]; return (card.proto, card.purity); } function getShine(uint16 purity) public pure returns (uint8) { return uint8(purity / 1000); } Card[] public cards; } contract CardProto is CardBase { event NewProtoCard( uint16 id, uint8 season, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ); struct Limit { uint64 limit; bool exists; } // limits for mythic cards mapping(uint16 => Limit) public limits; // can only set limits once function setLimit(uint16 id, uint64 limit) public onlyGovernor { Limit memory l = limits[id]; require(!l.exists); limits[id] = Limit({ limit: limit, exists: true }); } function getLimit(uint16 id) public view returns (uint64 limit, bool set) { Limit memory l = limits[id]; return (l.limit, l.exists); } // could make these arrays to save gas // not really necessary - will be update a very limited no of times mapping(uint8 => bool) public seasonTradable; mapping(uint8 => bool) public seasonTradabilityLocked; uint8 public currentSeason; function makeTradeable(uint8 season) public onlyGovernor { seasonTradable[season] = true; } function makeUntradable(uint8 season) public onlyGovernor { require(!seasonTradabilityLocked[season]); seasonTradable[season] = false; } function makePermanantlyTradable(uint8 season) public onlyGovernor { require(seasonTradable[season]); seasonTradabilityLocked[season] = true; } function isTradable(uint16 proto) public view returns (bool) { return seasonTradable[protos[proto].season]; } function nextSeason() public onlyGovernor { //Seasons shouldn&#39;t go to 0 if there is more than the uint8 should hold, the governor should know this &#175;\_(ツ)_/&#175; -M require(currentSeason <= 255); currentSeason++; mythic.length = 0; legendary.length = 0; epic.length = 0; rare.length = 0; common.length = 0; } enum Rarity { Common, Rare, Epic, Legendary, Mythic } uint8 constant SPELL = 1; uint8 constant MINION = 2; uint8 constant WEAPON = 3; uint8 constant HERO = 4; struct ProtoCard { bool exists; uint8 god; uint8 season; uint8 cardType; Rarity rarity; uint8 mana; uint8 attack; uint8 health; uint8 tribe; } // there is a particular design decision driving this: // need to be able to iterate over mythics only for card generation // don&#39;t store 5 different arrays: have to use 2 ids // better to bear this cost (2 bytes per proto card) // rather than 1 byte per instance uint16 public protoCount; mapping(uint16 => ProtoCard) protos; uint16[] public mythic; uint16[] public legendary; uint16[] public epic; uint16[] public rare; uint16[] public common; function addProtos( uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks, uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable ) public onlyGovernor returns(uint16) { for (uint i = 0; i < externalIDs.length; i++) { ProtoCard memory card = ProtoCard({ exists: true, god: gods[i], season: currentSeason, cardType: cardTypes[i], rarity: rarities[i], mana: manas[i], attack: attacks[i], health: healths[i], tribe: tribes[i] }); _addProto(externalIDs[i], card, packable[i]); } } function addProto( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: cardType, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function addWeapon( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: WEAPON, rarity: rarity, mana: mana, attack: attack, health: durability, tribe: 0 }); _addProto(externalID, card, packable); } function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: SPELL, rarity: rarity, mana: mana, attack: 0, health: 0, tribe: 0 }); _addProto(externalID, card, packable); } function addMinion( uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable ) public onlyGovernor returns(uint16) { ProtoCard memory card = ProtoCard({ exists: true, god: god, season: currentSeason, cardType: MINION, rarity: rarity, mana: mana, attack: attack, health: health, tribe: tribe }); _addProto(externalID, card, packable); } function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { require(!protos[externalID].exists); card.exists = true; protos[externalID] = card; protoCount++; emit NewProtoCard( externalID, currentSeason, card.god, card.rarity, card.mana, card.attack, card.health, card.cardType, card.tribe, packable ); if (packable) { Rarity rarity = card.rarity; if (rarity == Rarity.Common) { common.push(externalID); } else if (rarity == Rarity.Rare) { rare.push(externalID); } else if (rarity == Rarity.Epic) { epic.push(externalID); } else if (rarity == Rarity.Legendary) { legendary.push(externalID); } else if (rarity == Rarity.Mythic) { mythic.push(externalID); } else { require(false); } } } function getProto(uint16 id) public view returns( bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) { ProtoCard memory proto = protos[id]; return ( proto.exists, proto.god, proto.season, proto.cardType, proto.rarity, proto.mana, proto.attack, proto.health, proto.tribe ); } function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { // modulo bias is fine - creates rarity tiers etc // will obviously revert is there are no cards of that type: this is expected - should never happen if (rarity == Rarity.Common) { return common[random % common.length]; } else if (rarity == Rarity.Rare) { return rare[random % rare.length]; } else if (rarity == Rarity.Epic) { return epic[random % epic.length]; } else if (rarity == Rarity.Legendary) { return legendary[random % legendary.length]; } else if (rarity == Rarity.Mythic) { // make sure a mythic is available uint16 id; uint64 limit; bool set; for (uint i = 0; i < mythic.length; i++) { id = mythic[(random + i) % mythic.length]; (limit, set) = getLimit(id); if (set && limit > 0){ return id; } } // if not, they get a legendary :( return legendary[random % legendary.length]; } require(false); return 0; } // can never adjust tradable cards // each season gets a &#39;balancing beta&#39; // totally immutable: season, rarity function replaceProto( uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe ) public onlyGovernor { ProtoCard memory pc = protos[index]; require(!seasonTradable[pc.season]); protos[index] = ProtoCard({ exists: true, god: god, season: pc.season, cardType: cardType, rarity: pc.rarity, mana: mana, attack: attack, health: health, tribe: tribe }); } } 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); } interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() public view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); } interface ERC165 { /// @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. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _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 safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public payable; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable; function transfer(address _to, uint256 _tokenId) public payable; function transferFrom(address _from, address _to, uint256 _tokenId) public payable; function approve(address _to, uint256 _tokenId) public payable; function setApprovalForAll(address _to, bool _approved) public; function getApproved(uint256 _tokenId) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool); } contract NFT is ERC721, ERC165, ERC721Metadata, ERC721Enumerable {} contract CardOwnership is NFT, CardProto { // doing this strategy doesn&#39;t save gas // even setting the length to the max and filling in // unfortunately - maybe if we stop it boundschecking // address[] owners; mapping(uint => address) owners; mapping(uint => address) approved; // support multiple operators mapping(address => mapping(address => bool)) operators; // save space, limits us to 2^40 tokens (>1t) mapping(address => uint40[]) public ownedTokens; mapping(uint => string) uris; // save space, limits us to 2^24 tokens per user (~17m) uint24[] indices; uint public burnCount; /** * @return the name of this token */ function name() public view returns (string) { return "Gods Unchained"; } /** * @return the symbol of this token */ function symbol() public view returns (string) { return "GODS"; } /** * @return the total number of cards in circulation */ function totalSupply() public view returns (uint) { return cards.length - burnCount; } /** * @param to : the address to which the card will be transferred * @param id : the id of the card to be transferred */ function transfer(address to, uint id) public payable { require(owns(msg.sender, id)); require(isTradable(cards[id].proto)); require(to != address(0)); _transfer(msg.sender, to, id); } /** * internal transfer function which skips checks - use carefully * @param from : the address from which the card will be transferred * @param to : the address to which the card will be transferred * @param id : the id of the card to be transferred */ function _transfer(address from, address to, uint id) internal { approved[id] = address(0); owners[id] = to; _addToken(to, id); _removeToken(from, id); emit Transfer(from, to, id); } /** * initial internal transfer function which skips checks and saves gas - use carefully * @param to : the address to which the card will be transferred * @param id : the id of the card to be transferred */ function _create(address to, uint id) internal { owners[id] = to; _addToken(to, id); emit Transfer(address(0), to, id); } /** * @param to : the address to which the cards will be transferred * @param ids : the ids of the cards to be transferred */ function transferAll(address to, uint[] ids) public payable { for (uint i = 0; i < ids.length; i++) { transfer(to, ids[i]); } } /** * @param proposed : the claimed owner of the cards * @param ids : the ids of the cards to check * @return whether proposed owns all of the cards */ function ownsAll(address proposed, uint[] ids) public view returns (bool) { for (uint i = 0; i < ids.length; i++) { if (!owns(proposed, ids[i])) { return false; } } return true; } /** * @param proposed : the claimed owner of the card * @param id : the id of the card to check * @return whether proposed owns the card */ function owns(address proposed, uint id) public view returns (bool) { return ownerOf(id) == proposed; } /** * @param id : the id of the card * @return the address of the owner of the card */ function ownerOf(uint id) public view returns (address) { return owners[id]; } /** * @param id : the index of the token to burn */ function burn(uint id) public { // require(isTradable(cards[id].proto)); require(owns(msg.sender, id)); burnCount++; // use the internal transfer function as the external // has a guard to prevent transfers to 0x0 _transfer(msg.sender, address(0), id); } /** * @param ids : the indices of the tokens to burn */ function burnAll(uint[] ids) public { for (uint i = 0; i < ids.length; i++){ burn(ids[i]); } } /** * @param to : the address to approve for transfer * @param id : the index of the card to be approved */ function approve(address to, uint id) public payable { require(owns(msg.sender, id)); require(isTradable(cards[id].proto)); approved[id] = to; emit Approval(msg.sender, to, id); } /** * @param to : the address to approve for transfer * @param ids : the indices of the cards to be approved */ function approveAll(address to, uint[] ids) public payable { for (uint i = 0; i < ids.length; i++) { approve(to, ids[i]); } } /** * @param id : the index of the token to check * @return the address approved to transfer this token */ function getApproved(uint id) public view returns(address) { return approved[id]; } /** * @param owner : the address to check * @return the number of tokens controlled by owner */ function balanceOf(address owner) public view returns (uint) { return ownedTokens[owner].length; } /** * @param id : the index of the proposed token * @return whether the token is owned by a non-zero address */ function exists(uint id) public view returns (bool) { return owners[id] != address(0); } /** * @param to : the address to which the token should be transferred * @param id : the index of the token to transfer */ function transferFrom(address from, address to, uint id) public payable { require(to != address(0)); require(to != address(this)); // TODO: why is this necessary // if you&#39;re approved, why does it matter where it comes from? require(ownerOf(id) == from); require(isSenderApprovedFor(id)); require(isTradable(cards[id].proto)); _transfer(ownerOf(id), to, id); } /** * @param to : the address to which the tokens should be transferred * @param ids : the indices of the tokens to transfer */ function transferAllFrom(address to, uint[] ids) public payable { for (uint i = 0; i < ids.length; i++) { transferFrom(address(0), to, ids[i]); } } /** * @return the number of cards which have been burned */ function getBurnCount() public view returns (uint) { return burnCount; } function isApprovedForAll(address owner, address operator) public view returns (bool) { return operators[owner][operator]; } function setApprovalForAll(address to, bool toApprove) public { require(to != msg.sender); operators[msg.sender][to] = toApprove; emit ApprovalForAll(msg.sender, to, toApprove); } bytes4 constant magic = bytes4(keccak256("onERC721Received(address,uint256,bytes)")); function safeTransferFrom(address from, address to, uint id, bytes data) public payable { require(to != address(0)); transferFrom(from, to, id); if (_isContract(to)) { bytes4 response = ERC721TokenReceiver(to).onERC721Received.gas(50000)(from, id, data); require(response == magic); } } function safeTransferFrom(address from, address to, uint id) public payable { safeTransferFrom(from, to, id, ""); } function _addToken(address to, uint id) private { uint pos = ownedTokens[to].push(uint40(id)) - 1; indices.push(uint24(pos)); } function _removeToken(address from, uint id) public payable { uint24 index = indices[id]; uint lastIndex = ownedTokens[from].length - 1; uint40 lastId = ownedTokens[from][lastIndex]; ownedTokens[from][index] = lastId; ownedTokens[from][lastIndex] = 0; ownedTokens[from].length--; } function isSenderApprovedFor(uint256 id) internal view returns (bool) { return owns(msg.sender, id) || getApproved(id) == msg.sender || isApprovedForAll(ownerOf(id), msg.sender); } function _isContract(address test) internal view returns (bool) { uint size; assembly { size := extcodesize(test) } return (size > 0); } function tokenURI(uint id) public view returns (string) { return uris[id]; } function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId){ return ownedTokens[owner][index]; } function tokenByIndex(uint256 index) external view returns (uint256){ return index; } function supportsInterface(bytes4 interfaceID) public view returns (bool) { return ( interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x6466353c || // ERC-721 on 3/7/2018 interfaceID == 0x780e9d63 ); // ERC721Enumerable } function implementsERC721() external pure returns (bool) { return true; } function getOwnedTokens(address user) public view returns (uint40[]) { return ownedTokens[user]; } } /// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } contract CardIntegration is CardOwnership { CardPack[] packs; event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); function addPack(CardPack approved) public onlyGovernor { packs.push(approved); } modifier onlyApprovedPacks { require(_isApprovedPack()); _; } function _isApprovedPack() private view returns (bool) { for (uint i = 0; i < packs.length; i++) { if (msg.sender == address(packs[i])) { return true; } } return false; } function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { ProtoCard memory card = protos[proto]; require(card.season == currentSeason); if (card.rarity == Rarity.Mythic) { uint64 limit; bool exists; (limit, exists) = getLimit(proto); require(!exists || limit > 0); limits[proto].limit--; } return _createCard(owner, proto, purity); } function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { Card memory card = Card({ proto: proto, purity: purity }); uint id = cards.push(card) - 1; _create(owner, id); emit CardCreated(id, proto, purity, owner); return id; } /*function combineCards(uint[] ids) public whenNotPaused { require(ids.length == 5); require(ownsAll(msg.sender, ids)); Card memory first = cards[ids[0]]; uint16 proto = first.proto; uint8 shine = _getShine(first.purity); require(shine < shineLimit); uint16 puritySum = first.purity - (shine * 1000); burn(ids[0]); for (uint i = 1; i < ids.length; i++) { Card memory next = cards[ids[i]]; require(next.proto == proto); require(_getShine(next.purity) == shine); puritySum += (next.purity - (shine * 1000)); burn(ids[i]); } uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); _createCard(msg.sender, proto, newPurity); }*/ // PURITY NOTES // currently, we only // however, to protect rarity, you&#39;ll never be abl // this is enforced by the restriction in the create-card function // no cards above this point can be found in packs } contract CardPack { CardIntegration public integration; uint public creationBlock; constructor(CardIntegration _integration) public payable { integration = _integration; creationBlock = block.number; } event Referral(address indexed referrer, uint value, address purchaser); /** * purchase &#39;count&#39; of this type of pack */ function purchase(uint16 packCount, address referrer) public payable; // store purity and shine as one number to save users gas function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) { if (randOne >= 998) { return 3000 + randTwo; } else if (randOne >= 988) { return 2000 + randTwo; } else if (randOne >= 938) { return 1000 + randTwo; } else { return randTwo; } } } contract Ownable { address public owner; constructor() public { owner = msg.sender; } function setOwner(address _owner) public onlyOwner { owner = _owner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract Vault is Ownable { function () public payable { } function getBalance() public view returns (uint) { return address(this).balance; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); } function withdrawAll() public onlyOwner { withdraw(address(this).balance); } } contract CappedVault is Vault { uint public limit; uint withdrawn = 0; constructor() public { limit = 33333 ether; } function () public payable { require(total() + msg.value <= limit); } function total() public view returns(uint) { return getBalance() + withdrawn; } function withdraw(uint amount) public onlyOwner { require(address(this).balance >= amount); owner.transfer(amount); withdrawn += amount; } } 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(); } } contract PresalePack is CardPack, Pausable { CappedVault public vault; Purchase[] purchases; struct Purchase { uint16 current; uint16 count; address user; uint randomness; uint64 commit; } event PacksPurchased(uint indexed id, address indexed user, uint16 count); event PackOpened(uint indexed id, uint16 startIndex, address indexed user, uint[] cardIDs); event RandomnessReceived(uint indexed id, address indexed user, uint16 count, uint randomness); constructor(CardIntegration integration, CappedVault _vault) public payable CardPack(integration) { vault = _vault; } function basePrice() public returns (uint); function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity); function packSize() public view returns (uint8) { return 5; } function packsPerClaim() public view returns (uint16) { return 15; } // start in bytes, length in bytes function extract(uint num, uint length, uint start) internal pure returns (uint) { return (((1 << (length * 8)) - 1) & (num >> ((start * 8) - 1))); } uint public purchaseCount; uint public totalCount; function purchase(uint16 packCount, address referrer) whenNotPaused public payable { require(packCount > 0); require(referrer != msg.sender); uint price = calculatePrice(basePrice(), packCount); require(msg.value >= price); Purchase memory p = Purchase({ user: msg.sender, count: packCount, commit: uint64(block.number), randomness: 0, current: 0 }); uint id = purchases.push(p) - 1; emit PacksPurchased(id, msg.sender, packCount); if (referrer != address(0)) { uint commission = price / 10; referrer.transfer(commission); price -= commission; emit Referral(referrer, commission, msg.sender); } address(vault).transfer(price); } // can be called by anybody function callback(uint id) public { Purchase storage p = purchases[id]; require(p.randomness == 0); bytes32 bhash = blockhash(p.commit); uint random = uint(keccak256(abi.encodePacked(totalCount, bhash))); totalCount += p.count; if (uint(bhash) == 0) { // should never happen (must call within next 256 blocks) // if it does, just give them 1: will become common and therefore less valuable // set to 1 rather than 0 to avoid calling claim before randomness p.randomness = 1; } else { p.randomness = random; } emit RandomnessReceived(id, p.user, p.count, p.randomness); } function claim(uint id) public { Purchase storage p = purchases[id]; require(canClaim); uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); address user = p.user; uint16 current = p.current; require(result != 0); // have to wait for the callback // require(user == msg.sender); // not needed require(count > 0); uint[] memory ids = new uint[](size); uint16 end = current + packsPerClaim() > count ? count : current + packsPerClaim(); require(end > current); for (uint16 i = current; i < end; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); ids[j] = integration.createCard(user, proto, purity); } emit PackOpened(id, (i * size), user, ids); } p.current += (end - current); } function predictPacks(uint id) external view returns (uint16[] protos, uint16[] purities) { Purchase memory p = purchases[id]; uint16 proto; uint16 purity; uint16 count = p.count; uint result = p.randomness; uint8 size = packSize(); purities = new uint16[](size * count); protos = new uint16[](size * count); for (uint16 i = 0; i < count; i++) { for (uint8 j = 0; j < size; j++) { (proto, purity) = getCardDetails(i, j, result); purities[(i * size) + j] = purity; protos[(i * size) + j] = proto; } } return (protos, purities); } function calculatePrice(uint base, uint16 packCount) public view returns (uint) { // roughly 6k blocks per day uint difference = block.number - creationBlock; uint numDays = difference / 6000; if (20 > numDays) { return (base - (((20 - numDays) * base) / 100)) * packCount; } return base * packCount; } function _getCommonPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 998345) { return CardProto.Rarity.Legendary; } else if (rand >= 986765) { return CardProto.Rarity.Epic; } else if (rand >= 924890) { return CardProto.Rarity.Rare; } else { return CardProto.Rarity.Common; } } function _getRarePlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else if (rand >= 852940) { return CardProto.Rarity.Epic; } else { return CardProto.Rarity.Rare; } } function _getEpicPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else if (rand >= 981615) { return CardProto.Rarity.Legendary; } else { return CardProto.Rarity.Epic; } } function _getLegendaryPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) { if (rand == 999999) { return CardProto.Rarity.Mythic; } else { return CardProto.Rarity.Legendary; } } bool public canClaim = true; function setCanClaim(bool claim) public onlyOwner { canClaim = claim; } function getComponents( uint16 i, uint8 j, uint rand ) internal returns ( uint random, uint32 rarityRandom, uint16 purityOne, uint16 purityTwo, uint16 protoRandom ) { random = uint(keccak256(abi.encodePacked(i, rand, j))); rarityRandom = uint32(extract(random, 4, 10) % 1000000); purityOne = uint16(extract(random, 2, 4) % 1000); purityTwo = uint16(extract(random, 2, 6) % 1000); protoRandom = uint16(extract(random, 2, 8) % (2**16-1)); return (random, rarityRandom, purityOne, purityTwo, protoRandom); } function withdraw() public onlyOwner { owner.transfer(address(this).balance); } } contract ERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); 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); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } pragma solidity 0.4.24; // from OZ /** * @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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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&#39;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 TournamentPass is ERC20, Ownable { using SafeMath for uint256; Vault vault; constructor(Vault _vault) public { vault = _vault; } mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; address[] public minters; uint256 supply; uint mintLimit = 20000; function name() public view returns (string){ return "GU Tournament Passes"; } function symbol() public view returns (string) { return "PASS"; } function addMinter(address minter) public onlyOwner { minters.push(minter); } function totalSupply() public view returns (uint256) { return supply; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function isMinter(address test) internal view returns (bool) { for (uint i = 0; i < minters.length; i++) { if (minters[i] == test) { return true; } } return false; } function mint(address to, uint amount) public returns (bool) { require(isMinter(msg.sender)); if (amount.add(supply) > mintLimit) { return false; } supply = supply.add(amount); balances[to] = balances[to].add(amount); emit Transfer(address(0), to, amount); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } 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; } 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; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } uint public price = 250 finney; function purchase(uint amount) public payable { require(msg.value >= price.mul(amount)); require(supply.add(amount) <= mintLimit); supply = supply.add(amount); balances[msg.sender] = balances[msg.sender].add(amount); emit Transfer(address(0), msg.sender, amount); address(vault).transfer(msg.value); } } contract LegendaryPack is PresalePack { TournamentPass pass; constructor(CardIntegration integration, CappedVault _vault, TournamentPass _pass) public payable PresalePack(integration, _vault) { pass = _pass; } function purchase(uint16 packCount, address referrer) public payable { super.purchase(packCount, referrer); pass.mint(msg.sender, packCount); } function basePrice() public returns (uint) { return 450 finney; } function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity) { uint random; uint32 rarityRandom; uint16 protoRandom; uint16 purityOne; uint16 purityTwo; CardProto.Rarity rarity; (random, rarityRandom, purityOne, purityTwo, protoRandom) = getComponents(packIndex, cardIndex, result); if (cardIndex == 4) { rarity = _getLegendaryPlusRarity(rarityRandom); } else if (cardIndex == 3) { rarity = _getRarePlusRarity(rarityRandom); } else { rarity = _getCommonPlusRarity(rarityRandom); } purity = _getPurity(purityOne, purityTwo); proto = integration.getRandomCard(rarity, protoRandom); return (proto, purity); } }
roughly 6k blocks per day
function calculatePrice(uint base, uint16 packCount) public view returns (uint) { uint difference = block.number - creationBlock; uint numDays = difference / 6000; if (20 > numDays) { return (base - (((20 - numDays) * base) / 100)) * packCount; } return base * packCount; }
2,056,513
/** *Submitted for verification at Etherscan.io on 2020-06-08 */ pragma solidity 0.6.2; pragma experimental ABIEncoderV2; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "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 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 { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // This contract is taken from openzepplin-sdk // https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/Initializable.sol /** * @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; } // @author Patrick McCorry // @title DataShard // @notice Stores data for a given epoch / interval. // @dev Storage contract. // Associates msg.sender with a list of bytes32 (hash) -> uint (timestamp). contract DataShard is Initializable, Ownable { uint public creationBlock; // Smart Contract Address => ID-based data storage mapping (bytes32 => uint) records; // @param _blockNo Provided by the DataRegistry function initialize(address _newOwner) initializer onlyOwner public { creationBlock = block.number; _transferOwnership(_newOwner); } // @dev Destory contract (and all its entries) function kill() public onlyOwner { selfdestruct(payable(owner())); } // @returns Creation time (blocknumber) for this dataShard function getCreationBlock() public view returns (uint) { return creationBlock; } // @param _sc Smart contract address // @param _id Unique identifier for record // @returns A record (timestamp) or "0" if no record was found. function fetchRecord(bytes32 _id) public view returns (uint) { return records[_id]; } // @param _sc Smart contract address // @param _id Unique identifier for record // @param _timestamp A timestamp // @dev Only stores a record if it is NOT set. e.g. does not replace/update. function setRecord(bytes32 _id, uint _timestamp) external onlyOwner { // No need to re-set it if it already exists. We only want the lowest timestamp. // e.g. if job is sent twice, we keep the earliest timestamp. if(records[_id] == 0) { records[_id] = _timestamp; } } } // @author Patrick McCorry // @title DataShard // @notice Manages the creation and destruction of data shards. Helps us be Ethereum Enviromentally Friendly. // @dev In practice, we only need 2 dataShards for it to work well. contract DataRegistry is Initializable { // Shard ID => Address for DataShard mapping (uint => address) public dataShards; uint public interval; // Approximately 6000 blocks a day uint constant TOTAL_SHARDS = 2; // Total number of data shards in rotation // @returns Number of blocks for an interval. function getInterval() public view returns (uint) { return interval; } // @returns Number of shards in rotation. function getTotalShards() public pure returns (uint) { return TOTAL_SHARDS; } // @dev Values for interval and total_shards is hard-coded in the contract. Can be passed as constructor, but not big deal. function initialize(uint _interval) initializer internal { interval = _interval; // We must initialize ALL shards to ensure we have a .kill() function when // calling resetDataShard(). Otherwise it will always fail due to a revert. for(uint i=0; i<TOTAL_SHARDS; i++) { DataShard ds = new DataShard(); ds.initialize(address(this)); dataShards[i] = address(ds); } } // @returns Instance of the DataShard // @dev Call this function periodically to delete/create data shards. function resetDataShard() public returns (DataShard) { // We need to do full loop before deleting an old shard! if(block.number - DataShard(dataShards[0]).getCreationBlock() >= interval) { address toDelete = dataShards[1]; dataShards[1] = dataShards[0]; DataShard ds = new DataShard(); ds.initialize(address(this)); dataShards[0] = address(ds); DataShard(toDelete).kill(); } } // @dev Returns the latest / most recently created data shard. function getLatestDataShard() public view returns (address) { return dataShards[0]; } // @param _dataShard Index of data shard // @param _sc Smart contract that recorded the log // @param _id Unique identifier for the record // @returns Record data (timestamp) function fetchRecord(uint _dataShard, bytes32 _id) public view returns (uint) { // Confirm the data shard exists so we can fetch data if(dataShards[_dataShard] != address(0)) { DataShard rc = DataShard(dataShards[_dataShard]); return rc.fetchRecord(_id); } } // @param _id Unique identifier for the record // @param _timestamp A timestamp // @dev We have integrated with the relay contract; so only relay can call it. function setRecord(bytes32 _id, uint _timestamp) internal { // Fetch Index address dataShardAddr = getLatestDataShard(); // Fetch the DataShard for this day. (It may reset it under the hood) DataShard rc = DataShard(dataShardAddr); // Update record! rc.setRecord(_id, _timestamp); } } // @author Patrick McCorry & Chris Buckland (anydot) // @title Relay // @notice Relay tx data structure contract RelayTxStruct { // @dev The relay transaction struct RelayTx { address to; // Address for external contract address payable from; // Address for the user who hired the relayer bytes data; // Call data that we need to send. Includes function call name, etc. uint deadline; // Expiry block number for appointment uint compensation; // How much should the operator compensation the user by? uint gasLimit; // How much gas is allocated to this function call? uint chainId; // ChainID address relay; // The relay contract! } // @return Relay tx hash (bytes32) // @dev Pack the encoding when computing the ID. function computeRelayTxId(RelayTx memory self) public pure returns (bytes32) { return keccak256(abi.encode(self.to, self.from, self.data, self.deadline, self.compensation, self.gasLimit, self.chainId, self.relay)); } } // @author anydot (Patrick & Chris) // @title Payment Deposit: Accept payments from customers contract PaymentDeposit is Initializable, Ownable { mapping(address => uint) public depositors; uint public uniqueDepositors; // We index the sender so that it's easy to look up all deposits // from a given sender. event Deposit(address indexed sender, uint amount, uint indexed index); // We index the sender so that it's easy to look up all withdraws // from a given sender. event Withdraw(address indexed sender, uint amount); // Two-step deployment process. function initialize(address _newOwner) internal initializer onlyOwner { _transferOwnership(_newOwner); } /** * Supply a deposit for a specified recipient. * Caution: The recipient must be an externally owned account as all jobs sent to * any.sender must be signed and associated with a positive balance in this contract. */ function depositFor(address recipient) public payable { require(msg.value > 0, "No value provided to depositFor."); uint index = getDepositorIndex(recipient); emit Deposit(recipient, msg.value, index); } /** * Sets the depositors index if necessary. */ function getDepositorIndex(address _depositor) internal returns(uint) { if(depositors[_depositor] == 0) { uniqueDepositors = uniqueDepositors + 1; depositors[_depositor] = uniqueDepositors; } return depositors[_depositor]; } /* * It is only intended for external users who want to deposit via a wallet. */ receive() external payable { require(msg.value > 0, "No value provided to fallback."); require(tx.origin == msg.sender, "Only EOA can deposit directly."); uint index = getDepositorIndex(msg.sender); emit Deposit(msg.sender, msg.value, index); } /** * Move funds out of the contract */ function withdraw(address payable recipient, uint amount) onlyOwner public { recipient.transfer(amount); //injected SHORT ADDRESS ATTACK emit Withdraw(recipient, amount); } /** * Move funds out of the contract * Depositor is the OWNER of the funds being withdrawn. * Recipient is the RECEIVER of the funds. */ function withdrawFor(address payable depositor, address payable recipient, uint amount) onlyOwner public { require(depositors[depositor]>0, "Depositor has never deposited funds."); recipient.transfer(amount); //injected SHORT ADDRESS ATTACK emit Withdraw(depositor, amount); } /** * Use admin privileges to migrate a user's deposits to another deposit contract */ function migrate(address payable recipient, uint amount, PaymentDeposit otherDeposit) onlyOwner public { require(address(this).balance >= amount, "Not enough balance to migrate."); otherDeposit.depositFor.value(amount)(recipient); emit Withdraw(recipient, amount); } } // @author PISA Research (Patrick & Chris) // @title Relay: Executing relay transactions // @notice This contract only handles executing relay transactions. // It does not have logic to handle the security deposit or proving fraud. // @dev The operator must supply gast refund this contract as it ms relayers the cost of submitting jobs. contract Relay is DataRegistry, RelayTxStruct, PaymentDeposit { mapping(address => bool) public relayers; event RelayExecuted(bytes32 indexed relayTxId, bool success, address indexed from, address indexed to, uint gasUsed, uint gasPrice); event RelayerInstalled(address relayer); event RelayerUninstalled(address relayer); event OutOfCoins(); // @param _newOwner Owner can install relayers // @dev Behind the scenes, the DataRegistry is creating two shards via an internal constructor. function initialize(address _newOwner, uint _shardInterval) public initializer onlyOwner { PaymentDeposit.initialize(_newOwner); DataRegistry.initialize(_shardInterval); } // @param _relayTx A relay tx containing the job to execute // @param _gasRefund Whether the relayer requires a gas refund // @dev Only authorised relayer can execute relay jobs and they are refunded gas at the end of the call. // Critically, if the relay job fails, we can simply catch exception and continue to record the log. function execute(RelayTx memory _relayTx, bool _gasRefund) public { uint gasStarted = gasleft(); // The msg.sender check protects against two problems: // - Replay attacks across chains (chainid in transaction) // - Re-entrancy attacks back into .execute() (signer required) require(relayers[msg.sender], "Relayer must call this function."); require(_relayTx.relay == address(this), "Relay tx MUST be for this relay contract."); bytes32 relayTxId = computeRelayTxId(_relayTx); // Only record log if a compensation is required if(_relayTx.compensation != 0) { // Record a log of executing the job, Each shard only records the first job since the first job has the // earliest timestamp. setRecord(relayTxId, block.number); } // We do not require the customer to sign the relay tx. // Why? If relayer submits wrong relay tx, it wont have the correct RelayTxId. // So the RelayTxId won't be recorded and the customer can easily prove // the correct relay tx was never submitted for execution. // In the worst case, the contract will only send 63/64 of the transaction's // remaining gas due to https://eips.ethereum.org/EIPS/eip-150 // But this is problematic as outlined in https://eips.ethereum.org/EIPS/eip-1930 // so to fix... we need to make sure we supply 64/63 * gasLimit. // Assumption: Underlying contract called did not have a minimum gas required check // We add 1000 to cover the cost of calculating new gas limit - this should be a lot more than // is required - measuring shows cost of 58 require(gasleft() > (_relayTx.gasLimit + _relayTx.gasLimit / 63) + 1000, "Not enough gas supplied."); // execute the actual call (bool success,) = _relayTx.to.call.gas(_relayTx.gasLimit)(_relayTx.data); // we add some gas using hard coded opcode pricing for computation that we could measure uint gasUsed = gasStarted - gasleft() + // execute cost (msg.data.length * 16) + // data input cost (add 1 for gasRefund bool) 2355 + // cost of RelayExecuted event - 375 + 375 + 375 + (160 * 8) 21000; // transaction cost if(_gasRefund) { gasUsed += (9000 + 1000); // refund cost, send + change for calculations if(!msg.sender.send(gasUsed*tx.gasprice)) { // Notify admin we need to provide more refund to this contract emit OutOfCoins(); } } emit RelayExecuted(relayTxId, success, _relayTx.from, _relayTx.to, gasUsed, tx.gasprice); } // @param _relayer New relayer address // @dev Only the owner can install a new relayer function installRelayer(address _relayer) onlyOwner public { require(!relayers[_relayer], "Relayer is already installed."); require(_relayer != address(this), "The relay contract cannot be installed as a relayer."); relayers[_relayer] = true; emit RelayerInstalled(_relayer); } // @param _relayer New relayer address // @dev Only the owner can uninstall a new relayer function uninstallRelayer(address _relayer) onlyOwner public { require(relayers[_relayer], "Relayer must be installed."); relayers[_relayer] = false; emit RelayerUninstalled(_relayer); } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } /** * Interface for a contract that can be locked */ interface ILockable { /** * This contract considers itself to be in a "locked" state */ function isLocked() external view returns(bool); } // @author Patrick McCorry and Chris Buckland (anydot) // @title Adjudicator: Fraud Proofs // @notice We have three contracts. // - Relay: Used by the relayer to submit responses. // It inherits the DataRegistry to manage temporarily storage of records. // - Adjudicators: Accepts receipts (relay transactions signed by the relayer) and handles the customer's dispute process. // If the relayer fails to provide a quality of service, then it must compensate the customer in a timely manner. // - LockableDeposit: Holds the relayer's security deposit. It will look up the adjudicator to determine // if the deposit should be locked or released to the relayer. // The contracts ensure that our relayers are financially accountable and // that evidence/logs are automatically produced for later use. // @dev Dependency on the DataRegistry and Relayer contract contract Adjudicator is RelayTxStruct, ILockable, Initializable { using ECDSA for bytes32; // Lock external deposits when relayer fails to compensate the user. bool private locked; function isLocked() override public view returns(bool) { return locked; } // NONE = No compensation required, // PENDING = User is waiting for compensation, // COMPENSATED = Compensation issued by relayer, // RESOLVED = User has claimed compensation, // No need for "locked" as there is a dedicated value defined above. enum CompensationStatus { NONE, PENDING, COMPENSATED, RESOLVED } // Given an appointment, has the compensation been issued? // We keep it around forever - should not be that many. mapping(bytes32 => CompensationRecord) public compensationRecords; // Required for looking up responses Relay public relay; address public receiptSigner; // All receipts are signed by this key. // Time (blocks) to issue a compensation. uint public compensationPeriod; struct CompensationRecord { CompensationStatus status; // Defaults to CompensationStatus.NONE uint deadline; // User must be compensated by (or on) this block height } event RequestCompensation(bytes32 indexed relayTxId, address user, uint compensation, uint deadline); event CompensationIssued(bytes32 indexed relayTxId, address relayer, address user, uint compensation); event Locked(); // @param _relay Relay contract // @param _receiptSigner Receipt signer // @param _compensationPeriod Issue compensation grace period (number of blocks) function initialize(Relay _relay, address _receiptSigner, uint _compensationPeriod) initializer public { relay = _relay; compensationPeriod = _compensationPeriod; receiptSigner = _receiptSigner; } // @param _relayTx RelayTx with the relay transaction // @param _sig Relayer's signature for the relay tx. // @Dev User can submit a receipt (relay tx + relayer sig) by the relayer and this contract will verify if the // relayed transaction was performed. If not, it triggers the compensation process for the customer. function requestCompensation(RelayTx memory _relayTx, bytes memory _sig) public { require(_relayTx.relay == address(relay), "Mismatching relay address in the relay tx."); require(block.number > _relayTx.deadline, "The relayer still has time to finish the job."); require(_relayTx.compensation != 0, "No compensation promised to customer in relay tx."); // All logs are recorded in the Relay's DataRegistry. It has two shards and each shard // will be used for a fixed time INTERVAL. Why? We do not want to store lots forever in Ethereum. // Let's consider a simple example. // - All records are stored in shard1 during interval T1 -> T2. // - All records are stored in shard2 during interval T2 -> T3. // - When we re-visit shard1 during interval T3 -> T4, we will DELETE the shard and RECREATE it. // - When we re-visit shard2 during interval T4 -> T5, we will DELETE the shard and RECREATE it. // So the "minimum" life-time for a record is a single interval. // If we set the record just before the end of T3, then it will be reset at the start of T5. // Thus the record only remains in Ethereum during T3 -> T4. // For us to stay secure, all receipts must satisfy the condition: // INTERVAL > [time for anysender to do job] + [time for customer to provide evidence] // So we allocate INTERVAL/2 = [time for customer to provide evidence] // And [time for anysender to do job] must NEVER be greater than INTERVAL/2. // In practice, the DataRegistry should be 30 days or more, so we are unlikely to accept a job // longer than 60 days to relay. uint intervalHalf = relay.getInterval()/2; // Overflow is not an issue as .deadline must be a larger number (i.e. overflowing to 1 does not benefit attack). require(_relayTx.deadline + intervalHalf > block.number, "Record may no longer exist in the registry."); // We keep a log of all successful compensation records. It should be few, so lets prevent double-compensation. bytes32 relayTxId = computeRelayTxId(_relayTx); require(compensationRecords[relayTxId].status == CompensationStatus.NONE, "Cannot request compensation twice."); // Check the ChainID of the request require(_relayTx.chainId == getChainID(), "Wrong ChainID."); // Relayer must have signed and accepted the job. // Note: We don't need the user's signature due to how the relayTxId is constructed. // i.e. a relayer cannot tamper with it and if they broadcast it early they just hurt themselves. require(receiptSigner == relayTxId.toEthSignedMessageHash().recover(_sig), "Relayer did not sign the receipt."); // Look up if the relayer responded in the DataRegistry require(!checkDataRegistryRecord(relayTxId, _relayTx.deadline), "No compensation as relay transaction was completed in time."); compensationRecords[relayTxId].status = CompensationStatus.PENDING; compensationRecords[relayTxId].deadline = block.number + compensationPeriod; emit RequestCompensation(relayTxId, _relayTx.from, _relayTx.compensation, compensationRecords[relayTxId].deadline); } // @param _relayTxId Unique identification hash for relay tx // @param _deadline Expiry time from relay tx // @dev The DataRegistry records when the relay tx was submitted (block number). // So we only care about the earliest record in a shard. function checkDataRegistryRecord(bytes32 _relayTxId, uint _deadline) internal view returns (bool) { // Look through every shard (should only be two) uint shards = relay.getTotalShards(); for(uint i=0; i<shards; i++) { // Relay's DataRegistry only stores timestamp. uint response = relay.fetchRecord(i, _relayTxId); // It cannot be 0 as this implies no response at all! if(response > 0) { // We should find one response before the deadline if(_deadline >= response) { return true; } } } // No response. return false; } // @param _relayTx Relay tx has the compensation information. // @dev Relayer sends compensation to the user based on the compensation amount set in the relay tx. function issueCompensation(RelayTx memory _relayTx) public payable { bytes32 relayTxId = computeRelayTxId(_relayTx); require(compensationRecords[relayTxId].status == CompensationStatus.PENDING, "Compensation record must be in PENDING mode."); require(_relayTx.compensation == msg.value, "Relayer must compensate the exact value."); compensationRecords[relayTxId].status = CompensationStatus.COMPENSATED; emit CompensationIssued(relayTxId, msg.sender, _relayTx.from, msg.value); } // @param _relayTx Relay tx has the compensation information. // @dev User can withdraw the compensation after it was issued by the relayer (in issueCompensation()). function withdrawCompensation(RelayTx memory _relayTx) public { bytes32 relayTxId = computeRelayTxId(_relayTx); require(compensationRecords[relayTxId].status == CompensationStatus.COMPENSATED, "Compensation record must be in COMPENSATED mode."); compensationRecords[relayTxId].status = CompensationStatus.RESOLVED; uint toSend = _relayTx.compensation; _relayTx.from.transfer(toSend); } // @param _relayTx Relay tx to lock this adjudicator // Called by the user if their compensation is not issued in a timely manner. function lock(RelayTx memory _relayTx) public { bytes32 relayTxId = computeRelayTxId(_relayTx); require(compensationRecords[relayTxId].status == CompensationStatus.PENDING, "CompensationStatus must still be PENDING."); require(block.number > compensationRecords[relayTxId].deadline, "Deadline for compensation must have passed."); // damnation.1 locked = true; emit Locked(); } function getChainID() public pure returns(uint) { // Fetch chainId uint256 chainId; assembly {chainId := chainid() } return chainId; } }
_relayTxId Unique identification hash for relay tx _deadline Expiry time from relay tx The DataRegistry records when the relay tx was submitted (block number). So we only care about the earliest record in a shard. Look through every shard (should only be two) Relay's DataRegistry only stores timestamp. It cannot be 0 as this implies no response at all! We should find one response before the deadline
function checkDataRegistryRecord(bytes32 _relayTxId, uint _deadline) internal view returns (bool) { uint shards = relay.getTotalShards(); for(uint i=0; i<shards; i++) { uint response = relay.fetchRecord(i, _relayTxId); if(response > 0) { if(_deadline >= response) { return true; } } } }
12,959,619
./partial_match/1/0x9a50742da823F92575b30dBAE0FcAEF25aE0186f/sources/WithdrawalDelayer.sol
Getter of the current `_emergencyCouncil` return The `_emergencyCouncil` value/
function getEmergencyCouncil() external override view returns (address) { return _emergencyCouncil; }
4,251,239
/** *Submitted for verification at Etherscan.io on 2022-01-22 */ // hevm: flattened sources of src/FlapperMassBid.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.8.11 >=0.5.12; ////// lib/dss-interfaces/src/ERC/GemAbstract.sol /* pragma solidity >=0.5.12; */ // A base ERC-20 abstract class // https://eips.ethereum.org/EIPS/eip-20 interface GemAbstract { function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } ////// lib/dss-interfaces/src/dapp/DSAuthorityAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-auth interface DSAuthorityAbstract { function canCall(address, address, bytes4) external view returns (bool); } interface DSAuthAbstract { function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/dapp/DSChiefAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-chief interface DSChiefAbstract { function live() external view returns (uint256); function launch() external; function slates(bytes32) external view returns (address[] memory); function votes(address) external view returns (bytes32); function approvals(address) external view returns (uint256); function deposits(address) external view returns (address); function GOV() external view returns (address); function IOU() external view returns (address); function hat() external view returns (address); function MAX_YAYS() external view returns (uint256); function lock(uint256) external; function free(uint256) external; function etch(address[] calldata) external returns (bytes32); function vote(address[] calldata) external returns (bytes32); function vote(bytes32) external; function lift(address) external; function setOwner(address) external; function setAuthority(address) external; function isUserRoot(address) external view returns (bool); function setRootUser(address, bool) external; function _root_users(address) external view returns (bool); function _user_roles(address) external view returns (bytes32); function _capability_roles(address, bytes4) external view returns (bytes32); function _public_capabilities(address, bytes4) external view returns (bool); function getUserRoles(address) external view returns (bytes32); function getCapabilityRoles(address, bytes4) external view returns (bytes32); function isCapabilityPublic(address, bytes4) external view returns (bool); function hasUserRole(address, uint8) external view returns (bool); function canCall(address, address, bytes4) external view returns (bool); function setUserRole(address, uint8, bool) external; function setPublicCapability(address, bytes4, bool) external; function setRoleCapability(uint8, address, bytes4, bool) external; } interface DSChiefFabAbstract { function newChief(address, uint256) external returns (address); } ////// lib/dss-interfaces/src/dapp/DSPauseAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-pause interface DSPauseAbstract { function owner() external view returns (address); function authority() external view returns (address); function setOwner(address) external; function setAuthority(address) external; function setDelay(uint256) external; function plans(bytes32) external view returns (bool); function proxy() external view returns (address); function delay() external view returns (uint256); function plot(address, bytes32, bytes calldata, uint256) external; function drop(address, bytes32, bytes calldata, uint256) external; function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory); } ////// lib/dss-interfaces/src/dapp/DSPauseProxyAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-pause interface DSPauseProxyAbstract { function owner() external view returns (address); function exec(address, bytes calldata) external returns (bytes memory); } ////// lib/dss-interfaces/src/dapp/DSRolesAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-roles interface DSRolesAbstract { function _root_users(address) external view returns (bool); function _user_roles(address) external view returns (bytes32); function _capability_roles(address, bytes4) external view returns (bytes32); function _public_capabilities(address, bytes4) external view returns (bool); function getUserRoles(address) external view returns (bytes32); function getCapabilityRoles(address, bytes4) external view returns (bytes32); function isUserRoot(address) external view returns (bool); function isCapabilityPublic(address, bytes4) external view returns (bool); function hasUserRole(address, uint8) external view returns (bool); function canCall(address, address, bytes4) external view returns (bool); function setRootUser(address, bool) external; function setUserRole(address, uint8, bool) external; function setPublicCapability(address, bytes4, bool) external; function setRoleCapability(uint8, address, bytes4, bool) external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/dapp/DSRuneAbstract.sol // Copyright (C) 2020 Maker Foundation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-spellbook interface DSRuneAbstract { // @return [address] A contract address conforming to DSPauseAbstract function pause() external view returns (address); // @return [address] The address of the contract to be executed // TODO: is `action()` a required field? Not all spells rely on a seconary contract. function action() external view returns (address); // @return [bytes32] extcodehash of rune address function tag() external view returns (bytes32); // @return [bytes] The `abi.encodeWithSignature()` result of the function to be called. function sig() external view returns (bytes memory); // @return [uint256] Earliest time rune can execute function eta() external view returns (uint256); // The schedule() function plots the rune in the DSPause function schedule() external; // @return [bool] true if the rune has been cast() function done() external view returns (bool); // The cast() function executes the rune function cast() external; } ////// lib/dss-interfaces/src/dapp/DSSpellAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-spell interface DSSpellAbstract { function whom() external view returns (address); function mana() external view returns (uint256); function data() external view returns (bytes memory); function done() external view returns (bool); function cast() external; } ////// lib/dss-interfaces/src/dapp/DSThingAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-thing interface DSThingAbstract { function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/dapp/DSTokenAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-token/blob/master/src/token.sol interface DSTokenAbstract { function name() external view returns (bytes32); function symbol() external view returns (bytes32); function decimals() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function transfer(address, uint256) external returns (bool); function allowance(address, address) external view returns (uint256); function approve(address, uint256) external returns (bool); function approve(address) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function push(address, uint256) external; function pull(address, uint256) external; function move(address, address, uint256) external; function mint(uint256) external; function mint(address,uint) external; function burn(uint256) external; function burn(address,uint) external; function setName(bytes32) external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/dapp/DSValueAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/dapphub/ds-value/blob/master/src/value.sol interface DSValueAbstract { function has() external view returns (bool); function val() external view returns (bytes32); function peek() external view returns (bytes32, bool); function read() external view returns (bytes32); function poke(bytes32) external; function void() external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/dss/AuthGemJoinAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-deploy/blob/master/src/join.sol interface AuthGemJoinAbstract { function vat() external view returns (address); function ilk() external view returns (bytes32); function gem() external view returns (address); function dec() external view returns (uint256); function live() external view returns (uint256); function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function cage() external; function join(address, uint256) external; function exit(address, uint256) external; } ////// lib/dss-interfaces/src/dss/CatAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/cat.sol interface CatAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function box() external view returns (uint256); function litter() external view returns (uint256); function ilks(bytes32) external view returns (address, uint256, uint256); function live() external view returns (uint256); function vat() external view returns (address); function vow() external view returns (address); function file(bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, address) external; function bite(bytes32, address) external returns (uint256); function claw(uint256) external; function cage() external; } ////// lib/dss-interfaces/src/dss/ChainlogAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-chain-log interface ChainlogAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function keys() external view returns (bytes32[] memory); function version() external view returns (string memory); function ipfs() external view returns (string memory); function setVersion(string calldata) external; function setSha256sum(string calldata) external; function setIPFS(string calldata) external; function setAddress(bytes32,address) external; function removeAddress(bytes32) external; function count() external view returns (uint256); function get(uint256) external view returns (bytes32,address); function list() external view returns (bytes32[] memory); function getAddress(bytes32) external view returns (address); } // Helper function for returning address or abstract of Chainlog // Valid on Mainnet, Kovan, Rinkeby, Ropsten, and Goerli contract ChainlogHelper { address public constant ADDRESS = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F; ChainlogAbstract public constant ABSTRACT = ChainlogAbstract(ADDRESS); } ////// lib/dss-interfaces/src/dss/ClipAbstract.sol /// ClipAbstract.sol -- Clip Interface // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ interface ClipAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function ilk() external view returns (bytes32); function vat() external view returns (address); function dog() external view returns (address); function vow() external view returns (address); function spotter() external view returns (address); function calc() external view returns (address); function buf() external view returns (uint256); function tail() external view returns (uint256); function cusp() external view returns (uint256); function chip() external view returns (uint64); function tip() external view returns (uint192); function chost() external view returns (uint256); function kicks() external view returns (uint256); function active(uint256) external view returns (uint256); function sales(uint256) external view returns (uint256,uint256,uint256,address,uint96,uint256); function stopped() external view returns (uint256); function file(bytes32,uint256) external; function file(bytes32,address) external; function kick(uint256,uint256,address,address) external returns (uint256); function redo(uint256,address) external; function take(uint256,uint256,uint256,address,bytes calldata) external; function count() external view returns (uint256); function list() external view returns (uint256[] memory); function getStatus(uint256) external view returns (bool,uint256,uint256,uint256); function upchost() external; function yank(uint256) external; } ////// lib/dss-interfaces/src/dss/ClipperMomAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/Clipper-mom/blob/master/src/ClipperMom.sol interface ClipperMomAbstract { function owner() external view returns (address); function authority() external view returns (address); function locked(address) external view returns (uint256); function tolerance(address) external view returns (uint256); function spotter() external view returns (address); function setOwner(address) external; function setAuthority(address) external; function setPriceTolerance(address, uint256) external; function setBreaker(address, uint256, uint256) external; function tripBreaker(address) external; } ////// lib/dss-interfaces/src/dss/DaiAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/dai.sol interface DaiAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); function nonces(address) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external view returns (bytes32); function transfer(address, uint256) external; function transferFrom(address, address, uint256) external returns (bool); function mint(address, uint256) external; function burn(address, uint256) external; function approve(address, uint256) external returns (bool); function push(address, uint256) external; function pull(address, uint256) external; function move(address, address, uint256) external; function permit(address, address, uint256, uint256, bool, uint8, bytes32, bytes32) external; } ////// lib/dss-interfaces/src/dss/DaiJoinAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/join.sol interface DaiJoinAbstract { function wards(address) external view returns (uint256); function rely(address usr) external; function deny(address usr) external; function vat() external view returns (address); function dai() external view returns (address); function live() external view returns (uint256); function cage() external; function join(address, uint256) external; function exit(address, uint256) external; } ////// lib/dss-interfaces/src/dss/DogAbstract.sol /// DogAbstract.sol -- Dog Interface // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ interface DogAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function ilks(bytes32) external view returns (address,uint256,uint256,uint256); function vow() external view returns (address); function live() external view returns (uint256); function Hole() external view returns (uint256); function Dirt() external view returns (uint256); function file(bytes32,address) external; function file(bytes32,uint256) external; function file(bytes32,bytes32,uint256) external; function file(bytes32,bytes32,address) external; function chop(bytes32) external view returns (uint256); function bark(bytes32,address,address) external returns (uint256); function digs(bytes32,uint256) external; function cage() external; } ////// lib/dss-interfaces/src/dss/DssAutoLineAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-auto-line/blob/master/src/DssAutoLine.sol interface DssAutoLineAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48); function setIlk(bytes32,uint256,uint256,uint256) external; function remIlk(bytes32) external; function exec(bytes32) external returns (uint256); } ////// lib/dss-interfaces/src/dss/DssCdpManager.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-cdp-manager/ interface DssCdpManagerAbstract { function vat() external view returns (address); function cdpi() external view returns (uint256); function urns(uint256) external view returns (address); function list(uint256) external view returns (uint256,uint256); function owns(uint256) external view returns (address); function ilks(uint256) external view returns (bytes32); function first(address) external view returns (uint256); function last(address) external view returns (uint256); function count(address) external view returns (uint256); function cdpCan(address, uint256, address) external returns (uint256); function urnCan(address, address) external returns (uint256); function cdpAllow(uint256, address, uint256) external; function urnAllow(address, uint256) external; function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function frob(uint256, int256, int256) external; function flux(uint256, address, uint256) external; function flux(bytes32, uint256, address, uint256) external; function move(uint256, address, uint256) external; function quit(uint256, address) external; function enter(address, uint256) external; function shift(uint256, uint256) external; } ////// lib/dss-interfaces/src/dss/ESMAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/esm/blob/master/src/ESM.sol interface ESMAbstract { function gem() external view returns (address); function end() external view returns (address); function proxy() external view returns (address); function min() external view returns (uint256); function sum(address) external view returns (address); function Sum() external view returns (uint256); function revokesGovernanceAccess() external view returns (bool); function fire() external; function deny(address) external; function join(uint256) external; function burn() external; } ////// lib/dss-interfaces/src/dss/ETHJoinAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/join.sol interface ETHJoinAbstract { function wards(address) external view returns (uint256); function rely(address usr) external; function deny(address usr) external; function vat() external view returns (address); function ilk() external view returns (bytes32); function live() external view returns (uint256); function cage() external; function join(address) external payable; function exit(address, uint256) external; } ////// lib/dss-interfaces/src/dss/EndAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/end.sol interface EndAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function cat() external view returns (address); function dog() external view returns (address); function vow() external view returns (address); function pot() external view returns (address); function spot() external view returns (address); function live() external view returns (uint256); function when() external view returns (uint256); function wait() external view returns (uint256); function debt() external view returns (uint256); function tag(bytes32) external view returns (uint256); function gap(bytes32) external view returns (uint256); function Art(bytes32) external view returns (uint256); function fix(bytes32) external view returns (uint256); function bag(address) external view returns (uint256); function out(bytes32, address) external view returns (uint256); function WAD() external view returns (uint256); function RAY() external view returns (uint256); function file(bytes32, address) external; function file(bytes32, uint256) external; function cage() external; function cage(bytes32) external; function skip(bytes32, uint256) external; function snip(bytes32, uint256) external; function skim(bytes32, address) external; function free(bytes32) external; function thaw() external; function flow(bytes32) external; function pack(uint256) external; function cash(bytes32, uint256) external; } ////// lib/dss-interfaces/src/dss/ExponentialDecreaseAbstract.sol /// ExponentialDecreaseAbstract.sol -- Exponential Decrease Interface // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ interface ExponentialDecreaseAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function cut() external view returns (uint256); function file(bytes32,uint256) external; function price(uint256,uint256) external view returns (uint256); } ////// lib/dss-interfaces/src/dss/FaucetAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/token-faucet/blob/master/src/RestrictedTokenFaucet.sol interface FaucetAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function list(address) external view returns (uint256); function hope(address) external; function nope(address) external; function amt(address) external view returns (uint256); function done(address, address) external view returns (bool); function gulp(address) external; function gulp(address, address[] calldata) external; function shut(address) external; function undo(address, address) external; function setAmt(address, uint256) external; } ////// lib/dss-interfaces/src/dss/FlapAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/flap.sol interface FlapAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function bids(uint256) external view returns (uint256, uint256, address, uint48, uint48); function vat() external view returns (address); function gem() external view returns (address); function beg() external view returns (uint256); function ttl() external view returns (uint48); function tau() external view returns (uint48); function kicks() external view returns (uint256); function live() external view returns (uint256); function file(bytes32, uint256) external; function kick(uint256, uint256) external returns (uint256); function tick(uint256) external; function tend(uint256, uint256, uint256) external; function deal(uint256) external; function cage(uint256) external; function yank(uint256) external; } ////// lib/dss-interfaces/src/dss/FlashAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-flash/blob/master/src/flash.sol interface FlashAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function daiJoin() external view returns (address); function dai() external view returns (address); function vow() external view returns (address); function max() external view returns (uint256); function toll() external view returns (uint256); function CALLBACK_SUCCESS() external view returns (bytes32); function CALLBACK_SUCCESS_VAT_DAI() external view returns (bytes32); function file(bytes32, uint256) external; function maxFlashLoan(address) external view returns (uint256); function flashFee(address, uint256) external view returns (uint256); function flashLoan(address, address, uint256, bytes calldata) external returns (bool); function vatDaiFlashLoan(address, uint256, bytes calldata) external returns (bool); function convert() external; function accrue() external; } ////// lib/dss-interfaces/src/dss/FlipAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/flip.sol interface FlipAbstract { function wards(address) external view returns (uint256); function rely(address usr) external; function deny(address usr) external; function bids(uint256) external view returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function vat() external view returns (address); function cat() external view returns (address); function ilk() external view returns (bytes32); function beg() external view returns (uint256); function ttl() external view returns (uint48); function tau() external view returns (uint48); function kicks() external view returns (uint256); function file(bytes32, uint256) external; function kick(address, address, uint256, uint256, uint256) external returns (uint256); function tick(uint256) external; function tend(uint256, uint256, uint256) external; function dent(uint256, uint256, uint256) external; function deal(uint256) external; function yank(uint256) external; } ////// lib/dss-interfaces/src/dss/FlipperMomAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/flipper-mom/blob/master/src/FlipperMom.sol interface FlipperMomAbstract { function owner() external view returns (address); function authority() external view returns (address); function setOwner(address) external; function setAuthority(address) external; function cat() external returns (address); function rely(address) external; function deny(address) external; } ////// lib/dss-interfaces/src/dss/FlopAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/flop.sol interface FlopAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function bids(uint256) external view returns (uint256, uint256, address, uint48, uint48); function vat() external view returns (address); function gem() external view returns (address); function beg() external view returns (uint256); function pad() external view returns (uint256); function ttl() external view returns (uint48); function tau() external view returns (uint48); function kicks() external view returns (uint256); function live() external view returns (uint256); function vow() external view returns (address); function file(bytes32, uint256) external; function kick(address, uint256, uint256) external returns (uint256); function tick(uint256) external; function dent(uint256, uint256, uint256) external; function deal(uint256) external; function cage() external; function yank(uint256) external; } ////// lib/dss-interfaces/src/dss/GemJoinAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/join.sol interface GemJoinAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function ilk() external view returns (bytes32); function gem() external view returns (address); function dec() external view returns (uint256); function live() external view returns (uint256); function cage() external; function join(address, uint256) external; function exit(address, uint256) external; } ////// lib/dss-interfaces/src/dss/GemJoinImplementationAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-deploy/blob/master/src/join.sol interface GemJoinImplementationAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function ilk() external view returns (bytes32); function gem() external view returns (address); function dec() external view returns (uint256); function live() external view returns (uint256); function cage() external; function join(address, uint256) external; function exit(address, uint256) external; function setImplementation(address, uint256) external; } ////// lib/dss-interfaces/src/dss/GemJoinManagedAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-gem-joins/blob/master/src/join-managed.sol interface GemJoinManagedAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function ilk() external view returns (bytes32); function gem() external view returns (address); function dec() external view returns (uint256); function live() external view returns (uint256); function cage() external; function join(address, uint256) external; function exit(address, address, uint256) external; } ////// lib/dss-interfaces/src/dss/GetCdpsAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-cdp-manager/blob/master/src/GetCdps.sol interface GetCdpsAbstract { function getCdpsAsc(address, address) external view returns (uint256[] memory, address[] memory, bytes32[] memory); function getCdpsDesc(address, address) external view returns (uint256[] memory, address[] memory, bytes32[] memory); } ////// lib/dss-interfaces/src/dss/IlkRegistryAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/ilk-registry interface IlkRegistryAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function dog() external view returns (address); function cat() external view returns (address); function spot() external view returns (address); function ilkData(bytes32) external view returns ( uint96, address, address, uint8, uint96, address, address, string memory, string memory ); function ilks() external view returns (bytes32[] memory); function ilks(uint) external view returns (bytes32); function add(address) external; function remove(bytes32) external; function update(bytes32) external; function removeAuth(bytes32) external; function file(bytes32, address) external; function file(bytes32, bytes32, address) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, string calldata) external; function count() external view returns (uint256); function list() external view returns (bytes32[] memory); function list(uint256, uint256) external view returns (bytes32[] memory); function get(uint256) external view returns (bytes32); function info(bytes32) external view returns ( string memory, string memory, uint256, uint256, address, address, address, address ); function pos(bytes32) external view returns (uint256); function class(bytes32) external view returns (uint256); function gem(bytes32) external view returns (address); function pip(bytes32) external view returns (address); function join(bytes32) external view returns (address); function xlip(bytes32) external view returns (address); function dec(bytes32) external view returns (uint256); function symbol(bytes32) external view returns (string memory); function name(bytes32) external view returns (string memory); function put(bytes32, address, address, uint256, uint256, address, address, string calldata, string calldata) external; } ////// lib/dss-interfaces/src/dss/JugAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/jug.sol interface JugAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function ilks(bytes32) external view returns (uint256, uint256); function vat() external view returns (address); function vow() external view returns (address); function base() external view returns (address); function init(bytes32) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, uint256) external; function file(bytes32, address) external; function drip(bytes32) external returns (uint256); } ////// lib/dss-interfaces/src/dss/LPOsmAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/univ2-lp-oracle interface LPOsmAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function stopped() external view returns (uint256); function bud(address) external view returns (uint256); function dec0() external view returns (uint8); function dec1() external view returns (uint8); function orb0() external view returns (address); function orb1() external view returns (address); function wat() external view returns (bytes32); function hop() external view returns (uint32); function src() external view returns (address); function zzz() external view returns (uint64); function change(address) external; function step(uint256) external; function stop() external; function start() external; function pass() external view returns (bool); function poke() external; function peek() external view returns (bytes32, bool); function peep() external view returns (bytes32, bool); function read() external view returns (bytes32); function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; function link(uint256, address) external; } ////// lib/dss-interfaces/src/dss/LerpAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-lerp/blob/master/src/Lerp.sol interface LerpAbstract { function target() external view returns (address); function what() external view returns (bytes32); function start() external view returns (uint256); function end() external view returns (uint256); function duration() external view returns (uint256); function done() external view returns (bool); function startTime() external view returns (uint256); function tick() external returns (uint256); function ilk() external view returns (bytes32); } ////// lib/dss-interfaces/src/dss/LerpFactoryAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-lerp/blob/master/src/LerpFactory.sol interface LerpFactoryAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function lerps(bytes32) external view returns (address); function active(uint256) external view returns (address); function newLerp(bytes32, address, bytes32, uint256, uint256, uint256, uint256) external returns (address); function newIlkLerp(bytes32, address, bytes32, bytes32, uint256, uint256, uint256, uint256) external returns (address); function tall() external; function count() external view returns (uint256); function list() external view returns (address[] memory); } ////// lib/dss-interfaces/src/dss/LinearDecreaseAbstract.sol /// LinearDecreaseAbstract.sol -- Linear Decrease Interface // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ interface LinearDecreaseAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function tau() external view returns (uint256); function file(bytes32,uint256) external; function price(uint256,uint256) external view returns (uint256); } ////// lib/dss-interfaces/src/dss/MedianAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/median interface MedianAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function age() external view returns (uint32); function wat() external view returns (bytes32); function bar() external view returns (uint256); function orcl(address) external view returns (uint256); function bud(address) external view returns (uint256); function slot(uint8) external view returns (address); function read() external view returns (uint256); function peek() external view returns (uint256, bool); function lift(address[] calldata) external; function drop(address[] calldata) external; function setBar(uint256) external; function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; function poke(uint256[] calldata, uint256[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata) external; } ////// lib/dss-interfaces/src/dss/MkrAuthorityAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/mkr-authority/blob/master/src/MkrAuthority.sol interface MkrAuthorityAbstract { function root() external returns (address); function setRoot(address) external; function wards(address) external returns (uint256); function rely(address) external; function deny(address) external; function canCall(address, address, bytes4) external returns (bool); } ////// lib/dss-interfaces/src/dss/OsmAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/osm interface OsmAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function stopped() external view returns (uint256); function src() external view returns (address); function hop() external view returns (uint16); function zzz() external view returns (uint64); function bud(address) external view returns (uint256); function stop() external; function start() external; function change(address) external; function step(uint16) external; function void() external; function pass() external view returns (bool); function poke() external; function peek() external view returns (bytes32, bool); function peep() external view returns (bytes32, bool); function read() external view returns (bytes32); function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; } ////// lib/dss-interfaces/src/dss/OsmMomAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/osm-mom interface OsmMomAbstract { function owner() external view returns (address); function authority() external view returns (address); function osms(bytes32) external view returns (address); function setOsm(bytes32, address) external; function setOwner(address) external; function setAuthority(address) external; function stop(bytes32) external; } ////// lib/dss-interfaces/src/dss/PotAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/pot.sol interface PotAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function pie(address) external view returns (uint256); function Pie() external view returns (uint256); function dsr() external view returns (uint256); function chi() external view returns (uint256); function vat() external view returns (address); function vow() external view returns (address); function rho() external view returns (uint256); function live() external view returns (uint256); function file(bytes32, uint256) external; function file(bytes32, address) external; function cage() external; function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } ////// lib/dss-interfaces/src/dss/PotHelper.sol /* pragma solidity >=0.5.12; */ /* import { PotAbstract } from "./PotAbstract.sol"; */ // https://github.com/makerdao/dss/blob/master/src/pot.sol contract PotHelper { PotAbstract pa; constructor(address _pot) public { pa = PotAbstract(_pot); } // https://github.com/makerdao/dss/blob/master/src/pot.sol#L79 uint256 constant ONE = 10 ** 27; function _mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function _rmul(uint x, uint y) internal pure returns (uint z) { z = _mul(x, y) / ONE; } function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } // View function for calculating value of chi iff drip() is called in the same block. function drop() external view returns (uint256) { if (block.timestamp == pa.rho()) return pa.chi(); return _rmul(rpow(pa.dsr(), block.timestamp - pa.rho(), ONE), pa.chi()); } // Pass the Pot Abstract for additional operations function pot() external view returns (PotAbstract) { return pa; } } ////// lib/dss-interfaces/src/dss/PsmAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-psm/blob/master/src/psm.sol interface PsmAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function gemJoin() external view returns (address); function dai() external view returns (address); function daiJoin() external view returns (address); function ilk() external view returns (bytes32); function vow() external view returns (address); function tin() external view returns (uint256); function tout() external view returns (uint256); function file(bytes32 what, uint256 data) external; function hope(address) external; function nope(address) external; function sellGem(address usr, uint256 gemAmt) external; function buyGem(address usr, uint256 gemAmt) external; } ////// lib/dss-interfaces/src/dss/SpotAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/spot.sol interface SpotAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function ilks(bytes32) external view returns (address, uint256); function vat() external view returns (address); function par() external view returns (uint256); function live() external view returns (uint256); function file(bytes32, bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function poke(bytes32) external; function cage() external; } ////// lib/dss-interfaces/src/dss/StairstepExponentialDecreaseAbstract.sol /// StairstepExponentialDecreaseAbstract.sol -- StairstepExponentialDecrease Interface // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ interface StairstepExponentialDecreaseAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function step() external view returns (uint256); function cut() external view returns (uint256); function file(bytes32,uint256) external; function price(uint256,uint256) external view returns (uint256); } ////// lib/dss-interfaces/src/dss/VatAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/vat.sol interface VatAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function can(address, address) external view returns (uint256); function hope(address) external; function nope(address) external; function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function urns(bytes32, address) external view returns (uint256, uint256); function gem(bytes32, address) external view returns (uint256); function dai(address) external view returns (uint256); function sin(address) external view returns (uint256); function debt() external view returns (uint256); function vice() external view returns (uint256); function Line() external view returns (uint256); function live() external view returns (uint256); function init(bytes32) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function cage() external; function slip(bytes32, address, int256) external; function flux(bytes32, address, address, uint256) external; function move(address, address, uint256) external; function frob(bytes32, address, address, address, int256, int256) external; function fork(bytes32, address, address, int256, int256) external; function grab(bytes32, address, address, address, int256, int256) external; function heal(uint256) external; function suck(address, address, uint256) external; function fold(bytes32, address, int256) external; } ////// lib/dss-interfaces/src/dss/VestAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-vest/blob/master/src/DssVest.sol interface VestAbstract { function TWENTY_YEARS() external view returns (uint256); function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function awards(uint256) external view returns (address, uint48, uint48, uint48, address, uint8, uint128, uint128); function ids() external view returns (uint256); function cap() external view returns (uint256); function usr(uint256) external view returns (address); function bgn(uint256) external view returns (uint256); function clf(uint256) external view returns (uint256); function fin(uint256) external view returns (uint256); function mgr(uint256) external view returns (address); function res(uint256) external view returns (uint256); function tot(uint256) external view returns (uint256); function rxd(uint256) external view returns (uint256); function file(bytes32, uint256) external; function create(address, uint256, uint256, uint256, uint256, address) external returns (uint256); function vest(uint256) external; function vest(uint256, uint256) external; function accrued(uint256) external view returns (uint256); function unpaid(uint256) external view returns (uint256); function restrict(uint256) external; function unrestrict(uint256) external; function yank(uint256) external; function yank(uint256, uint256) external; function move(uint256, address) external; function valid(uint256) external view returns (bool); } ////// lib/dss-interfaces/src/dss/VowAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/vow.sol interface VowAbstract { function wards(address) external view returns (uint256); function rely(address usr) external; function deny(address usr) external; function vat() external view returns (address); function flapper() external view returns (address); function flopper() external view returns (address); function sin(uint256) external view returns (uint256); function Sin() external view returns (uint256); function Ash() external view returns (uint256); function wait() external view returns (uint256); function dump() external view returns (uint256); function sump() external view returns (uint256); function bump() external view returns (uint256); function hump() external view returns (uint256); function live() external view returns (uint256); function file(bytes32, uint256) external; function file(bytes32, address) external; function fess(uint256) external; function flog(uint256) external; function heal(uint256) external; function kiss(uint256) external; function flop() external returns (uint256); function flap() external returns (uint256); function cage() external; } ////// lib/dss-interfaces/src/sai/GemPitAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/sai/blob/master/src/pit.sol interface GemPitAbstract { function burn(address) external; } ////// lib/dss-interfaces/src/sai/SaiMomAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/sai/blob/master/src/mom.sol interface SaiMomAbstract { function tub() external view returns (address); function tap() external view returns (address); function vox() external view returns (address); function setCap(uint256) external; function setMat(uint256) external; function setTax(uint256) external; function setFee(uint256) external; function setAxe(uint256) external; function setTubGap(uint256) external; function setPip(address) external; function setPep(address) external; function setVox(address) external; function setTapGap(uint256) external; function setWay(uint256) external; function setHow(uint256) external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/sai/SaiTapAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/sai/blob/master/src/tap.sol interface SaiTapAbstract { function sai() external view returns (address); function sin() external view returns (address); function skr() external view returns (address); function vox() external view returns (address); function tub() external view returns (address); function gap() external view returns (uint256); function off() external view returns (bool); function fix() external view returns (uint256); function joy() external view returns (uint256); function woe() external view returns (uint256); function fog() external view returns (uint256); function mold(bytes32, uint256) external; function heal() external; function s2s() external returns (uint256); function bid(uint256) external returns (uint256); function ask(uint256) external returns (uint256); function bust(uint256) external; function boom(uint256) external; function cage(uint256) external; function cash(uint256) external; function mock(uint256) external; function vent() external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/sai/SaiTopAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/sai/blob/master/src/top.sol interface SaiTopAbstract { function vox() external view returns (address); function tub() external view returns (address); function tap() external view returns (address); function sai() external view returns (address); function sin() external view returns (address); function skr() external view returns (address); function gem() external view returns (address); function fix() external view returns (uint256); function fit() external view returns (uint256); function caged() external view returns (uint256); function cooldown() external view returns (uint256); function era() external view returns (uint256); function cage() external; function flow() external; function setCooldown(uint256) external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/sai/SaiTubAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/sai/blob/master/src/tub.sol interface SaiTubAbstract { function sai() external view returns (address); function sin() external view returns (address); function skr() external view returns (address); function gem() external view returns (address); function gov() external view returns (address); function vox() external view returns (address); function pip() external view returns (address); function pep() external view returns (address); function tap() external view returns (address); function pit() external view returns (address); function axe() external view returns (uint256); function cap() external view returns (uint256); function mat() external view returns (uint256); function tax() external view returns (uint256); function fee() external view returns (uint256); function gap() external view returns (uint256); function off() external view returns (bool); function out() external view returns (bool); function fit() external view returns (uint256); function rho() external view returns (uint256); function rum() external view returns (uint256); function cupi() external view returns (uint256); function cups(bytes32) external view returns (address, uint256, uint256, uint256); function lad(bytes32) external view returns (address); function ink(bytes32) external view returns (address); function tab(bytes32) external view returns (uint256); function rap(bytes32) external returns (uint256); function din() external returns (uint256); function air() external view returns (uint256); function pie() external view returns (uint256); function era() external view returns (uint256); function mold(bytes32, uint256) external; function setPip(address) external; function setPep(address) external; function setVox(address) external; function turn(address) external; function per() external view returns (uint256); function ask(uint256) external view returns (uint256); function bid(uint256) external view returns (uint256); function join(uint256) external; function exit(uint256) external; function chi() external returns (uint256); function rhi() external returns (uint256); function drip() external; function tag() external view returns (uint256); function safe(bytes32) external returns (bool); function open() external returns (bytes32); function give(bytes32, address) external; function lock(bytes32, uint256) external; function free(bytes32, uint256) external; function draw(bytes32, uint256) external; function wipe(bytes32, uint256) external; function shut(bytes32) external; function bite(bytes32) external; function cage(uint256, uint256) external; function flow() external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/sai/SaiVoxAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/sai/blob/master/src/vox.sol interface SaiVoxAbstract { function fix() external view returns (uint256); function how() external view returns (uint256); function tau() external view returns (uint256); function era() external view returns (uint256); function mold(bytes32, uint256) external; function par() external returns (uint256); function way() external returns (uint256); function tell(uint256) external; function tune(uint256) external; function prod() external; function authority() external view returns (address); function owner() external view returns (address); function setOwner(address) external; function setAuthority(address) external; } ////// lib/dss-interfaces/src/utils/WardsAbstract.sol /* pragma solidity >=0.5.12; */ interface WardsAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; } ////// lib/dss-interfaces/src/Interfaces.sol /* pragma solidity >=0.5.12; */ /* import { GemAbstract } from "./ERC/GemAbstract.sol"; */ /* import { DSAuthorityAbstract, DSAuthAbstract } from "./dapp/DSAuthorityAbstract.sol"; */ /* import { DSChiefAbstract } from "./dapp/DSChiefAbstract.sol"; */ /* import { DSPauseAbstract } from "./dapp/DSPauseAbstract.sol"; */ /* import { DSPauseProxyAbstract } from "./dapp/DSPauseProxyAbstract.sol"; */ /* import { DSRolesAbstract } from "./dapp/DSRolesAbstract.sol"; */ /* import { DSSpellAbstract } from "./dapp/DSSpellAbstract.sol"; */ /* import { DSRuneAbstract } from "./dapp/DSRuneAbstract.sol"; */ /* import { DSThingAbstract } from "./dapp/DSThingAbstract.sol"; */ /* import { DSTokenAbstract } from "./dapp/DSTokenAbstract.sol"; */ /* import { DSValueAbstract } from "./dapp/DSValueAbstract.sol"; */ /* import { AuthGemJoinAbstract } from "./dss/AuthGemJoinAbstract.sol"; */ /* import { CatAbstract } from "./dss/CatAbstract.sol"; */ /* import { ChainlogAbstract } from "./dss/ChainlogAbstract.sol"; */ /* import { ChainlogHelper } from "./dss/ChainlogAbstract.sol"; */ /* import { ClipAbstract } from "./dss/ClipAbstract.sol"; */ /* import { ClipperMomAbstract } from "./dss/ClipperMomAbstract.sol"; */ /* import { DaiAbstract } from "./dss/DaiAbstract.sol"; */ /* import { DaiJoinAbstract } from "./dss/DaiJoinAbstract.sol"; */ /* import { DogAbstract } from "./dss/DogAbstract.sol"; */ /* import { DssAutoLineAbstract } from "./dss/DssAutoLineAbstract.sol"; */ /* import { DssCdpManagerAbstract } from "./dss/DssCdpManager.sol"; */ /* import { EndAbstract } from "./dss/EndAbstract.sol"; */ /* import { ESMAbstract } from "./dss/ESMAbstract.sol"; */ /* import { ETHJoinAbstract } from "./dss/ETHJoinAbstract.sol"; */ /* import { ExponentialDecreaseAbstract } from "./dss/ExponentialDecreaseAbstract.sol"; */ /* import { FaucetAbstract } from "./dss/FaucetAbstract.sol"; */ /* import { FlapAbstract } from "./dss/FlapAbstract.sol"; */ /* import { FlashAbstract } from "./dss/FlashAbstract.sol"; */ /* import { FlipAbstract } from "./dss/FlipAbstract.sol"; */ /* import { FlipperMomAbstract } from "./dss/FlipperMomAbstract.sol"; */ /* import { FlopAbstract } from "./dss/FlopAbstract.sol"; */ /* import { GemJoinAbstract } from "./dss/GemJoinAbstract.sol"; */ /* import { GemJoinImplementationAbstract } from "./dss/GemJoinImplementationAbstract.sol"; */ /* import { GemJoinManagedAbstract } from "./dss/GemJoinManagedAbstract.sol"; */ /* import { GetCdpsAbstract } from "./dss/GetCdpsAbstract.sol"; */ /* import { IlkRegistryAbstract } from "./dss/IlkRegistryAbstract.sol"; */ /* import { JugAbstract } from "./dss/JugAbstract.sol"; */ /* import { LerpAbstract } from "./dss/LerpAbstract.sol"; */ /* import { LerpFactoryAbstract } from "./dss/LerpFactoryAbstract.sol"; */ /* import { LinearDecreaseAbstract } from "./dss/LinearDecreaseAbstract.sol"; */ /* import { LPOsmAbstract } from "./dss/LPOsmAbstract.sol"; */ /* import { MkrAuthorityAbstract } from "./dss/MkrAuthorityAbstract.sol"; */ /* import { MedianAbstract } from "./dss/MedianAbstract.sol"; */ /* import { OsmAbstract } from "./dss/OsmAbstract.sol"; */ /* import { OsmMomAbstract } from "./dss/OsmMomAbstract.sol"; */ /* import { PotAbstract } from "./dss/PotAbstract.sol"; */ /* import { PotHelper } from "./dss/PotHelper.sol"; */ /* import { PsmAbstract } from "./dss/PsmAbstract.sol"; */ /* import { SpotAbstract } from "./dss/SpotAbstract.sol"; */ /* import { StairstepExponentialDecreaseAbstract } from "./dss/StairstepExponentialDecreaseAbstract.sol"; */ /* import { VatAbstract } from "./dss/VatAbstract.sol"; */ /* import { VestAbstract } from "./dss/VestAbstract.sol"; */ /* import { VowAbstract } from "./dss/VowAbstract.sol"; */ /* import { GemPitAbstract } from "./sai/GemPitAbstract.sol"; */ /* import { SaiMomAbstract } from "./sai/SaiMomAbstract.sol"; */ /* import { SaiTapAbstract } from "./sai/SaiTapAbstract.sol"; */ /* import { SaiTopAbstract } from "./sai/SaiTopAbstract.sol"; */ /* import { SaiTubAbstract } from "./sai/SaiTubAbstract.sol"; */ /* import { SaiVoxAbstract } from "./sai/SaiVoxAbstract.sol"; */ // Partial DSS Abstracts /* import { WardsAbstract } from "./utils/WardsAbstract.sol"; */ ////// src/FlapperMassBid.sol // Copyright (C) 2021 Sam MacPherson (hexonaut) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity 0.8.11; */ /* import { VowAbstract, FlapAbstract, DSTokenAbstract, DaiJoinAbstract, DaiAbstract, VatAbstract } from "dss-interfaces/Interfaces.sol"; */ contract FlapperMassBid { struct AuctionCandidate { uint256 index; uint256 auction; uint256 bid; } uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; address public immutable owner; VowAbstract public immutable vow; FlapAbstract public immutable flap; DaiJoinAbstract public immutable daiJoin; DaiAbstract public immutable dai; VatAbstract public immutable vat; DSTokenAbstract public immutable mkr; constructor(address _owner, address _vow, address _daiJoin) { owner = _owner; vow = VowAbstract(_vow); flap = FlapAbstract(vow.flapper()); daiJoin = DaiJoinAbstract(_daiJoin); dai = DaiAbstract(daiJoin.dai()); vat = VatAbstract(daiJoin.vat()); mkr = DSTokenAbstract(flap.gem()); // Setup permissions mkr.approve(address(flap), type(uint256).max); vat.hope(address(daiJoin)); } function findAuctions( uint256 startAuctionIndex, uint256 endAuctionIndex, uint256 maxAuctionsToBid, uint256 mkrBidInWads ) external view returns (uint256 numAuctions, bytes memory data) { require(endAuctionIndex >= startAuctionIndex, "start-must-be-before-end"); require(maxAuctionsToBid > 0, "at-least-one-auction"); require(mkrBidInWads > 0, "need-to-bid-something"); require(mkr.balanceOf(owner) >= mkrBidInWads * maxAuctionsToBid, "not-enough-mkr-in-your-wallet"); require(mkr.allowance(owner, address(this)) >= mkrBidInWads * maxAuctionsToBid, "not-enough-mkr-allowance"); uint256 beg = flap.beg(); uint256 i; AuctionCandidate[] memory candidates = new AuctionCandidate[](maxAuctionsToBid); for (i = startAuctionIndex; i <= endAuctionIndex; i++) { (uint256 bid,, address guy, uint48 tic, uint48 end) = flap.bids(i); if (guy == address(0)) continue; // Auction doesn't exist if (tic <= block.timestamp && tic != 0) continue; // Auction finished if (end <= block.timestamp) continue; // Auction end if (mkrBidInWads <= bid) continue; // Bid not high enough if (mkrBidInWads * WAD < beg * bid) continue; // Bid increase is not above beg if (numAuctions < maxAuctionsToBid) { // Always append if not full candidates[numAuctions] = AuctionCandidate(numAuctions, i, bid); numAuctions++; } else { // Potentially add to candidates if it's smaller amount // First find the largest candidate to replace AuctionCandidate memory largestBidCandidate; for (uint256 o = 0; o < maxAuctionsToBid; o++) { AuctionCandidate memory candidate = candidates[o]; if (candidate.bid > largestBidCandidate.bid) { largestBidCandidate = candidate; } } // Replace it if the current bid is smaller if (bid < largestBidCandidate.bid) { candidates[largestBidCandidate.index] = AuctionCandidate(largestBidCandidate.index, i, bid); } } } uint256[] memory auctions = new uint256[](numAuctions); for (i = 0; i < numAuctions; i++) { auctions[i] = candidates[i].auction; } data = abi.encode(mkrBidInWads, auctions); // Encode for easier copy+paste } function execute (bytes calldata data) external { require(msg.sender == owner, "only-owner"); (uint256 bid, uint256[] memory auctions) = abi.decode(data, (uint256, uint256[])); uint256 lot = vow.bump(); // At most you will need bid * numAuctions MKR mkr.transferFrom(owner, address(this), bid * auctions.length); for (uint256 i = 0; i < auctions.length; i++) { try flap.tend(auctions[i], lot, bid) {} catch { // Carry on if one of the bids fails } } // Transfer any remaining MKR back out mkr.transfer(owner, mkr.balanceOf(address(this))); } function extractVatDAI() external { require(msg.sender == owner, "only-owner"); // Pull DAI out of vat (if any) daiJoin.exit(owner, vat.dai(address(this)) / RAY); } function extractMKR() external { require(msg.sender == owner, "only-owner"); // Pull MKR out of here (it will show up if outbid) mkr.transfer(owner, mkr.balanceOf(address(this))); } // This should never have DAI in it, but let's just be safe function extractDAI() external { require(msg.sender == owner, "only-owner"); // Pull MKR out of here (it will show up if outbid) dai.transfer(owner, dai.balanceOf(address(this))); } } contract FlapperMassBidFactory { address public immutable vow; address public immutable daiJoin; constructor(address _vow, address _daiJoin) { vow = _vow; daiJoin = _daiJoin; } function create() external returns (FlapperMassBid) { return new FlapperMassBid(msg.sender, vow, daiJoin); } }
https:github.com/makerdao/Clipper-mom/blob/master/src/ClipperMom.sol
interface ClipperMomAbstract { function owner() external view returns (address); function authority() external view returns (address); function locked(address) external view returns (uint256); function tolerance(address) external view returns (uint256); function spotter() external view returns (address); function setOwner(address) external; function setAuthority(address) external; function setPriceTolerance(address, uint256) external; function setBreaker(address, uint256, uint256) external; function tripBreaker(address) external; }
2,203,232
./full_match/43113/0xc932aad437d8bD945Ed016B70EF406Aae8FbDba9/sources/project_/contracts/fractions/DelnorteFractionalizer.sol
Function allows withdrawing ETH from the smart contract [for the owner only]/
function withdrawAll() external onlyOwner { uint amount = address(this).balance; payable(msg.sender).transfer(amount); emit Events.WithdrawExecuted(msg.sender, amount); }
13,177,722