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.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "IERC20.sol"; import "SafeMath.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev 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; } } // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @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; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Context} from "Context.sol"; import {Initializable} from "Initializable.sol"; /** * @title UpgradeableClaimable * @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. Since * this contract combines Claimable and UpgradableOwnable contracts, ownership * can be later change via 2 step method {transferOwnership} and {claimOwnership} * * 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 UpgradeableClaimable is Initializable, Context { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting a custom initial owner of choice. * @param __owner Initial owner of contract to be set. */ function initialize(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view 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 Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface ITrueDistributor { function trustToken() external view returns (IERC20); function farm() external view returns (address); function distribute() external; function nextDistribution() external view returns (uint256); function empty() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ITrueDistributor} from "ITrueDistributor.sol"; interface ITrueMultiFarm { function trueDistributor() external view returns (ITrueDistributor); function stake(IERC20 token, uint256 amount) external; function unstake(IERC20 token, uint256 amount) external; function claim(IERC20[] calldata tokens) external; function exit(IERC20[] calldata tokens) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {UpgradeableClaimable} from "UpgradeableClaimable.sol"; import {ITrueDistributor} from "ITrueDistributor.sol"; import {ITrueMultiFarm} from "ITrueMultiFarm.sol"; /** * @title TrueMultiFarm * @notice Deposit liquidity tokens to earn TRU rewards over time * @dev Staking pool where tokens are staked for TRU rewards * A Distributor contract decides how much TRU all farms in total can earn over time * Calling setShare() by owner decides ratio of rewards going to respective token farms * You can think of this contract as of a farm that is a distributor to the multiple other farms * A share of a farm in the multifarm is it's stake */ contract TrueMultiFarm is ITrueMultiFarm, UpgradeableClaimable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant PRECISION = 1e30; struct Stakes { // total amount of a particular token staked uint256 totalStaked; // who staked how much mapping(address => uint256) staked; } struct Rewards { // track overall cumulative rewards uint256 cumulativeRewardPerToken; // track previous cumulate rewards for accounts mapping(address => uint256) previousCumulatedRewardPerToken; // track claimable rewards for accounts mapping(address => uint256) claimableReward; // track total rewards uint256 totalClaimedRewards; uint256 totalRewards; } // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== IERC20 public rewardToken; ITrueDistributor public override trueDistributor; mapping(IERC20 => Stakes) public stakes; mapping(IERC20 => Rewards) public stakerRewards; // Shares of farms in the multifarm Stakes public shares; // Total rewards per farm Rewards public farmRewards; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted when an account stakes * @param who Account staking * @param amountStaked Amount of tokens staked */ event Stake(IERC20 indexed token, address indexed who, uint256 amountStaked); /** * @dev Emitted when an account unstakes * @param who Account unstaking * @param amountUnstaked Amount of tokens unstaked */ event Unstake(IERC20 indexed token, address indexed who, uint256 amountUnstaked); /** * @dev Emitted when an account claims TRU rewards * @param who Account claiming * @param amountClaimed Amount of TRU claimed */ event Claim(IERC20 indexed token, address indexed who, uint256 amountClaimed); /** * @dev Update all rewards associated with the token and msg.sender */ modifier update(IERC20 token) { distribute(); updateRewards(token); _; } /** * @dev Is there any reward allocatiion for given token */ modifier hasShares(IERC20 token) { require(shares.staked[address(token)] > 0, "TrueMultiFarm: This token has no shares"); _; } /** * @dev How much is staked by staker on token farm */ function staked(IERC20 token, address staker) external view returns (uint256) { return stakes[token].staked[staker]; } /** * @dev Initialize staking pool with a Distributor contract * The distributor contract calculates how much TRU rewards this contract * gets, and stores TRU for distribution. * @param _trueDistributor Distributor contract */ function initialize(ITrueDistributor _trueDistributor) public initializer { UpgradeableClaimable.initialize(msg.sender); trueDistributor = _trueDistributor; rewardToken = _trueDistributor.trustToken(); require(trueDistributor.farm() == address(this), "TrueMultiFarm: Distributor farm is not set"); } /** * @dev Stake tokens for TRU rewards. * Also claims any existing rewards. * @param amount Amount of tokens to stake */ function stake(IERC20 token, uint256 amount) external override hasShares(token) update(token) { if (stakerRewards[token].claimableReward[msg.sender] > 0) { _claim(token); } stakes[token].staked[msg.sender] = stakes[token].staked[msg.sender].add(amount); stakes[token].totalStaked = stakes[token].totalStaked.add(amount); token.safeTransferFrom(msg.sender, address(this), amount); emit Stake(token, msg.sender, amount); } /** * @dev Remove staked tokens * @param amount Amount of tokens to unstake */ function unstake(IERC20 token, uint256 amount) external override update(token) { _unstake(token, amount); } /** * @dev Claim TRU rewards */ function claim(IERC20[] calldata tokens) external override { uint256 tokensLength = tokens.length; distribute(); for (uint256 i = 0; i < tokensLength; i++) { updateRewards(tokens[i]); } for (uint256 i = 0; i < tokensLength; i++) { _claim(tokens[i]); } } /** * @dev Unstake amount and claim rewards */ function exit(IERC20[] calldata tokens) external override { distribute(); uint256 tokensLength = tokens.length; for (uint256 i = 0; i < tokensLength; i++) { updateRewards(tokens[i]); } for (uint256 i = 0; i < tokensLength; i++) { _unstake(tokens[i], stakes[tokens[i]].staked[msg.sender]); _claim(tokens[i]); } } /** * @dev Set shares for farms * Example: setShares([DAI, USDC], [1, 2]) will ensure that 33.(3)% of rewards will go to DAI farm and rest to USDC farm * If later setShares([DAI, TUSD], [2, 1]) will be called then shares of DAI will grow to 2, shares of USDC won't change and shares of TUSD will be 1 * So this will give 40% of rewards going to DAI farm, 40% to USDC and 20% to TUSD * @param tokens Token addresses * @param updatedShares share of the i-th token in the multifarm */ function setShares(IERC20[] calldata tokens, uint256[] calldata updatedShares) external onlyOwner { uint256 tokensLength = tokens.length; require(tokensLength == updatedShares.length, "TrueMultiFarm: Array lengths mismatch"); distribute(); for (uint256 i = 0; i < tokensLength; i++) { _updateClaimableRewardsForFarm(tokens[i]); } for (uint256 i = 0; i < tokensLength; i++) { uint256 oldStaked = shares.staked[address(tokens[i])]; shares.staked[address(tokens[i])] = updatedShares[i]; shares.totalStaked = shares.totalStaked.sub(oldStaked).add(updatedShares[i]); } } /** * @dev Internal unstake function * @param amount Amount of tokens to unstake */ function _unstake(IERC20 token, uint256 amount) internal { require(amount <= stakes[token].staked[msg.sender], "TrueMultiFarm: Cannot withdraw amount bigger than available balance"); stakes[token].staked[msg.sender] = stakes[token].staked[msg.sender].sub(amount); stakes[token].totalStaked = stakes[token].totalStaked.sub(amount); token.safeTransfer(msg.sender, amount); emit Unstake(token, msg.sender, amount); } /** * @dev Internal claim function */ function _claim(IERC20 token) internal { uint256 rewardToClaim = stakerRewards[token].claimableReward[msg.sender]; stakerRewards[token].totalClaimedRewards = stakerRewards[token].totalClaimedRewards.add(rewardToClaim); farmRewards.totalClaimedRewards = farmRewards.totalClaimedRewards.add(rewardToClaim); stakerRewards[token].claimableReward[msg.sender] = 0; farmRewards.claimableReward[address(token)] = farmRewards.claimableReward[address(token)].sub(rewardToClaim); rewardToken.safeTransfer(msg.sender, rewardToClaim); emit Claim(token, msg.sender, rewardToClaim); } /** * @dev View to estimate the claimable reward for an account that is staking token * @return claimable rewards for account */ function claimable(IERC20 token, address account) external view returns (uint256) { if (stakes[token].staked[account] == 0) { return stakerRewards[token].claimableReward[account]; } // estimate pending reward from distributor uint256 pending = _pendingDistribution(token); // calculate total rewards (including pending) uint256 newTotalRewards = pending.add(stakerRewards[token].totalClaimedRewards).mul(PRECISION); // calculate block reward uint256 totalBlockReward = newTotalRewards.sub(stakerRewards[token].totalRewards); // calculate next cumulative reward per token uint256 nextcumulativeRewardPerToken = stakerRewards[token].cumulativeRewardPerToken.add( totalBlockReward.div(stakes[token].totalStaked) ); // return claimable reward for this account return stakerRewards[token].claimableReward[account].add( stakes[token].staked[account] .mul(nextcumulativeRewardPerToken.sub(stakerRewards[token].previousCumulatedRewardPerToken[account])) .div(PRECISION) ); } function _pendingDistribution(IERC20 token) internal view returns (uint256) { // estimate pending reward from distributor uint256 pending = trueDistributor.farm() == address(this) ? trueDistributor.nextDistribution() : 0; // calculate new total rewards ever received by farm uint256 newTotalRewards = rewardToken.balanceOf(address(this)).add(pending).add(farmRewards.totalClaimedRewards).mul( PRECISION ); // calculate new rewards that were received since previous distribution uint256 totalBlockReward = newTotalRewards.sub(farmRewards.totalRewards); uint256 cumulativeRewardPerShare = farmRewards.cumulativeRewardPerToken; if (shares.totalStaked > 0) { cumulativeRewardPerShare = cumulativeRewardPerShare.add(totalBlockReward.div(shares.totalStaked)); } uint256 newReward = shares.staked[address(token)] .mul(cumulativeRewardPerShare.sub(farmRewards.previousCumulatedRewardPerToken[address(token)])) .div(PRECISION); return farmRewards.claimableReward[address(token)].add(newReward); } /** * @dev Distribute rewards from distributor and increase cumulativeRewardPerShare in Multifarm */ function distribute() internal { // pull TRU from distributor // only pull if there is distribution and distributor farm is set to this farm if (trueDistributor.nextDistribution() > 0 && trueDistributor.farm() == address(this)) { trueDistributor.distribute(); } _updateCumulativeRewardPerShare(); } /** * @dev This function must be called before any change of token share in multifarm happens (e.g. before shares.totalStaked changes) * This will also update cumulativeRewardPerToken after distribution has happened * 1. Get total lifetime rewards as Balance of TRU plus total rewards that have already been claimed * 2. See how much reward we got since previous update (R) * 3. Increase cumulativeRewardPerToken by R/total shares */ function _updateCumulativeRewardPerShare() internal { // calculate new total rewards ever received by farm uint256 newTotalRewards = rewardToken.balanceOf(address(this)).add(farmRewards.totalClaimedRewards).mul(PRECISION); // calculate new rewards that were received since previous distribution uint256 rewardSinceLastUpdate = newTotalRewards.sub(farmRewards.totalRewards); // update info about total farm rewards farmRewards.totalRewards = newTotalRewards; // if there are sub farms increase their value per share if (shares.totalStaked > 0) { farmRewards.cumulativeRewardPerToken = farmRewards.cumulativeRewardPerToken.add( rewardSinceLastUpdate.div(shares.totalStaked) ); } } /** * @dev Update rewards for the farm on token and for the staker. * The function must be called before any modification of staker's stake and to update values when claiming rewards */ function updateRewards(IERC20 token) internal { _updateTokenFarmRewards(token); _updateClaimableRewardsForStaker(token); } /** * @dev Update rewards data for the token farm - update all values associated with total available rewards for the farm inside multifarm */ function _updateTokenFarmRewards(IERC20 token) internal { _updateClaimableRewardsForFarm(token); _updateTotalRewards(token); } /** * @dev Increase total claimable rewards for token farm in multifarm. * This function must be called before share of the token in multifarm is changed and to update total claimable rewards for the staker */ function _updateClaimableRewardsForFarm(IERC20 token) internal { if (shares.staked[address(token)] == 0) { return; } // claimableReward += staked(token) * (cumulativeRewardPerShare - previousCumulatedRewardPerShare(token)) uint256 newReward = shares.staked[address(token)] .mul(farmRewards.cumulativeRewardPerToken.sub(farmRewards.previousCumulatedRewardPerToken[address(token)])) .div(PRECISION); farmRewards.claimableReward[address(token)] = farmRewards.claimableReward[address(token)].add(newReward); farmRewards.previousCumulatedRewardPerToken[address(token)] = farmRewards.cumulativeRewardPerToken; } /** * @dev Update total reward for the farm * Get total farm reward as claimable rewards for the given farm plus total rewards claimed by stakers in the farm */ function _updateTotalRewards(IERC20 token) internal { uint256 totalRewards = farmRewards.claimableReward[address(token)].add(stakerRewards[token].totalClaimedRewards).mul( PRECISION ); // calculate received reward uint256 rewardReceivedSinceLastUpdate = totalRewards.sub(stakerRewards[token].totalRewards); // if there are stakers of the token, increase cumulativeRewardPerToken by newly received reward per total staked amount if (stakes[token].totalStaked > 0) { stakerRewards[token].cumulativeRewardPerToken = stakerRewards[token].cumulativeRewardPerToken.add( rewardReceivedSinceLastUpdate.div(stakes[token].totalStaked) ); } // update farm rewards stakerRewards[token].totalRewards = totalRewards; } /** * @dev Update claimable rewards for the msg.sender who is staking this token * Increase claimable reward by the number that is * staker's stake times the change of cumulativeRewardPerToken for the given token since this function was previously called * This method must be called before any change of staker's stake */ function _updateClaimableRewardsForStaker(IERC20 token) internal { // increase claimable reward for sender by amount staked by the staker times the growth of cumulativeRewardPerToken since last update stakerRewards[token].claimableReward[msg.sender] = stakerRewards[token].claimableReward[msg.sender].add( stakes[token].staked[msg.sender] .mul( stakerRewards[token].cumulativeRewardPerToken.sub(stakerRewards[token].previousCumulatedRewardPerToken[msg.sender]) ) .div(PRECISION) ); // update previous cumulative for sender stakerRewards[token].previousCumulatedRewardPerToken[msg.sender] = stakerRewards[token].cumulativeRewardPerToken; } }
Initialize staking pool with a Distributor contract The distributor contract calculates how much TRU rewards this contract gets, and stores TRU for distribution. _trueDistributor Distributor contract/
function initialize(ITrueDistributor _trueDistributor) public initializer { UpgradeableClaimable.initialize(msg.sender); trueDistributor = _trueDistributor; rewardToken = _trueDistributor.trustToken(); require(trueDistributor.farm() == address(this), "TrueMultiFarm: Distributor farm is not set"); }
6,952,378
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./ERC721.sol"; import "./Ownable.sol"; import "./ITheNinjaHideout.sol"; contract TheFemaleNinjaHideout is ERC721, Ownable { using Strings for uint256; uint256 public constant MAX_NINJAS = 444; uint256 public reservedNinjas = 44; // Withdrawal addresses address public constant ADD = 0xa64b407D4363E203F682f7D95eB13241B039E580; bool public claimStarted; mapping(uint256 => bool) public claimed; ITheNinjaHideout public ITNH = ITheNinjaHideout(0x97e41d5cE9C8cB1f83947ef82a86E345Aed673F3); constructor() ERC721("The Ninja Hideout (Females)", "TNHF") {} function gift(address[] calldata receivers) external onlyOwner { require(totalSupply() + receivers.length <= MAX_NINJAS, "MAX_MINT"); require(receivers.length <= reservedNinjas, "No reserved ninjas left"); for (uint256 i = 0; i < receivers.length; i++) { reservedNinjas--; _safeMint(receivers[i], totalSupply()); } } function claim() external returns (bool) { require(claimStarted, "Claim not started!"); require(!_isContract(msg.sender), "Caller cannot be a contract"); require( ITNH.tokensOfOwner(_msgSender()).length > 1, "Not enough to claim" ); uint256[] memory ownedTokens = ITNH.tokensOfOwner(_msgSender()); uint256 claimCount = 0; uint256 firstClaim; for (uint256 i = 0; i < ownedTokens.length; i++) { if (!claimed[ownedTokens[i]]) { if (claimCount == 0) firstClaim = ownedTokens[i]; claimCount++; claimed[ownedTokens[i]] = true; } if (claimCount == 2) { claimCount = 0; if (totalSupply() < MAX_NINJAS) { uint256 tokenIndex = totalSupply(); _safeMint(_msgSender(), tokenIndex); } } } if (claimCount == 1) claimed[firstClaim] = false; return true; } function claimableAmount() external view returns (uint256) { uint256[] memory ownedTokens = ITNH.tokensOfOwner(_msgSender()); uint256 claimCount = 0; for (uint256 i = 0; i < ownedTokens.length; i++) { if (!claimed[ownedTokens[i]]) { claimCount++; } } return claimCount; } function isClaimed(uint256 tokenId) external view returns (bool) { return claimed[tokenId]; } function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { result[i] = tokenOfOwnerByIndex(_owner, i); } return result; } } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(tokenId < totalSupply(), "Token not exist."); string memory _tokenURI = _tokenUriMapping[tokenId]; //return tokenURI if it is set if (bytes(_tokenURI).length > 0) { return _tokenURI; } //If tokenURI is not set, concatenate the tokenID to the baseURI. return string(abi.encodePacked(baseURI(), tokenId.toString(), ".json")); } function toggleClaim() public onlyOwner { claimStarted = !claimStarted; } function setBaseURI(string memory _newBaseURI) public onlyOwner { _setBaseURI(_newBaseURI); } function setTokenURI(uint256 tokenId, string memory _tokenURI) public onlyOwner { _setTokenURI(tokenId, _tokenURI); } function withdrawAll() public payable onlyOwner { //withdraw half require( payable(ADD).send(address(this).balance), "Withdraw Unsuccessful" ); } function _isContract(address _addr) internal view returns (bool) { uint32 _size; assembly { _size := extcodesize(_addr) } return (_size > 0); } }
return tokenURI if it is set
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(tokenId < totalSupply(), "Token not exist."); string memory _tokenURI = _tokenUriMapping[tokenId]; if (bytes(_tokenURI).length > 0) { return _tokenURI; } }
1,253,342
./partial_match/5/0xabCD258252155b4BF4F2694eC0B789f232eaaAb9/sources/SharedDeposit.sol
USER INTERACTIONS input is whole, not / 1e18 , i.e. in 1 = 1 eth sendmake sure max validator limit not yet reached make sure its mintable TODO: fix this check require(address(this).balance.add(msg.value) < uint256(32).mul(numValidators).mul(1e18));
function deposit() public payable nonReentrant whenNotPaused { uint value = uint(msg.value); uint shareOfOne = value.div(32); uint valMinusAdmin = value.sub(adminFee.mul(shareOfOne)); uint newShareTotal = curValidatorShares.add(valMinusAdmin); require(newShareTotal <= maxValidatorShares(), "Eth2Staker:deposit:Amount too large, not enough validators left"); curValidatorShares = newShareTotal; adminFeeTotal = adminFeeTotal.add(adminFee.mul(shareOfOne)); BETHToken.mint(msg.sender, valMinusAdmin); }
16,843,361
./partial_match/1/0x79241Fd23F74a5587D22E24795776159f5455569/sources/Proposal22.sol
Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. This method is included for ERC20 compatibility. increaseAllowance and decreaseAllowance should be used instead. Changing an allowance with this method brings the risk that someone may transfer both the old and the new allowance - if they are both greater than zero - if a transfer transaction is mined before the later approve() call is mined. spender The address which will spend the funds. value The amount of tokens to be spent./
function approve(address spender, uint256 value) override external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
4,022,546
./full_match/80001/0xBd99517e1994226FB8124D37087A0b835829D593/sources/contracts/Portfolio.sol
Write function to update description Optional: Check if the new description is different from the current description
function setDescription(string memory _newDescription) public onlyOwner { require( bytes(_newDescription).length > 0, "Description cannot be empty" ); require( keccak256(bytes(_description)) != keccak256(bytes(_newDescription)), "New description is the same as the current description" ); _description = _newDescription; }
5,572,139
// 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-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); }
5,414,101
pragma solidity >=0.5.0 <0.6.0; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/CanReclaimToken.sol /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { /** * @dev Reclaim all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function reclaimToken(IERC20 token) external onlyOwner { address payable owner = address(uint160(owner())); if (address(token) == address(0)) { owner.transfer(address(this).balance); return; } uint256 balance = token.balanceOf(address(this)); token.transfer(owner, balance); } } // File: lib/PPQueue.sol /** * @title PPQueue */ library PPQueue { struct Item { // uint idx; bool exists; uint prev; uint next; } struct Queue { uint length; uint first; uint last; uint counter; mapping (uint => Item) items; } /** * @dev push item to fifo queue */ function push(Queue storage queue, uint index) internal { require(!queue.items[index].exists); queue.items[index] = Item({ exists: true, prev: queue.last, next: 0 }); if (queue.length == 0) { queue.first = index; } else { queue.items[queue.last].next = index; } //save last item queue idx queue.last = index; queue.length++; } /** * @dev pop item from fifo queue */ function popf(Queue storage queue) internal returns (uint index) { index = queue.first; remove(queue, index); } /** * @dev pop item from lifo queue */ function popl(Queue storage queue) internal returns (uint index) { index = queue.last; remove(queue, index); } /** * @dev remove an item from queue */ function remove(Queue storage queue, uint index) internal { require(queue.length > 0); require(queue.items[index].exists); if (queue.items[index].prev != 0) { queue.items[queue.items[index].prev].next = queue.items[index].next; } else { //assume we delete first item queue.first = queue.items[index].next; } if (queue.items[index].next != 0) { queue.items[queue.items[index].next].prev = queue.items[index].prev; } else { //assume we delete last item queue.last = queue.items[index].prev; } //del from queue delete queue.items[index]; queue.length--; } /** * @dev get queue length * @return uint */ function len(Queue storage queue) internal view returns (uint) { //auto prevent existing of agents with updated address and same id return queue.length; } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev 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: contracts/Referrals.sol interface Affiliates { function plusByCode(address _token, uint256 _affCode, uint _amount) external payable; function upAffCode(uint256 _affCode) external view returns (uint); function setUpAffCodeByAddr(address _address, uint _upAffCode) external; function getAffCode(uint256 _a) external pure returns (uint); function sendAffReward(address _token, address _address) external returns (uint); } contract Referrals is Ownable, ReentrancyGuard { using SafeMath for uint; //1% - 100, 10% - 1000 50% - 5000 uint256[] public affLevelReward; Affiliates public aff; constructor (address _aff) public { require(_aff != address(0)); aff = Affiliates(_aff); // two upper levels for each: winner and loser // total sum of level's % must be 100% //1% - 100, 10% - 1000 50% - 5000 affLevelReward.push(0); // level 0, 10% - player self - cacheback affLevelReward.push(8000); // level 1, 70% of affPool affLevelReward.push(2000); // level 2, 20% of affPool } //AFFILIATES function setAffiliateLevel(uint256 _level, uint256 _rewardPercent) external onlyOwner { require(_level < affLevelReward.length); affLevelReward[_level] = _rewardPercent; } function incAffiliateLevel(uint256 _rewardPercent) external onlyOwner { affLevelReward.push(_rewardPercent); } function decAffiliateLevel() external onlyOwner { delete affLevelReward[affLevelReward.length--]; } function affLevelsCount() external view returns (uint) { return affLevelReward.length; } function _distributeAffiliateReward(uint256 _sum, uint256 _affCode, uint256 _level, bool _cacheBack) internal { uint upAffCode = aff.upAffCode(_affCode); if (affLevelReward[_level] > 0 && _affCode != 0 && (_level > 0 || (_cacheBack && upAffCode != 0))) { uint total = _getPercent(_sum, affLevelReward[_level]); aff.plusByCode.value(total)(address(0x0), _affCode, total); } if (affLevelReward.length > ++_level) { _distributeAffiliateReward(_sum, upAffCode, _level, false); } } function getAffReward() external nonReentrant { aff.sendAffReward(address(0x0), msg.sender); } //1% - 100, 10% - 1000 50% - 5000 function _getPercent(uint256 _v, uint256 _p) internal pure returns (uint) { return _v.mul(_p) / 10000; } } // File: openzeppelin-solidity/contracts/access/Roles.sol /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: lib/ServiceRole.sol contract ServiceRole { using Roles for Roles.Role; event ServiceAdded(address indexed account); event ServiceRemoved(address indexed account); Roles.Role private services; constructor() internal { _addService(msg.sender); } modifier onlyService() { require(isService(msg.sender)); _; } function isService(address account) public view returns (bool) { return services.has(account); } function renounceService() public { _removeService(msg.sender); } function _addService(address account) internal { services.add(account); emit ServiceAdded(account); } function _removeService(address account) internal { services.remove(account); emit ServiceRemoved(account); } } // File: contracts/Services.sol contract Services is Ownable,ServiceRole { constructor() public{ } function addService(address account) external onlyOwner { _addService(account); } function removeService(address account) external onlyOwner { _removeService(account); } } // File: contracts/BetLevels.sol contract BetLevels is Ownable { //value => level mapping(uint => uint) betLevels; //array of avail bets values uint[] public betLevelValues; constructor () public { //zero level = 0, skip it betLevelValues.length += 8; _setBetLevel(1, 0.01 ether); _setBetLevel(2, 0.05 ether); _setBetLevel(3, 0.1 ether); _setBetLevel(4, 0.5 ether); _setBetLevel(5, 1 ether); _setBetLevel(6, 5 ether); _setBetLevel(7, 10 ether); } function addBetLevel(uint256 value) external onlyOwner { require(betLevelValues.length == 0 || betLevelValues[betLevelValues.length - 1] < value); betLevelValues.length++; _setBetLevel(betLevelValues.length - 1, value); } function _setBetLevel(uint level, uint value) internal { betLevelValues[level] = value; betLevels[value] = level; } function setBetLevel(uint level, uint value) external onlyOwner { require(betLevelValues.length > level); require(betLevelValues[level] != value); delete betLevels[betLevelValues[level]]; _setBetLevel(level, value); } function betLevelsCount() external view returns (uint) { return betLevelValues.length; } function getBetLevel(uint value) internal view returns (uint level) { level = betLevels[value]; require(level != 0); } } // File: contracts/BetIntervals.sol contract BetIntervals is Ownable { event SetInterval(uint startsFrom, uint pastCount, uint newInterval, uint newPeriod); uint public constant BetEpoch = 1550534400; //Tuesday, 19 February 2019 г., 0:00:00 struct RoundInterval { uint interval; uint from; uint count; uint period; } RoundInterval[] public intervalHistory; constructor() public{ intervalHistory.push(RoundInterval({ period : 10 * 60, from : BetEpoch, count : 0, interval : 15 * 60 })); } function setInterval(uint _interval, uint _period) external onlyOwner { RoundInterval memory i = _getRoundIntervalAt(now); uint intervalsCount = (now - i.from) / i.interval + 1; RoundInterval memory ni = RoundInterval({ interval : _interval, from : i.from + i.interval * intervalsCount, count : intervalsCount + i.count, period : _period }); intervalHistory.push(ni); emit SetInterval(ni.from, ni.count, _interval, _period); } function getCurrentRoundId() public view returns (uint) { return getRoundIdAt(now, 0); } function getNextRoundId() public view returns (uint) { return getRoundIdAt(now, 1); } function getRoundIdAt(uint _time, uint _shift) public view returns (uint) { uint intervalId = _getRoundIntervalIdAt(_time); RoundInterval memory i = intervalHistory[intervalId]; return _time > i.from ? (_time - i.from) / i.interval + i.count + _shift : 0; } function getCurrentRoundInterval() public view returns (uint interval, uint period) { return getRoundIntervalAt(now); } function getRoundIntervalAt(uint _time) public view returns (uint interval, uint period) { RoundInterval memory i = _getRoundIntervalAt(_time); interval = i.interval; period = i.period; } function getCurrentRoundInfo() public view returns ( uint roundId, uint startAt, uint finishAt ) { return getRoundInfoAt(now, 0); } function getNextRoundInfo() public view returns ( uint roundId, uint startAt, uint finishAt ) { return getRoundInfoAt(now, 1); } function getRoundInfoAt(uint _time, uint _shift) public view returns ( uint roundId, uint startAt, uint finishAt ) { RoundInterval memory i = _getRoundIntervalAt(_time); uint intervalsCount = _time > i.from ? (_time - i.from) / i.interval + _shift : 0; startAt = i.from + i.interval * intervalsCount; roundId = i.count + intervalsCount; finishAt = i.period + startAt; } function _getRoundIntervalAt(uint _time) internal view returns (RoundInterval memory) { return intervalHistory[_getRoundIntervalIdAt(_time)]; } function _getRoundIntervalIdAt(uint _time) internal view returns (uint) { require(intervalHistory.length > 0); // if (intervalHistory.length == 0) return 0; // Shortcut for the actual value if (_time >= intervalHistory[intervalHistory.length - 1].from) return intervalHistory.length - 1; if (_time < intervalHistory[0].from) return 0; // Binary search of the value in the array uint min = 0; uint max = intervalHistory.length - 1; while (max > min) { uint mid = (max + min + 1) / 2; if (intervalHistory[mid].from <= _time) { min = mid; } else { max = mid - 1; } } return min; } } // File: contracts/ReservedValue.sol contract ReservedValue is Ownable { using SafeMath for uint; event Income(address source, uint256 amount); address payable public wallet; //total reserved eth amount uint256 public totalReserved; constructor(address payable _w) public { require(_w != address(0)); wallet = _w; } function setWallet(address payable _w) external onlyOwner { require(address(_w) != address(0)); wallet = _w; } /// @notice The fallback function payable function() external payable { require(msg.value > 0); _flushBalance(); } function _flushBalance() internal { uint256 balance = address(this).balance.sub(totalReserved); if (balance > 0) { address(wallet).transfer(balance); emit Income(address(this), balance); } } function _incTotalReserved(uint value) internal { totalReserved = totalReserved.add(value); } function _decTotalReserved(uint value) internal { totalReserved = totalReserved.sub(value); } } // File: contracts/Bets.sol contract Bets is Ownable, ReservedValue, BetIntervals, BetLevels, Referrals, Services, CanReclaimToken { using SafeMath for uint; event BetCreated(address indexed bettor, uint betId, uint index, uint allyRace, uint enemyRace, uint betLevel, uint value, uint utmSource); event BetAccepted(uint betId, uint opBetId, uint roundId); event BetCanceled(uint betId); event BetRewarded(uint winBetId, uint loseBetId, uint reward, bool noWin); event BetRoundCalculated(uint roundId, uint winnerRace, uint loserRace, uint betLevel, uint pool, uint bettorCount); event StartBetRound(uint roundId, uint startAt, uint finishAt); event RoundRaceResult(uint roundId, uint raceId, int32 result); event FinishBetRound(uint roundId, uint startCheckedAt, uint finishCheckedAt); using PPQueue for PPQueue.Queue; struct Bettor { uint counter; mapping(uint => uint) bets; } struct Race { uint index; bool exists; uint count; int32 result; } struct BetRound { uint startedAt; uint finishedAt; uint startCheckedAt; uint finishCheckedAt; uint[] bets; mapping(uint => Race) races; uint[] raceList; } uint[] public roundsList; //roundId => BetRound mapping(uint => BetRound) betRounds; struct Bet { address payable bettor; uint roundId; uint allyRace; uint enemyRace; uint value; uint level; uint opBetId; uint reward; bool active; } struct BetStat { uint sum; uint pool; uint affPool; uint count; bool taxed; } uint public lastBetId; mapping(uint => Bet) bets; mapping(address => Bettor) bettors; struct BetData { mapping(uint => BetStat) stat; PPQueue.Queue queue; } //betLevel => allyRace => enemyRace => BetData mapping(uint => mapping(uint => mapping(uint => BetData))) betData; //raceId => allowed mapping(uint => bool) public allowedRace; uint public systemFeePcnt; uint public affPoolPcnt; constructor(address payable _w, address _aff) ReservedValue(_w) Referrals(_aff) public payable { // systemFee 5% (from loser sum) // affPoolPercent 5% (from loser sum) setFee(500, 500); //allow races, BTC,LTC,ETH by default allowedRace[1] = true; allowedRace[2] = true; allowedRace[4] = true; allowedRace[10] = true; allowedRace[13] = true; } function setFee(uint _systemFee, uint _affFee) public onlyOwner { systemFeePcnt = _systemFee; affPoolPcnt = _affFee; } function allowRace(uint _race, bool _allow) external onlyOwner { allowedRace[_race] = _allow; } function makeBet(uint allyRace, uint enemyRace, uint _affCode, uint _source) public payable { require(allyRace != enemyRace && allowedRace[allyRace] && allowedRace[enemyRace]); //require bet level exists uint level = getBetLevel(msg.value); Bet storage bet = bets[++lastBetId]; bet.active = true; bet.bettor = msg.sender; bet.allyRace = allyRace; bet.enemyRace = enemyRace; bet.value = msg.value; bet.level = level; //save bet to bettor list && inc. bets count bettors[bet.bettor].bets[++bettors[bet.bettor].counter] = lastBetId; emit BetCreated(bet.bettor, lastBetId, bettors[bet.bettor].counter, allyRace, enemyRace, level, msg.value, _source); //upd queue BetData storage allyData = betData[level][allyRace][enemyRace]; BetData storage enemyData = betData[level][enemyRace][allyRace]; //if there is nobody on opposite side if (enemyData.queue.len() == 0) { allyData.queue.push(lastBetId); } else { //accepting bet uint nextRoundId = _startNextRound(); uint opBetId = enemyData.queue.popf(); bet.opBetId = opBetId; bet.roundId = nextRoundId; bets[opBetId].opBetId = lastBetId; bets[opBetId].roundId = nextRoundId; //upd fight stat allyData.stat[nextRoundId].sum = allyData.stat[nextRoundId].sum.add(msg.value); allyData.stat[nextRoundId].count++; enemyData.stat[nextRoundId].sum = enemyData.stat[nextRoundId].sum.add(bets[opBetId].value); enemyData.stat[nextRoundId].count++; if (!betRounds[nextRoundId].races[allyRace].exists) { betRounds[nextRoundId].races[allyRace].exists = true; betRounds[nextRoundId].races[allyRace].index = betRounds[nextRoundId].raceList.length; betRounds[nextRoundId].raceList.push(allyRace); } betRounds[nextRoundId].races[allyRace].count++; if (!betRounds[nextRoundId].races[enemyRace].exists) { betRounds[nextRoundId].races[enemyRace].exists = true; betRounds[nextRoundId].races[enemyRace].index = betRounds[nextRoundId].raceList.length; betRounds[nextRoundId].raceList.push(enemyRace); } betRounds[nextRoundId].races[enemyRace].count++; betRounds[nextRoundId].bets.push(opBetId); betRounds[nextRoundId].bets.push(lastBetId); emit BetAccepted(opBetId, lastBetId, nextRoundId); } _incTotalReserved(msg.value); // update last affiliate aff.setUpAffCodeByAddr(bet.bettor, _affCode); } function _startNextRound() internal returns (uint nextRoundId) { uint nextStartAt; uint nextFinishAt; (nextRoundId, nextStartAt, nextFinishAt) = getNextRoundInfo(); if (betRounds[nextRoundId].startedAt == 0) { betRounds[nextRoundId].startedAt = nextStartAt; roundsList.push(nextRoundId); emit StartBetRound(nextRoundId, nextStartAt, nextFinishAt); } } function cancelBettorBet(address bettor, uint betIndex) external onlyService { _cancelBet(bettors[bettor].bets[betIndex]); } function cancelMyBet(uint betIndex) external nonReentrant { _cancelBet(bettors[msg.sender].bets[betIndex]); } function cancelBet(uint betId) external nonReentrant { require(bets[betId].bettor == msg.sender); _cancelBet(betId); } function _cancelBet(uint betId) internal { Bet storage bet = bets[betId]; require(bet.active); //can cancel only not yet accepted bets require(bet.roundId == 0); //upd queue BetData storage allyData = betData[bet.level][bet.allyRace][bet.enemyRace]; allyData.queue.remove(betId); _decTotalReserved(bet.value); bet.bettor.transfer(bet.value); emit BetCanceled(betId); // del bet delete bets[betId]; } function _calcRoundLevel(uint level, uint allyRace, uint enemyRace, uint roundId) internal returns (int32 allyResult, int32 enemyResult){ require(betRounds[roundId].startedAt != 0 && betRounds[roundId].finishedAt != 0); allyResult = betRounds[roundId].races[allyRace].result; enemyResult = betRounds[roundId].races[enemyRace].result; if (allyResult < enemyResult) { (allyRace, enemyRace) = (enemyRace, allyRace); } BetData storage winnerData = betData[level][allyRace][enemyRace]; BetData storage loserData = betData[level][enemyRace][allyRace]; if (!loserData.stat[roundId].taxed) { loserData.stat[roundId].taxed = true; //check if really winner if (allyResult != enemyResult) { //system fee uint fee = _getPercent(loserData.stat[roundId].sum, systemFeePcnt); _decTotalReserved(fee); //affiliate % winnerData.stat[roundId].affPool = _getPercent(loserData.stat[roundId].sum, affPoolPcnt); //calc pool for round winnerData.stat[roundId].pool = loserData.stat[roundId].sum - fee - winnerData.stat[roundId].affPool; emit BetRoundCalculated(roundId, allyRace, enemyRace, level, winnerData.stat[roundId].pool, winnerData.stat[roundId].count); } } if (!winnerData.stat[roundId].taxed) { winnerData.stat[roundId].taxed = true; } } function rewardBettorBet(address bettor, uint betIndex) external onlyService { _rewardBet(bettors[bettor].bets[betIndex]); } function rewardMyBet(uint betIndex) external nonReentrant { _rewardBet(bettors[msg.sender].bets[betIndex]); } function rewardBet(uint betId) external nonReentrant { require(bets[betId].bettor == msg.sender); _rewardBet(betId); } function _rewardBet(uint betId) internal { Bet storage bet = bets[betId]; require(bet.active); //only accepted bets require(bet.roundId != 0); (int32 allyResult, int32 enemyResult) = _calcRoundLevel(bet.level, bet.allyRace, bet.enemyRace, bet.roundId); //disabling bet bet.active = false; if (allyResult >= enemyResult) { bet.reward = bet.value; if (allyResult > enemyResult) { //win BetStat memory s = betData[bet.level][bet.allyRace][bet.enemyRace].stat[bet.roundId]; bet.reward = bet.reward.add(s.pool / s.count); // winner's affiliates + loser's affiliates uint affPool = s.affPool / s.count; _decTotalReserved(affPool); // affiliate pool is 1/2 of total aff. pool, per each winner and loser _distributeAffiliateReward(affPool >> 1, aff.getAffCode(uint(bet.bettor)), 0, false); //no cacheback to winner _distributeAffiliateReward(affPool >> 1, aff.getAffCode(uint(bets[bet.opBetId].bettor)), 0, true); //cacheback to looser } bet.bettor.transfer(bet.reward); _decTotalReserved(bet.reward); emit BetRewarded(betId, bet.opBetId, bet.reward, allyResult == enemyResult); } _flushBalance(); } function provisionBetReward(uint betId) public view returns (uint reward) { Bet storage bet = bets[betId]; if (!bet.active) { return 0; } int32 allyResult = betRounds[bet.roundId].races[bet.allyRace].result; int32 enemyResult = betRounds[bet.roundId].races[bet.enemyRace].result; if (allyResult < enemyResult) { return 0; } reward = bet.value; BetData storage allyData = betData[bet.level][bet.allyRace][bet.enemyRace]; BetData storage enemyData = betData[bet.level][bet.enemyRace][bet.allyRace]; if (allyResult > enemyResult) { //win if (!enemyData.stat[bet.roundId].taxed) { uint pool = enemyData.stat[bet.roundId].sum - _getPercent(enemyData.stat[bet.roundId].sum, systemFeePcnt + affPoolPcnt); reward = bet.value.add(pool / allyData.stat[bet.roundId].count); } else { reward = bet.value.add(allyData.stat[bet.roundId].pool / allyData.stat[bet.roundId].count); } } } function provisionBettorBetReward(address bettor, uint betIndex) public view returns (uint reward) { return provisionBetReward(bettors[bettor].bets[betIndex]); } function finalizeBetRound(uint betLevel, uint allyRace, uint enemyRace, uint roundId) external onlyService { _calcRoundLevel(betLevel, allyRace, enemyRace, roundId); _flushBalance(); } function roundsCount() external view returns (uint) { return roundsList.length; } function getBettorsBetCounter(address bettor) external view returns (uint) { return bettors[bettor].counter; } function getBettorsBetId(address bettor, uint betIndex) external view returns (uint betId) { return bettors[bettor].bets[betIndex]; } function getBettorsBets(address bettor) external view returns (uint[] memory betIds) { Bettor storage b = bettors[bettor]; uint j; for (uint i = 1; i <= b.counter; i++) { if (b.bets[i] != 0) { j++; } } if (j > 0) { betIds = new uint[](j); j = 0; for (uint i = 1; i <= b.counter; i++) { if (b.bets[i] != 0) { betIds[j++] = b.bets[i]; } } } } function getBet(uint betId) public view returns ( address bettor, bool active, uint roundId, uint allyRace, uint enemyRace, uint value, uint level, uint opBetId, uint reward ) { Bet memory b = bets[betId]; return (b.bettor, b.active, b.roundId, b.allyRace, b.enemyRace, b.value, b.level, b.opBetId, b.reward); } function getBetRoundStat(uint roundId, uint allyRace, uint enemyRace, uint level) public view returns ( uint sum, uint pool, uint affPool, uint count, bool taxed ) { BetStat memory bs = betData[level][allyRace][enemyRace].stat[roundId]; return (bs.sum, bs.pool, bs.affPool, bs.count, bs.taxed); } function getBetQueueLength(uint allyRace, uint enemyRace, uint level) public view returns (uint) { return betData[level][allyRace][enemyRace].queue.len(); } function getCurrentBetRound() public view returns ( uint roundId, uint startedAt, uint finishedAt, uint startCheckedAt, uint finishCheckedAt, uint betsCount, uint raceCount ) { roundId = getCurrentRoundId(); (startedAt, finishedAt, startCheckedAt, finishCheckedAt, betsCount, raceCount) = getBetRound(roundId); } function getNextBetRound() public view returns ( uint roundId, uint startedAt, uint finishedAt, uint startCheckedAt, uint finishCheckedAt, uint betsCount, uint raceCount ) { roundId = getCurrentRoundId() + 1; (startedAt, finishedAt, startCheckedAt, finishCheckedAt, betsCount, raceCount) = getBetRound(roundId); } function getBetRound(uint roundId) public view returns ( uint startedAt, uint finishedAt, uint startCheckedAt, uint finishCheckedAt, uint betsCount, uint raceCount ) { BetRound memory b = betRounds[roundId]; return (b.startedAt, b.finishedAt, b.startCheckedAt, b.finishCheckedAt, b.bets.length, b.raceList.length); } function getBetRoundBets(uint roundId) public view returns (uint[] memory betIds) { return betRounds[roundId].bets; } function getBetRoundBetId(uint roundId, uint betIndex) public view returns (uint betId) { return betRounds[roundId].bets[betIndex]; } function getBetRoundRaces(uint roundId) public view returns (uint[] memory raceIds) { return betRounds[roundId].raceList; } function getBetRoundRaceStat(uint roundId, uint raceId) external view returns ( uint index, uint count, int32 result ){ Race memory r = betRounds[roundId].races[raceId]; return (r.index, r.count, r.result); } function setBetRoundResult(uint roundId, uint count, uint[] memory packedRaces, uint[] memory packedResults) public onlyService { require(packedRaces.length == packedResults.length); require(packedRaces.length * 8 >= count); BetRound storage r = betRounds[roundId]; require(r.startedAt != 0 && r.finishedAt == 0); uint raceId; int32 result; for (uint i = 0; i < count; i++) { raceId = _upack(packedRaces[i / 8], i % 8); result = int32(_upack(packedResults[i / 8], i % 8)); r.races[raceId].result = result; emit RoundRaceResult(roundId, raceId, result); } } function finishBetRound(uint roundId, uint startCheckedAt, uint finishCheckedAt) public onlyService { BetRound storage r = betRounds[roundId]; require(r.startedAt != 0 && r.finishedAt == 0); uint finishAt; (, , finishAt) = getRoundInfoAt(r.startedAt, 0); require(now >= finishAt); r.finishedAt = finishAt; r.startCheckedAt = startCheckedAt; r.finishCheckedAt = finishCheckedAt; emit FinishBetRound(roundId, startCheckedAt, finishCheckedAt); } //extract n-th 32-bit int from uint function _upack(uint _v, uint _n) internal pure returns (uint) { // _n = _n & 7; //be sure < 8 return (_v >> (32 * _n)) & 0xFFFFFFFF; } }
pop item from lifo queue/
function popl(Queue storage queue) internal returns (uint index) { index = queue.last; remove(queue, index); }
7,305,594
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY39() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF342(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER892(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE335(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE49(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM790(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER356(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL503(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER272() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA393() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY39() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF342(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER892(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER337(_MSGSENDER272(), recipient, amount); return true; } function ALLOWANCE335(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE49(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, amount); return true; } function TRANSFERFROM790(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER337(sender, recipient, amount); _APPROVE27(sender, _MSGSENDER272(), _allowances[sender][_MSGSENDER272()].SUB956(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE743(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, _allowances[_MSGSENDER272()][spender].ADD786(addedValue)); return true; } function DECREASEALLOWANCE224(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, _allowances[_MSGSENDER272()][spender].SUB956(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER337(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB956(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD786(amount); emit TRANSFER356(sender, recipient, amount); } function _MINT977(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD786(amount); _balances[account] = _balances[account].ADD786(amount); emit TRANSFER356(address(0), account, amount); } function _BURN905(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB956(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB956(amount); emit TRANSFER356(account, address(0), amount); } function _APPROVE27(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING 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 APPROVAL503(owner, spender, amount); } function _BURNFROM541(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN905(account, amount); _APPROVE27(account, _MSGSENDER272(), _allowances[account][_MSGSENDER272()].SUB956(amount, "ERC20: burn amount exceeds allowance")); } } library SafeMath { function ADD786(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB956(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB956(a, b, "SafeMath: subtraction overflow"); } function SUB956(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL88(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 DIV343(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV343(a, b, "SafeMath: division by zero"); } function DIV343(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD197(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD197(a, b, "SafeMath: modulo by zero"); } function MOD197(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT818(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE126(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE5(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER46(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.TRANSFER892.selector, to, value)); } function SAFETRANSFERFROM146(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.TRANSFERFROM790.selector, from, to, value)); } function SAFEAPPROVE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE335(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, value)); } function SAFEINCREASEALLOWANCE235(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE335(address(this), spender).ADD786(value); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE541(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE335(address(this), spender).SUB956(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, newAllowance)); } function CALLOPTIONALRETURN200(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT818(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract pLINKVault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct RewardDivide { mapping (address => uint256) amount; uint256 time; } IERC20 public token = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); address public governance; uint256 public totalDeposit; mapping(address => uint256) public depositBalances; mapping(address => uint256) public rewardBalances; address[] public addressIndices; mapping(uint256 => RewardDivide) public _rewards; uint256 public _rewardCount = 0; event WITHDRAWN459(address indexed user, uint256 amount); //inject NONSTANDARD NAMING constructor () public { governance = msg.sender; } function BALANCE221() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF342(address(this)); } function SETGOVERNANCE269(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function DEPOSITALL567() external { //inject NONSTANDARD NAMING DEPOSIT500(token.BALANCEOF342(msg.sender)); } function DEPOSIT500(uint256 _amount) public { //inject NONSTANDARD NAMING require(_amount > 0, "can't deposit 0"); uint arrayLength = addressIndices.length; bool found = false; for (uint i = 0; i < arrayLength; i++) { if(addressIndices[i]==msg.sender){ found=true; break; } } if(!found){ addressIndices.push(msg.sender); } uint256 realAmount = _amount.MUL88(995).DIV343(1000); uint256 feeAmount = _amount.MUL88(5).DIV343(1000); address feeAddress = 0xD319d5a9D039f06858263E95235575Bb0Bd630BC; address vaultAddress = 0x32e4bD46e7cee1797b22B02c0340818B6e75C75a; // Vault7 Address token.SAFETRANSFERFROM146(msg.sender, feeAddress, feeAmount); token.SAFETRANSFERFROM146(msg.sender, vaultAddress, realAmount); totalDeposit = totalDeposit.ADD786(realAmount); depositBalances[msg.sender] = depositBalances[msg.sender].ADD786(realAmount); } function REWARD357(uint256 _amount) external { //inject NONSTANDARD NAMING require(_amount > 0, "can't reward 0"); require(totalDeposit > 0, "totalDeposit must bigger than 0"); token.SAFETRANSFERFROM146(msg.sender, address(this), _amount); uint arrayLength = addressIndices.length; for (uint i = 0; i < arrayLength; i++) { rewardBalances[addressIndices[i]] = rewardBalances[addressIndices[i]].ADD786(_amount.MUL88(depositBalances[addressIndices[i]]).DIV343(totalDeposit)); _rewards[_rewardCount].amount[addressIndices[i]] = _amount.MUL88(depositBalances[addressIndices[i]]).DIV343(totalDeposit); } _rewards[_rewardCount].time = block.timestamp; _rewardCount++; } function WITHDRAWALL757() external { //inject NONSTANDARD NAMING WITHDRAW270(rewardBalances[msg.sender]); } function WITHDRAW270(uint256 _amount) public { //inject NONSTANDARD NAMING require(_rewardCount > 0, "no reward amount"); require(_amount > 0, "can't withdraw 0"); uint256 availableWithdrawAmount = AVAILABLEWITHDRAW17(msg.sender); if (_amount > availableWithdrawAmount) { _amount = availableWithdrawAmount; } token.SAFETRANSFER46(msg.sender, _amount); rewardBalances[msg.sender] = rewardBalances[msg.sender].SUB956(_amount); emit WITHDRAWN459(msg.sender, _amount); } function AVAILABLEWITHDRAW17(address owner) public view returns(uint256){ //inject NONSTANDARD NAMING uint256 availableWithdrawAmount = rewardBalances[owner]; for (uint256 i = _rewardCount - 1; block.timestamp < _rewards[i].time.ADD786(7 days); --i) { availableWithdrawAmount = availableWithdrawAmount.SUB956(_rewards[i].amount[owner].MUL88(_rewards[i].time.ADD786(7 days).SUB956(block.timestamp)).DIV343(7 days)); if (i == 0) break; } return availableWithdrawAmount; } }
inject NONSTANDARD NAMING
function SUB956(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
12,811,412
pragma solidity ^0.5.4; 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); } } interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /* * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor () internal { _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } 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; } } 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; } } 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) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply = 1e6; constructor() public { _balances[msg.sender] = 1e6; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // 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 token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0)); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0)); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId)); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Returns whether the specified token exists * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId)); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId)); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * Deprecated, use _burn(uint256) instead * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } contract OathForge is ERC721, ERC721Metadata, Ownable { using SafeMath for uint256; uint256 private _totalSupply; uint256 private _nextTokenId; mapping(uint256 => uint256) private _sunsetInitiatedAt; mapping(uint256 => uint256) private _sunsetLength; mapping(uint256 => uint256) private _redemptionCodeHashSubmittedAt; mapping(uint256 => bytes32) private _redemptionCodeHash; mapping(address => bool) private _isBlacklisted; /// @param name The ERC721 Metadata name /// @param symbol The ERC721 Metadata symbol constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) public {} /// @dev Emits when a sunset has been initiated /// @param tokenId The token id event SunsetInitiated(uint256 indexed tokenId); /// @dev Emits when a redemption code hash has been submitted /// @param tokenId The token id /// @param redemptionCodeHash The redemption code hash event RedemptionCodeHashSubmitted(uint256 indexed tokenId, bytes32 redemptionCodeHash); /// @dev Returns the total number of tokens (minted - burned) registered function totalSupply() external view returns(uint256){ return _totalSupply; } /// @dev Returns the token id of the next minted token function nextTokenId() external view returns(uint256){ return _nextTokenId; } /// @dev Returns if an address is blacklisted /// @param to The address to check function isBlacklisted(address to) external view returns(bool){ return _isBlacklisted[to]; } /// @dev Returns the timestamp at which a token's sunset was initated. Returns 0 if no sunset has been initated. /// @param tokenId The token id function sunsetInitiatedAt(uint256 tokenId) external view returns(uint256){ return _sunsetInitiatedAt[tokenId]; } /// @dev Returns the sunset length of a token /// @param tokenId The token id function sunsetLength(uint256 tokenId) external view returns(uint256){ return _sunsetLength[tokenId]; } /// @dev Returns the redemption code hash submitted for a token /// @param tokenId The token id function redemptionCodeHash(uint256 tokenId) external view returns(bytes32){ return _redemptionCodeHash[tokenId]; } /// @dev Returns the timestamp at which a redemption code hash was submitted /// @param tokenId The token id function redemptionCodeHashSubmittedAt(uint256 tokenId) external view returns(uint256){ return _redemptionCodeHashSubmittedAt[tokenId]; } /// @dev Mint a token. Only `owner` may call this function. /// @param to The receiver of the token /// @param tokenURI The tokenURI of the the tokenURI /// @param __sunsetLength The length (in seconds) that a sunset period can last function mint(address to, string memory tokenURI, uint256 __sunsetLength) public onlyOwner { _mint(to, _nextTokenId); _sunsetLength[_nextTokenId] = __sunsetLength; _setTokenURI(_nextTokenId, tokenURI); _nextTokenId = _nextTokenId.add(1); _totalSupply = _totalSupply.add(1); } /// @dev Initiate a sunset. Sets `sunsetInitiatedAt` to current timestamp. Only `owner` may call this function. /// @param tokenId The id of the token function initiateSunset(uint256 tokenId) external onlyOwner { require(tokenId < _nextTokenId); require(_sunsetInitiatedAt[tokenId] == 0); _sunsetInitiatedAt[tokenId] = now; emit SunsetInitiated(tokenId); } /// @dev Submit a redemption code hash for a specific token. Burns the token. Sets `redemptionCodeHashSubmittedAt` to current timestamp. Decreases `totalSupply` by 1. /// @param tokenId The id of the token /// @param __redemptionCodeHash The redemption code hash function submitRedemptionCodeHash(uint256 tokenId, bytes32 __redemptionCodeHash) external { _burn(msg.sender, tokenId); _redemptionCodeHashSubmittedAt[tokenId] = now; _redemptionCodeHash[tokenId] = __redemptionCodeHash; _totalSupply = _totalSupply.sub(1); emit RedemptionCodeHashSubmitted(tokenId, __redemptionCodeHash); } /// @dev Transfers the ownership of a given token ID to another address. Usage of this method is discouraged, use `safeTransferFrom` whenever possible. Requires the msg sender to be the owner, approved, or operator /// @param from current owner of the token /// @param to address to receive the ownership of the given token ID /// @param tokenId uint256 ID of the token to be transferred function transferFrom(address from, address to, uint256 tokenId) public { require(!_isBlacklisted[to]); if (_sunsetInitiatedAt[tokenId] > 0) { require(now <= _sunsetInitiatedAt[tokenId].add(_sunsetLength[tokenId])); } super.transferFrom(from, to, tokenId); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { require(!_isBlacklisted[to]); super.approve(to, tokenId); } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(!_isBlacklisted[to]); super.setApprovalForAll(to, approved); } /// @dev Set `tokenUri`. Only `owner` may do this. /// @param tokenId The id of the token /// @param tokenURI The token URI function setTokenURI(uint256 tokenId, string calldata tokenURI) external onlyOwner { _setTokenURI(tokenId, tokenURI); } /// @dev Set if an address is blacklisted /// @param to The address to change /// @param __isBlacklisted True if the address should be blacklisted, false otherwise function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner { _isBlacklisted[to] = __isBlacklisted; } } contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } 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); } } contract RiftPact is ERC20, Ownable, ReentrancyGuard { using SafeMath for uint256; uint256 private _parentTokenId; uint256 private _auctionAllowedAt; address private _currencyAddress; address private _parentToken; uint256 private _minAuctionCompleteWait; uint256 private _minBidDeltaPermille; uint256 private _auctionStartedAt; uint256 private _auctionCompletedAt; uint256 private _minBid = 1; uint256 private _topBid; address private _topBidder; uint256 private _topBidSubmittedAt; mapping(address => bool) private _isBlacklisted; /// @param __parentToken The address of the OathForge contract /// @param __parentTokenId The id of the token on the OathForge contract /// @param __totalSupply The total supply /// @param __currencyAddress The address of the currency contract /// @param __auctionAllowedAt The timestamp at which anyone can start an auction /// @param __minAuctionCompleteWait The minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed /// @param __minBidDeltaPermille The minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be constructor( address __parentToken, uint256 __parentTokenId, uint256 __totalSupply, address __currencyAddress, uint256 __auctionAllowedAt, uint256 __minAuctionCompleteWait, uint256 __minBidDeltaPermille ) public { _parentToken = __parentToken; _parentTokenId = __parentTokenId; _currencyAddress = __currencyAddress; _auctionAllowedAt = __auctionAllowedAt; _minAuctionCompleteWait = __minAuctionCompleteWait; _minBidDeltaPermille = __minBidDeltaPermille; _mint(msg.sender, __totalSupply); } /// @dev Emits when an auction is started event AuctionStarted(); /// @dev Emits when the auction is completed /// @param bid The final bid price of the auction /// @param winner The winner of the auction event AuctionCompleted(address winner, uint256 bid); /// @dev Emits when there is a bid /// @param bid The bid /// @param bidder The address of the bidder event Bid(address bidder, uint256 bid); /// @dev Emits when there is a payout /// @param to The address of the account paying out /// @param balance The balance of `to` prior to the paying out event Payout(address to, uint256 balance); /// @dev Returns the OathForge contract address. **UI should check for phishing.**. function parentToken() external view returns(address) { return _parentToken; } /// @dev Returns the OathForge token id. **Does not imply RiftPact has ownership over token.** function parentTokenId() external view returns(uint256) { return _parentTokenId; } /// @dev Returns the currency contract address. function currencyAddress() external view returns(address) { return _currencyAddress; } /// @dev Returns the minimum amount of time (in seconds) between when a bid is placed and when an auction can be completed. function minAuctionCompleteWait() external view returns(uint256) { return _minAuctionCompleteWait; } /// @dev Returns the minimum increase (expressed as 1/1000ths of the current bid) that a subsequent bid must be function minBidDeltaPermille() external view returns(uint256) { return _minBidDeltaPermille; } /// @dev Returns the timestamp at which anyone can start an auction by calling [`startAuction()`](#startAuction()) function auctionAllowedAt() external view returns(uint256) { return _auctionAllowedAt; } /// @dev Returns the minimum bid in currency function minBid() external view returns(uint256) { return _minBid; } /// @dev Returns the timestamp at which an auction was started or 0 if no auction has been started function auctionStartedAt() external view returns(uint256) { return _auctionStartedAt; } /// @dev Returns the timestamp at which an auction was completed or 0 if no auction has been completed function auctionCompletedAt() external view returns(uint256) { return _auctionCompletedAt; } /// @dev Returns the top bid or 0 if no bids have been placed function topBid() external view returns(uint256) { return _topBid; } /// @dev Returns the top bidder or `address(0)` if no bids have been placed function topBidder() external view returns(address) { return _topBidder; } /// @dev Start an auction function startAuction() external nonReentrant { require(_auctionStartedAt == 0); require( (now >= _auctionAllowedAt) || (OathForge(_parentToken).sunsetInitiatedAt(_parentTokenId) > 0) ); emit AuctionStarted(); _auctionStartedAt = now; } /// @dev Submit a bid. Must have sufficient funds approved in currency contract (bid * totalSupply). /// @param bid Bid in currency function submitBid(uint256 bid) external nonReentrant { require(_auctionStartedAt > 0); require(_auctionCompletedAt == 0); require(bid >= _minBid); emit Bid(msg.sender, bid); uint256 _totalSupply = totalSupply(); if (_topBidder != address(0)) { /// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid /* require(ERC20(_currencyAddress).transfer(_topBidder, _topBid * _totalSupply)); */ require(ERC20(_currencyAddress).transfer(_topBidder, _topBid)); } /// NOTE: This has been commented out because it's wrong since we don't want to send the total supply multiplied by the bid /* require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid * _totalSupply)); */ require(ERC20(_currencyAddress).transferFrom(msg.sender, address(this), bid)); _topBid = bid; _topBidder = msg.sender; _topBidSubmittedAt = now; /* 3030 * 10 = 30300 delta = 30300 / 1000 = 30,3 30300 % 1000 = 300 > 0, yes roundUp = 1 minBid = 3030 + 30 + 1 which is wrong, it should be 3060 instead of 3061 */ uint256 minBidNumerator = bid * _minBidDeltaPermille; uint256 minBidDelta = minBidNumerator / 1000; uint256 minBidRoundUp = 0; /// NOTE commented out because it doesn't work as expected with big bids /* if((bid * _minBidDeltaPermille) % 1000 > 0) { minBidRoundUp = 1; } */ if((bid * _minBidDeltaPermille) < 1000) { minBidRoundUp = 1; } _minBid = bid + minBidDelta + minBidRoundUp; } /// @dev Complete auction function completeAuction() external { require(_auctionCompletedAt == 0); require(_topBid > 0); require((_topBidSubmittedAt + _minAuctionCompleteWait) < now); emit AuctionCompleted(_topBidder, _topBid); _auctionCompletedAt = now; } /// @dev Payout `currency` after auction completed function payout() external nonReentrant { uint256 balance = balanceOf(msg.sender); require(balance > 0); require(_auctionCompletedAt > 0); emit Payout(msg.sender, balance); /// NOTE this won't work since we can't send more tokens than what's already in this contract /* require(ERC20(_currencyAddress).transfer(msg.sender, balance * _topBid)); */ require(ERC20(_currencyAddress).transfer(msg.sender, _topBid)); /// NOTE Remove this since the sender doesn't have any riftPact tokens inside this contract so we can't burn them. /* _burn(msg.sender, balance); */ } /// @dev Returns if an address is blacklisted /// @param to The address to check function isBlacklisted(address to) external view returns(bool){ return _isBlacklisted[to]; } /// @dev Set if an address is blacklisted /// @param to The address to change /// @param __isBlacklisted True if the address should be blacklisted, false otherwise function setIsBlacklisted(address to, bool __isBlacklisted) external onlyOwner { _isBlacklisted[to] = __isBlacklisted; } /** * @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(!_isBlacklisted[to]); return super.transfer(to, value); } /** * @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) { require(!_isBlacklisted[to]); return super.transferFrom(from, to, value); } /** * @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) { if (value > 0) { require(!_isBlacklisted[spender]); } return super.approve(spender, value); } /** * @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(!_isBlacklisted[spender]); return super.increaseAllowance(spender, addedValue); } }
Returns the sunset length of a token tokenId The token id
function sunsetLength(uint256 tokenId) external view returns(uint256){ return _sunsetLength[tokenId]; }
5,390,900
// SPDX-License-Identifier: MIT /* Coded for MakerDAO and The Keep3r Network with ♥ by ██████╗░███████╗███████╗██╗  ░██╗░░░░░░░██╗░█████╗░███╗░░██╗██████╗░███████╗██████╗░██╗░░░░░░█████╗░███╗░░██╗██████╗░ ██╔══██╗██╔════╝██╔════╝██║  ░██║░░██╗░░██║██╔══██╗████╗░██║██╔══██╗██╔════╝██╔══██╗██║░░░░░██╔══██╗████╗░██║██╔══██╗ ██║░░██║█████╗░░█████╗░░██║  ░╚██╗████╗██╔╝██║░░██║██╔██╗██║██║░░██║█████╗░░██████╔╝██║░░░░░███████║██╔██╗██║██║░░██║ ██║░░██║██╔══╝░░██╔══╝░░██║  ░░████╔═████║░██║░░██║██║╚████║██║░░██║██╔══╝░░██╔══██╗██║░░░░░██╔══██║██║╚████║██║░░██║ ██████╔╝███████╗██║░░░░░██║  ░░╚██╔╝░╚██╔╝░╚█████╔╝██║░╚███║██████╔╝███████╗██║░░██║███████╗██║░░██║██║░╚███║██████╔╝ ╚═════╝░╚══════╝╚═╝░░░░░╚═╝  ░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚══╝╚═════╝░╚══════╝╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚══╝╚═════╝░ https://defi.sucks */ pragma solidity >=0.8.4 <0.9.0; import './utils/Governable.sol'; import './utils/Keep3rJob.sol'; import './utils/Pausable.sol'; import './utils/DustCollector.sol'; import '../interfaces/external/ISequencer.sol'; import '../interfaces/external/IJob.sol'; import '../interfaces/external/IKeep3rV2.sol'; import '../interfaces/IMakerDAOUpkeep.sol'; contract MakerDAOUpkeep is IMakerDAOUpkeep, Governable, Keep3rJob, Pausable, DustCollector { address public override sequencer = 0x9566eB72e47E3E20643C0b1dfbEe04Da5c7E4732; bytes32 public override network; constructor(address _governor, bytes32 _network) Governable(_governor) Keep3rJob() { network = _network; } function work(address _job, bytes calldata _data) external override validateAndPayKeeper(msg.sender) { if (paused) revert Paused(); if (!ISequencer(sequencer).hasJob(_job)) revert NotValidJob(); IJob(_job).work(network, _data); } function setNetwork(bytes32 _network) external override onlyGovernor { network = _network; emit NetworkSet(network); } function setSequencerAddress(address _sequencer) external override onlyGovernor { sequencer = _sequencer; emit SequencerAddressSet(sequencer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import '../../interfaces/utils/IGovernable.sol'; abstract contract Governable is IGovernable { address public override governor; address public override pendingGovernor; constructor(address _governor) { if (_governor == address(0)) revert ZeroAddress(); governor = _governor; } function setPendingGovernor(address _pendingGovernor) external override onlyGovernor { if (_pendingGovernor == address(0)) revert ZeroAddress(); pendingGovernor = _pendingGovernor; emit PendingGovernorSet(governor, pendingGovernor); } function acceptPendingGovernor() external override onlyPendingGovernor { governor = pendingGovernor; pendingGovernor = address(0); emit PendingGovernorAccepted(governor); } modifier onlyGovernor() { if (msg.sender != governor) revert OnlyGovernor(); _; } modifier onlyPendingGovernor() { if (msg.sender != pendingGovernor) revert OnlyPendingGovernor(); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './Governable.sol'; import '../../interfaces/utils/IKeep3rJob.sol'; import '../../interfaces/external/IKeep3rV2.sol'; import '../../libraries/OracleLibrary.sol'; abstract contract Keep3rJob is IKeep3rJob, Governable { address public override keep3r = 0xdc02981c9C062d48a9bD54adBf51b816623dcc6E; address public override requiredBond = 0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44; uint256 public override requiredMinBond = 50 ether; uint256 public override requiredEarnings; uint256 public override requiredAge; address public override tokenWETHPool = 0x60594a405d53811d3BC4766596EFD80fd545A270; address public override baseToken = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public override quoteToken = 0x6B175474E89094C44Da98b954EedeAC495271d0F; uint256 public override boost = 120; uint32 public override twapTime = 300; function setKeep3r(address _keep3r) public override onlyGovernor { keep3r = _keep3r; emit Keep3rSet(_keep3r); } function setKeep3rRequirements( address _bond, uint256 _minBond, uint256 _earned, uint256 _age ) public override onlyGovernor { requiredBond = _bond; requiredMinBond = _minBond; requiredEarnings = _earned; requiredAge = _age; emit Keep3rRequirementsSet(_bond, _minBond, _earned, _age); } function setTokenWETHPool(address _tokenWETHPool) external override onlyGovernor { tokenWETHPool = _tokenWETHPool; emit TokenWETHPoolAddressSet(tokenWETHPool); } function setBaseToken(address _baseToken) external override onlyGovernor { baseToken = _baseToken; emit BaseTokenAddressSet(baseToken); } function setQuoteToken(address _quoteToken) external override onlyGovernor { quoteToken = _quoteToken; emit QuoteTokenAddressSet(quoteToken); } function setBoost(uint256 _boost) external override onlyGovernor { boost = _boost; emit BoostSet(_boost); } function setTwapTime(uint32 _twapTime) external override onlyGovernor { twapTime = _twapTime; emit TwapTimeSet(twapTime); } function _isValidKeeper(address _keeper) internal { if (!IKeep3rV2(keep3r).isBondedKeeper(_keeper, requiredBond, requiredMinBond, requiredEarnings, requiredAge)) revert KeeperNotValid(); } modifier validateAndPayKeeper(address _keeper) { uint256 _initialGas = gasleft(); _isValidKeeper(_keeper); _; try IKeep3rV2(keep3r).worked(_keeper) {} catch { int24 _twapTick = OracleLibrary.consult(tokenWETHPool, twapTime); uint256 _amount = OracleLibrary.getQuoteAtTick( _twapTick, uint128(((((_initialGas - gasleft()) * block.basefee * boost) / 100))), baseToken, quoteToken ); IKeep3rV2(keep3r).directTokenPayment(quoteToken, _keeper, _amount); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './Governable.sol'; import '../../interfaces/utils/IPausable.sol'; abstract contract Pausable is IPausable, Governable { bool public override paused; function setPause(bool _paused) external override onlyGovernor { if (paused == _paused) revert NoChangeInPause(); paused = _paused; emit PauseSet(_paused); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './Governable.sol'; import '../../interfaces/utils/IDustCollector.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; abstract contract DustCollector is IDustCollector, Governable { using SafeERC20 for IERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function sendDust( address _token, uint256 _amount, address _to ) external override onlyGovernor { if (_to == address(0)) revert ZeroAddress(); if (_token == ETH_ADDRESS) { payable(_to).transfer(_amount); } else { IERC20(_token).safeTransfer(_to, _amount); } emit DustSent(_token, _amount, _to); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; interface ISequencer { struct WorkableJob { address job; bool canWork; bytes args; } event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); event AddNetwork(bytes32 indexed network); event RemoveNetwork(bytes32 indexed network); event AddJob(address indexed job); event RemoveJob(address indexed job); error InvalidFileParam(bytes32 what); error NetworkExists(bytes32 network); error NetworkDoesNotExist(bytes32 network); error JobExists(address job); error JobDoesNotExist(address network); error IndexTooHigh(uint256 index, uint256 length); error BadIndicies(uint256 startIndex, uint256 exclEndIndex); function wards(address) external returns (uint256); function rely(address usr) external; function deny(address usr) external; function window() external returns (uint256); function file(bytes32 what, uint256 data) external; function addNetwork(bytes32 network) external; function removeNetwork(uint256 index) external; function addJob(address job) external; function removeJob(uint256 index) external; function isMaster(bytes32 _network) external view returns (bool _isMaster); function numNetworks() external view returns (uint256); function hasNetwork() external view returns (bool); function networkAt(uint256 index) external view returns (bytes32); function numJobs() external view returns (uint256); function hasJob(address job) external returns (bool); function jobAt(uint256 index) external view returns (address); function getNextJobs( bytes32 network, uint256 startIndex, uint256 endIndexExcl ) external returns (WorkableJob[] memory); function getNextJobs(bytes32 network) external returns (WorkableJob[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; interface IJob { function work(bytes32 network, bytes calldata args) external; function workable(bytes32 network) external returns (bool canWork, bytes memory args); } pragma solidity >=0.8.4 <0.9.0; interface IKeep3rV2 { /// @notice Stores the tick information of the different liquidity pairs struct TickCache { int56 current; // Tracks the current tick int56 difference; // Stores the difference between the current tick and the last tick uint256 period; // Stores the period at which the last observation was made } // Events /// @notice Emitted when the Keep3rHelper address is changed /// @param _keep3rHelper The address of Keep3rHelper's contract event Keep3rHelperChange(address _keep3rHelper); /// @notice Emitted when the Keep3rV1 address is changed /// @param _keep3rV1 The address of Keep3rV1's contract event Keep3rV1Change(address _keep3rV1); /// @notice Emitted when the Keep3rV1Proxy address is changed /// @param _keep3rV1Proxy The address of Keep3rV1Proxy's contract event Keep3rV1ProxyChange(address _keep3rV1Proxy); /// @notice Emitted when the KP3R-WETH pool address is changed /// @param _kp3rWethPool The address of the KP3R-WETH pool event Kp3rWethPoolChange(address _kp3rWethPool); /// @notice Emitted when bondTime is changed /// @param _bondTime The new bondTime event BondTimeChange(uint256 _bondTime); /// @notice Emitted when _liquidityMinimum is changed /// @param _liquidityMinimum The new _liquidityMinimum event LiquidityMinimumChange(uint256 _liquidityMinimum); /// @notice Emitted when _unbondTime is changed /// @param _unbondTime The new _unbondTime event UnbondTimeChange(uint256 _unbondTime); /// @notice Emitted when _rewardPeriodTime is changed /// @param _rewardPeriodTime The new _rewardPeriodTime event RewardPeriodTimeChange(uint256 _rewardPeriodTime); /// @notice Emitted when the inflationPeriod is changed /// @param _inflationPeriod The new inflationPeriod event InflationPeriodChange(uint256 _inflationPeriod); /// @notice Emitted when the fee is changed /// @param _fee The new token credits fee event FeeChange(uint256 _fee); /// @notice Emitted when a slasher is added /// @param _slasher Address of the added slasher event SlasherAdded(address _slasher); /// @notice Emitted when a slasher is removed /// @param _slasher Address of the removed slasher event SlasherRemoved(address _slasher); /// @notice Emitted when a disputer is added /// @param _disputer Address of the added disputer event DisputerAdded(address _disputer); /// @notice Emitted when a disputer is removed /// @param _disputer Address of the removed disputer event DisputerRemoved(address _disputer); /// @notice Emitted when the bonding process of a new keeper begins /// @param _keeper The caller of Keep3rKeeperFundable#bond function /// @param _bonding The asset the keeper has bonded /// @param _amount The amount the keeper has bonded event Bonding(address indexed _keeper, address indexed _bonding, uint256 _amount); /// @notice Emitted when a keeper or job begins the unbonding process to withdraw the funds /// @param _keeperOrJob The keeper or job that began the unbonding process /// @param _unbonding The liquidity pair or asset being unbonded /// @param _amount The amount being unbonded event Unbonding(address indexed _keeperOrJob, address indexed _unbonding, uint256 _amount); /// @notice Emitted when Keep3rKeeperFundable#activate is called /// @param _keeper The keeper that has been activated /// @param _bond The asset the keeper has bonded /// @param _amount The amount of the asset the keeper has bonded event Activation(address indexed _keeper, address indexed _bond, uint256 _amount); /// @notice Emitted when Keep3rKeeperFundable#withdraw is called /// @param _keeper The caller of Keep3rKeeperFundable#withdraw function /// @param _bond The asset to withdraw from the bonding pool /// @param _amount The amount of funds withdrawn event Withdrawal(address indexed _keeper, address indexed _bond, uint256 _amount); /// @notice Emitted when Keep3rKeeperDisputable#slash is called /// @param _keeper The slashed keeper /// @param _slasher The user that called Keep3rKeeperDisputable#slash /// @param _amount The amount of credits slashed from the keeper event KeeperSlash(address indexed _keeper, address indexed _slasher, uint256 _amount); /// @notice Emitted when Keep3rKeeperDisputable#revoke is called /// @param _keeper The revoked keeper /// @param _slasher The user that called Keep3rKeeperDisputable#revoke event KeeperRevoke(address indexed _keeper, address indexed _slasher); /// @notice Emitted when Keep3rJobFundableCredits#addTokenCreditsToJob is called /// @param _job The address of the job being credited /// @param _token The address of the token being provided /// @param _provider The user that calls the function /// @param _amount The amount of credit being added to the job event TokenCreditAddition(address indexed _job, address indexed _token, address indexed _provider, uint256 _amount); /// @notice Emitted when Keep3rJobFundableCredits#withdrawTokenCreditsFromJob is called /// @param _job The address of the job from which the credits are withdrawn /// @param _token The credit being withdrawn from the job /// @param _receiver The user that receives the tokens /// @param _amount The amount of credit withdrawn event TokenCreditWithdrawal(address indexed _job, address indexed _token, address indexed _receiver, uint256 _amount); /// @notice Emitted when Keep3rJobFundableLiquidity#approveLiquidity function is called /// @param _liquidity The address of the liquidity pair being approved event LiquidityApproval(address _liquidity); /// @notice Emitted when Keep3rJobFundableLiquidity#revokeLiquidity function is called /// @param _liquidity The address of the liquidity pair being revoked event LiquidityRevocation(address _liquidity); /// @notice Emitted when IKeep3rJobFundableLiquidity#addLiquidityToJob function is called /// @param _job The address of the job to which liquidity will be added /// @param _liquidity The address of the liquidity being added /// @param _provider The user that calls the function /// @param _amount The amount of liquidity being added event LiquidityAddition(address indexed _job, address indexed _liquidity, address indexed _provider, uint256 _amount); /// @notice Emitted when IKeep3rJobFundableLiquidity#withdrawLiquidityFromJob function is called /// @param _job The address of the job of which liquidity will be withdrawn from /// @param _liquidity The address of the liquidity being withdrawn /// @param _receiver The receiver of the liquidity tokens /// @param _amount The amount of liquidity being withdrawn from the job event LiquidityWithdrawal(address indexed _job, address indexed _liquidity, address indexed _receiver, uint256 _amount); /// @notice Emitted when Keep3rJobFundableLiquidity#addLiquidityToJob function is called /// @param _job The address of the job whose credits will be updated /// @param _rewardedAt The time at which the job was last rewarded /// @param _currentCredits The current credits of the job /// @param _periodCredits The credits of the job for the current period event LiquidityCreditsReward(address indexed _job, uint256 _rewardedAt, uint256 _currentCredits, uint256 _periodCredits); /// @notice Emitted when Keep3rJobFundableLiquidity#forceLiquidityCreditsToJob function is called /// @param _job The address of the job whose credits will be updated /// @param _rewardedAt The time at which the job was last rewarded /// @param _currentCredits The current credits of the job event LiquidityCreditsForced(address indexed _job, uint256 _rewardedAt, uint256 _currentCredits); /// @notice Emitted when Keep3rJobManager#addJob is called /// @param _job The address of the job to add /// @param _jobOwner The job's owner event JobAddition(address indexed _job, address indexed _jobOwner); /// @notice Emitted when a keeper is validated before a job /// @param _gasLeft The amount of gas that the transaction has left at the moment of keeper validation event KeeperValidation(uint256 _gasLeft); /// @notice Emitted when a keeper works a job /// @param _credit The address of the asset in which the keeper is paid /// @param _job The address of the job the keeper has worked /// @param _keeper The address of the keeper that has worked the job /// @param _amount The amount that has been paid out to the keeper in exchange for working the job /// @param _gasLeft The amount of gas that the transaction has left at the moment of payment event KeeperWork(address indexed _credit, address indexed _job, address indexed _keeper, uint256 _amount, uint256 _gasLeft); /// @notice Emitted when Keep3rJobOwnership#changeJobOwnership is called /// @param _job The address of the job proposed to have a change of owner /// @param _owner The current owner of the job /// @param _pendingOwner The new address proposed to be the owner of the job event JobOwnershipChange(address indexed _job, address indexed _owner, address indexed _pendingOwner); /// @notice Emitted when Keep3rJobOwnership#JobOwnershipAssent is called /// @param _job The address of the job which the proposed owner will now own /// @param _previousOwner The previous owner of the job /// @param _newOwner The newowner of the job event JobOwnershipAssent(address indexed _job, address indexed _previousOwner, address indexed _newOwner); /// @notice Emitted when Keep3rJobMigration#migrateJob function is called /// @param _fromJob The address of the job that requests to migrate /// @param _toJob The address at which the job requests to migrate event JobMigrationRequested(address indexed _fromJob, address _toJob); /// @notice Emitted when Keep3rJobMigration#acceptJobMigration function is called /// @param _fromJob The address of the job that requested to migrate /// @param _toJob The address at which the job had requested to migrate event JobMigrationSuccessful(address _fromJob, address indexed _toJob); /// @notice Emitted when Keep3rJobDisputable#slashTokenFromJob is called /// @param _job The address of the job from which the token will be slashed /// @param _token The address of the token being slashed /// @param _slasher The user that slashes the token /// @param _amount The amount of the token being slashed event JobSlashToken(address indexed _job, address _token, address indexed _slasher, uint256 _amount); /// @notice Emitted when Keep3rJobDisputable#slashLiquidityFromJob is called /// @param _job The address of the job from which the liquidity will be slashed /// @param _liquidity The address of the liquidity being slashed /// @param _slasher The user that slashes the liquidity /// @param _amount The amount of the liquidity being slashed event JobSlashLiquidity(address indexed _job, address _liquidity, address indexed _slasher, uint256 _amount); /// @notice Emitted when a keeper or a job is disputed /// @param _jobOrKeeper The address of the disputed keeper/job /// @param _disputer The user that called the function and disputed the keeper event Dispute(address indexed _jobOrKeeper, address indexed _disputer); /// @notice Emitted when a dispute is resolved /// @param _jobOrKeeper The address of the disputed keeper/job /// @param _resolver The user that called the function and resolved the dispute event Resolve(address indexed _jobOrKeeper, address indexed _resolver); // Errors /// @notice Throws if the reward period is less than the minimum reward period time error MinRewardPeriod(); /// @notice Throws if either a job or a keeper is disputed error Disputed(); /// @notice Throws if there are no bonded assets error BondsUnexistent(); /// @notice Throws if the time required to bond an asset has not passed yet error BondsLocked(); /// @notice Throws if there are no bonds to withdraw error UnbondsUnexistent(); /// @notice Throws if the time required to withdraw the bonds has not passed yet error UnbondsLocked(); /// @notice Throws if the address is already a registered slasher error SlasherExistent(); /// @notice Throws if caller is not a registered slasher error SlasherUnexistent(); /// @notice Throws if the address is already a registered disputer error DisputerExistent(); /// @notice Throws if caller is not a registered disputer error DisputerUnexistent(); /// @notice Throws if the msg.sender is not a slasher or is not a part of governance error OnlySlasher(); /// @notice Throws if the msg.sender is not a disputer or is not a part of governance error OnlyDisputer(); /// @notice Throws when an address is passed as a job, but that address is not a job error JobUnavailable(); /// @notice Throws when an action that requires an undisputed job is applied on a disputed job error JobDisputed(); /// @notice Throws when the address that is trying to register as a job is already a job error AlreadyAJob(); /// @notice Throws when the token is KP3R, as it should not be used for direct token payments error TokenUnallowed(); /// @notice Throws when the token withdraw cooldown has not yet passed error JobTokenCreditsLocked(); /// @notice Throws when the user tries to withdraw more tokens than it has error InsufficientJobTokenCredits(); /// @notice Throws when trying to add a job that has already been added error JobAlreadyAdded(); /// @notice Throws when the address that is trying to register as a keeper is already a keeper error AlreadyAKeeper(); /// @notice Throws when the liquidity being approved has already been approved error LiquidityPairApproved(); /// @notice Throws when the liquidity being removed has not been approved error LiquidityPairUnexistent(); /// @notice Throws when trying to add liquidity to an unapproved pool error LiquidityPairUnapproved(); /// @notice Throws when the job doesn't have the requested liquidity error JobLiquidityUnexistent(); /// @notice Throws when trying to remove more liquidity than the job has error JobLiquidityInsufficient(); /// @notice Throws when trying to add less liquidity than the minimum liquidity required error JobLiquidityLessThanMin(); /// @notice Throws if a variable is assigned to the zero address error ZeroAddress(); /// @notice Throws if the address claiming to be a job is not in the list of approved jobs error JobUnapproved(); /// @notice Throws if the amount of funds in the job is less than the payment that must be paid to the keeper that works that job error InsufficientFunds(); /// @notice Throws when the caller of the function is not the job owner error OnlyJobOwner(); /// @notice Throws when the caller of the function is not the pending job owner error OnlyPendingJobOwner(); /// @notice Throws when the address of the job that requests to migrate wants to migrate to its same address error JobMigrationImpossible(); /// @notice Throws when the _toJob address differs from the address being tracked in the pendingJobMigrations mapping error JobMigrationUnavailable(); /// @notice Throws when cooldown between migrations has not yet passed error JobMigrationLocked(); /// @notice Throws when the token trying to be slashed doesn't exist error JobTokenUnexistent(); /// @notice Throws when someone tries to slash more tokens than the job has error JobTokenInsufficient(); /// @notice Throws when a job or keeper is already disputed error AlreadyDisputed(); /// @notice Throws when a job or keeper is not disputed and someone tries to resolve the dispute error NotDisputed(); // Variables /// @notice Address of Keep3rHelper's contract /// @return _keep3rHelper The address of Keep3rHelper's contract function keep3rHelper() external view returns (address _keep3rHelper); /// @notice Address of Keep3rV1's contract /// @return _keep3rV1 The address of Keep3rV1's contract function keep3rV1() external view returns (address _keep3rV1); /// @notice Address of Keep3rV1Proxy's contract /// @return _keep3rV1Proxy The address of Keep3rV1Proxy's contract function keep3rV1Proxy() external view returns (address _keep3rV1Proxy); /// @notice Address of the KP3R-WETH pool /// @return _kp3rWethPool The address of KP3R-WETH pool function kp3rWethPool() external view returns (address _kp3rWethPool); /// @notice The amount of time required to pass after a keeper has bonded assets for it to be able to activate /// @return _days The required bondTime in days function bondTime() external view returns (uint256 _days); /// @notice The amount of time required to pass before a keeper can unbond what he has bonded /// @return _days The required unbondTime in days function unbondTime() external view returns (uint256 _days); /// @notice The minimum amount of liquidity required to fund a job per liquidity /// @return _amount The minimum amount of liquidity in KP3R function liquidityMinimum() external view returns (uint256 _amount); /// @notice The amount of time between each scheduled credits reward given to a job /// @return _days The reward period in days function rewardPeriodTime() external view returns (uint256 _days); /// @notice The inflation period is the denominator used to regulate the emission of KP3R /// @return _period The denominator used to regulate the emission of KP3R function inflationPeriod() external view returns (uint256 _period); /// @notice The fee to be sent to governance when a user adds liquidity to a job /// @return _amount The fee amount to be sent to governance when a user adds liquidity to a job function fee() external view returns (uint256 _amount); // solhint-disable func-name-mixedcase /// @notice The base that will be used to calculate the fee /// @return _base The base that will be used to calculate the fee function BASE() external view returns (uint256 _base); /// @notice The minimum rewardPeriodTime value to be set /// @return _minPeriod The minimum reward period in seconds function MIN_REWARD_PERIOD_TIME() external view returns (uint256 _minPeriod); /// @notice Maps an address to a boolean to determine whether the address is a slasher or not. /// @return _isSlasher Whether the address is a slasher or not function slashers(address _slasher) external view returns (bool _isSlasher); /// @notice Maps an address to a boolean to determine whether the address is a disputer or not. /// @return _isDisputer Whether the address is a disputer or not function disputers(address _disputer) external view returns (bool _isDisputer); /// @notice Tracks the total KP3R earnings of a keeper since it started working /// @return _workCompleted Total KP3R earnings of a keeper since it started working function workCompleted(address _keeper) external view returns (uint256 _workCompleted); /// @notice Tracks when a keeper was first registered /// @return timestamp The time at which the keeper was first registered function firstSeen(address _keeper) external view returns (uint256 timestamp); /// @notice Tracks if a keeper or job has a pending dispute /// @return _disputed Whether a keeper or job has a pending dispute function disputes(address _keeperOrJob) external view returns (bool _disputed); /// @notice Allows governance to create a dispute for a given keeper/job /// @param _jobOrKeeper The address in dispute function dispute(address _jobOrKeeper) external; /// @notice Allows governance to resolve a dispute on a keeper/job /// @param _jobOrKeeper The address cleared function resolve(address _jobOrKeeper) external; /// @notice Tracks how much a keeper has bonded of a certain token /// @return _bonds Amount of a certain token that a keeper has bonded function bonds(address _keeper, address _bond) external view returns (uint256 _bonds); /// @notice The current token credits available for a job /// @return _amount The amount of token credits available for a job function jobTokenCredits(address _job, address _token) external view returns (uint256 _amount); /// @notice Tracks the amount of assets deposited in pending bonds /// @return _pendingBonds Amount of a certain asset a keeper has unbonding function pendingBonds(address _keeper, address _bonding) external view returns (uint256 _pendingBonds); /// @notice Tracks when a bonding for a keeper can be activated /// @return _timestamp Time at which the bonding for a keeper can be activated function canActivateAfter(address _keeper, address _bonding) external view returns (uint256 _timestamp); /// @notice Tracks when keeper bonds are ready to be withdrawn /// @return _timestamp Time at which the keeper bonds are ready to be withdrawn function canWithdrawAfter(address _keeper, address _bonding) external view returns (uint256 _timestamp); /// @notice Tracks how much keeper bonds are to be withdrawn /// @return _pendingUnbonds The amount of keeper bonds that are to be withdrawn function pendingUnbonds(address _keeper, address _bonding) external view returns (uint256 _pendingUnbonds); /// @notice Checks whether the address has ever bonded an asset /// @return _hasBonded Whether the address has ever bonded an asset function hasBonded(address _keeper) external view returns (bool _hasBonded); /// @notice Last block where tokens were added to the job [job => token => timestamp] /// @return _timestamp The last block where tokens were added to the job function jobTokenCreditsAddedAt(address _job, address _token) external view returns (uint256 _timestamp); // Methods /// @notice Add credit to a job to be paid out for work /// @param _job The address of the job being credited /// @param _token The address of the token being credited /// @param _amount The amount of credit being added function addTokenCreditsToJob( address _job, address _token, uint256 _amount ) external; /// @notice Withdraw credit from a job /// @param _job The address of the job from which the credits are withdrawn /// @param _token The address of the token being withdrawn /// @param _amount The amount of token to be withdrawn /// @param _receiver The user that will receive tokens function withdrawTokenCreditsFromJob( address _job, address _token, uint256 _amount, address _receiver ) external; /// @notice Lists liquidity pairs /// @return _list An array of addresses with all the approved liquidity pairs function approvedLiquidities() external view returns (address[] memory _list); /// @notice Amount of liquidity in a specified job /// @param _job The address of the job being checked /// @param _liquidity The address of the liquidity we are checking /// @return _amount Amount of liquidity in the specified job function liquidityAmount(address _job, address _liquidity) external view returns (uint256 _amount); /// @notice Last time the job was rewarded liquidity credits /// @param _job The address of the job being checked /// @return _timestamp Timestamp of the last time the job was rewarded liquidity credits function rewardedAt(address _job) external view returns (uint256 _timestamp); /// @notice Last time the job was worked /// @param _job The address of the job being checked /// @return _timestamp Timestamp of the last time the job was worked function workedAt(address _job) external view returns (uint256 _timestamp); /// @notice Maps the job to the owner of the job (job => user) /// @return _owner The addres of the owner of the job function jobOwner(address _job) external view returns (address _owner); /// @notice Maps the owner of the job to its pending owner (job => user) /// @return _pendingOwner The address of the pending owner of the job function jobPendingOwner(address _job) external view returns (address _pendingOwner); /// @notice Maps the jobs that have requested a migration to the address they have requested to migrate to /// @return _toJob The address to which the job has requested to migrate to function pendingJobMigrations(address _fromJob) external view returns (address _toJob); // Methods /// @notice Sets the Keep3rHelper address /// @param _keep3rHelper The Keep3rHelper address function setKeep3rHelper(address _keep3rHelper) external; /// @notice Sets the Keep3rV1 address /// @param _keep3rV1 The Keep3rV1 address function setKeep3rV1(address _keep3rV1) external; /// @notice Sets the Keep3rV1Proxy address /// @param _keep3rV1Proxy The Keep3rV1Proxy address function setKeep3rV1Proxy(address _keep3rV1Proxy) external; /// @notice Sets the KP3R-WETH pool address /// @param _kp3rWethPool The KP3R-WETH pool address function setKp3rWethPool(address _kp3rWethPool) external; /// @notice Sets the bond time required to activate as a keeper /// @param _bond The new bond time function setBondTime(uint256 _bond) external; /// @notice Sets the unbond time required unbond what has been bonded /// @param _unbond The new unbond time function setUnbondTime(uint256 _unbond) external; /// @notice Sets the minimum amount of liquidity required to fund a job /// @param _liquidityMinimum The new minimum amount of liquidity function setLiquidityMinimum(uint256 _liquidityMinimum) external; /// @notice Sets the time required to pass between rewards for jobs /// @param _rewardPeriodTime The new amount of time required to pass between rewards function setRewardPeriodTime(uint256 _rewardPeriodTime) external; /// @notice Sets the new inflation period /// @param _inflationPeriod The new inflation period function setInflationPeriod(uint256 _inflationPeriod) external; /// @notice Sets the new fee /// @param _fee The new fee function setFee(uint256 _fee) external; /// @notice Registers a slasher by updating the slashers mapping function addSlasher(address _slasher) external; /// @notice Removes a slasher by updating the slashers mapping function removeSlasher(address _slasher) external; /// @notice Registers a disputer by updating the disputers mapping function addDisputer(address _disputer) external; /// @notice Removes a disputer by updating the disputers mapping function removeDisputer(address _disputer) external; /// @notice Lists all jobs /// @return _jobList Array with all the jobs in _jobs function jobs() external view returns (address[] memory _jobList); /// @notice Lists all keepers /// @return _keeperList Array with all the jobs in keepers function keepers() external view returns (address[] memory _keeperList); /// @notice Beginning of the bonding process /// @param _bonding The asset being bound /// @param _amount The amount of bonding asset being bound function bond(address _bonding, uint256 _amount) external; /// @notice Beginning of the unbonding process /// @param _bonding The asset being unbound /// @param _amount Allows for partial unbonding function unbond(address _bonding, uint256 _amount) external; /// @notice End of the bonding process after bonding time has passed /// @param _bonding The asset being activated as bond collateral function activate(address _bonding) external; /// @notice Withdraw funds after unbonding has finished /// @param _bonding The asset to withdraw from the bonding pool function withdraw(address _bonding) external; /// @notice Allows governance to slash a keeper based on a dispute /// @param _keeper The address being slashed /// @param _bonded The asset being slashed /// @param _amount The amount being slashed function slash( address _keeper, address _bonded, uint256 _amount ) external; /// @notice Blacklists a keeper from participating in the network /// @param _keeper The address being slashed function revoke(address _keeper) external; /// @notice Allows any caller to add a new job /// @param _job Address of the contract for which work should be performed function addJob(address _job) external; /// @notice Returns the liquidity credits of a given job /// @param _job The address of the job of which we want to know the liquidity credits /// @return _amount The liquidity credits of a given job function jobLiquidityCredits(address _job) external view returns (uint256 _amount); /// @notice Returns the credits of a given job for the current period /// @param _job The address of the job of which we want to know the period credits /// @return _amount The credits the given job has at the current period function jobPeriodCredits(address _job) external view returns (uint256 _amount); /// @notice Calculates the total credits of a given job /// @param _job The address of the job of which we want to know the total credits /// @return _amount The total credits of the given job function totalJobCredits(address _job) external view returns (uint256 _amount); /// @notice Calculates how many credits should be rewarded periodically for a given liquidity amount /// @dev _periodCredits = underlying KP3Rs for given liquidity amount * rewardPeriod / inflationPeriod /// @param _liquidity The liquidity to provide /// @param _amount The amount of liquidity to provide /// @return _periodCredits The amount of KP3R periodically minted for the given liquidity function quoteLiquidity(address _liquidity, uint256 _amount) external view returns (uint256 _periodCredits); /// @notice Observes the current state of the liquidity pair being observed and updates TickCache with the information /// @param _liquidity The liquidity pair being observed /// @return _tickCache The updated TickCache function observeLiquidity(address _liquidity) external view returns (TickCache memory _tickCache); /// @notice Gifts liquidity credits to the specified job /// @param _job The address of the job being credited /// @param _amount The amount of liquidity credits to gift function forceLiquidityCreditsToJob(address _job, uint256 _amount) external; /// @notice Approve a liquidity pair for being accepted in future /// @param _liquidity The address of the liquidity accepted function approveLiquidity(address _liquidity) external; /// @notice Revoke a liquidity pair from being accepted in future /// @param _liquidity The liquidity no longer accepted function revokeLiquidity(address _liquidity) external; /// @notice Allows anyone to fund a job with liquidity /// @param _job The address of the job to assign liquidity to /// @param _liquidity The liquidity being added /// @param _amount The amount of liquidity tokens to add function addLiquidityToJob( address _job, address _liquidity, uint256 _amount ) external; /// @notice Unbond liquidity for a job /// @dev Can only be called by the job's owner /// @param _job The address of the job being unbound from /// @param _liquidity The liquidity being unbound /// @param _amount The amount of liquidity being removed function unbondLiquidityFromJob( address _job, address _liquidity, uint256 _amount ) external; /// @notice Withdraw liquidity from a job /// @param _job The address of the job being withdrawn from /// @param _liquidity The liquidity being withdrawn /// @param _receiver The address that will receive the withdrawn liquidity function withdrawLiquidityFromJob( address _job, address _liquidity, address _receiver ) external; /// @notice Confirms if the current keeper is registered, can be used for general (non critical) functions /// @param _keeper The keeper being investigated /// @return _isKeeper Whether the address passed as a parameter is a keeper or not function isKeeper(address _keeper) external returns (bool _isKeeper); /// @notice Confirms if the current keeper is registered and has a minimum bond of any asset. Should be used for protected functions /// @param _keeper The keeper to check /// @param _bond The bond token being evaluated /// @param _minBond The minimum amount of bonded tokens /// @param _earned The minimum funds earned in the keepers lifetime /// @param _age The minimum keeper age required /// @return _isBondedKeeper Whether the `_keeper` meets the given requirements function isBondedKeeper( address _keeper, address _bond, uint256 _minBond, uint256 _earned, uint256 _age ) external returns (bool _isBondedKeeper); /// @notice Implemented by jobs to show that a keeper performed work /// @dev Automatically calculates the payment for the keeper /// @param _keeper Address of the keeper that performed the work function worked(address _keeper) external; /// @notice Implemented by jobs to show that a keeper performed work /// @dev Pays the keeper that performs the work with KP3R /// @param _keeper Address of the keeper that performed the work /// @param _payment The reward that should be allocated for the job function bondedPayment(address _keeper, uint256 _payment) external; /// @notice Implemented by jobs to show that a keeper performed work /// @dev Pays the keeper that performs the work with a specific token /// @param _token The asset being awarded to the keeper /// @param _keeper Address of the keeper that performed the work /// @param _amount The reward that should be allocated function directTokenPayment( address _token, address _keeper, uint256 _amount ) external; /// @notice Proposes a new address to be the owner of the job function changeJobOwnership(address _job, address _newOwner) external; /// @notice The proposed address accepts to be the owner of the job function acceptJobOwnership(address _job) external; /// @notice Initializes the migration process for a job by adding the request to the pendingJobMigrations mapping /// @param _fromJob The address of the job that is requesting to migrate /// @param _toJob The address at which the job is requesting to migrate function migrateJob(address _fromJob, address _toJob) external; /// @notice Completes the migration process for a job /// @dev Unbond/withdraw process doesn't get migrated /// @param _fromJob The address of the job that requested to migrate /// @param _toJob The address to which the job wants to migrate to function acceptJobMigration(address _fromJob, address _toJob) external; /// @notice Allows governance or slasher to slash a job specific token /// @param _job The address of the job from which the token will be slashed /// @param _token The address of the token that will be slashed /// @param _amount The amount of the token that will be slashed function slashTokenFromJob( address _job, address _token, uint256 _amount ) external; /// @notice Allows governance or a slasher to slash liquidity from a job /// @param _job The address being slashed /// @param _liquidity The address of the liquidity that will be slashed /// @param _amount The amount of liquidity that will be slashed function slashLiquidityFromJob( address _job, address _liquidity, uint256 _amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './utils/IGovernable.sol'; import './utils/IKeep3rJob.sol'; import './utils/IPausable.sol'; import './utils/IDustCollector.sol'; interface IMakerDAOUpkeep is IGovernable, IPausable, IKeep3rJob, IDustCollector { // event event NetworkSet(bytes32 _newNetwork); event SequencerAddressSet(address _newSequencerAddress); // errors error AvailableCredits(); error Paused(); error CallFailed(); error NotValidJob(); // variables function network() external returns (bytes32 _network); function sequencer() external returns (address _sequencer); // methods function work(address _job, bytes calldata _data) external; function setNetwork(bytes32 _network) external; function setSequencerAddress(address _sequencer) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './IBaseErrors.sol'; interface IGovernable is IBaseErrors { // events event PendingGovernorSet(address _governor, address _pendingGovernor); event PendingGovernorAccepted(address _newGovernor); // errors error OnlyGovernor(); error OnlyPendingGovernor(); // variables function governor() external view returns (address _governor); function pendingGovernor() external view returns (address _pendingGovernor); // methods function setPendingGovernor(address _pendingGovernor) external; function acceptPendingGovernor() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; interface IBaseErrors { /// @notice Throws if a variable is assigned to the zero address error ZeroAddress(); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './IGovernable.sol'; interface IKeep3rJob is IGovernable { // events event Keep3rSet(address _keep3r); event Keep3rRequirementsSet(address _bond, uint256 _minBond, uint256 _earned, uint256 _age); event TokenPaymentAddressSet(address _newTokenPaymentAddress); event TokenWETHPoolAddressSet(address _newTokenWETHPool); event BaseTokenAddressSet(address _newBaseToken); event QuoteTokenAddressSet(address _newQuoteToken); event BoostSet(uint256 _newBoost); event TwapTimeSet(uint256 _twapTime); // errors error KeeperNotRegistered(); error KeeperNotValid(); // variables function keep3r() external view returns (address _keep3r); function requiredBond() external view returns (address _requiredBond); function requiredMinBond() external view returns (uint256 _requiredMinBond); function requiredEarnings() external view returns (uint256 _requiredEarnings); function requiredAge() external view returns (uint256 _requiredAge); function tokenWETHPool() external returns (address _tokenWETHPool); function baseToken() external returns (address _baseToken); function quoteToken() external returns (address _quoteToken); function boost() external returns (uint256 _boost); function twapTime() external returns (uint32 _twapTime); // methods function setKeep3r(address _keep3r) external; function setKeep3rRequirements( address _bond, uint256 _minBond, uint256 _earned, uint256 _age ) external; function setTokenWETHPool(address _tokenWETHPool) external; function setBaseToken(address _baseToken) external; function setQuoteToken(address _quoteToken) external; function setBoost(uint256 _boost) external; function setTwapTime(uint32 _twapTime) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import './FullMath.sol'; import './TickMath.sol'; /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Fetches time-weighted average tick using Uniswap V3 oracle /// @param pool Address of Uniswap V3 pool that we want to observe /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / int256(uint256(period))); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int256(uint256(period)) != 0)) timeWeightedAverageTick--; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } } // 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: MIT pragma solidity >=0.8.4 <0.9.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) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (~denominator + 1) & 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) { unchecked { 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.5.0; // solhint-disable /// @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(int256(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; // 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: 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 liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './IGovernable.sol'; interface IPausable is IGovernable { // events event PauseSet(bool _paused); // errors error NoChangeInPause(); // variables function paused() external view returns (bool _paused); // methods function setPause(bool _paused) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4 <0.9.0; import './IGovernable.sol'; interface IDustCollector is IGovernable { /// @notice Emitted when dust is sent /// @param _to The address which wil received the funds /// @param _token The token that will be transferred /// @param _amount The amount of the token that will be transferred event DustSent(address _token, uint256 _amount, address _to); /// @notice Allows an authorized user to transfer the tokens or eth that may have been left in a contract /// @param _token The token that will be transferred /// @param _amount The amont of the token that will be transferred /// @param _to The address that will receive the idle funds function sendDust( address _token, uint256 _amount, address _to ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
events errors variables methods
interface IPausable is IGovernable { event PauseSet(bool _paused); error NoChangeInPause(); function paused() external view returns (bool _paused); function setPause(bool _paused) external; } pragma solidity >=0.8.4 <0.9.0; }
947,560
./full_match/3/0xb9B76944685Dcf1F83a2f28D70beE859B501180f/sources/contracts/kontrakt.sol
always return the id if this isn't an lp token, don't even bother calling getLpData this is an lp token, so let's get some data
function getLpData() external view returns ( bool hasLpData, uint40 id, address token0, address token1, uint256 balance0, uint256 balance1, uint256 price0, uint256 price1 ) { id = _id; if (!_isLpToken) { hasLpData = false; try Util.getLpData(address(_token)) returns ( address token0_, address token1_, uint256 balance0_, uint256 balance1_, uint256 price0_, uint256 price1_ ){ hasLpData = true; token0 = token0_; token1 = token1_; balance0 = balance0_; balance1 = balance1_; price0 = price0_; price1 = price1_; hasLpData = false; hasLpData = false; } } }
14,243,205
pragma solidity ^0.4.24; contract RSEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularRatScam is RSEvents {} contract RatScam is modularRatScam { using SafeMath for *; using NameFilter for string; using RSKeysCalc for uint256; RatBookInterface constant private RatBook = RatBookInterface(0x3257d637B8977781B4f8178365858A474b2A6195); string constant public name = "RatScam In One Hour"; string constant public symbol = "RS"; uint256 private rndGap_ = 0; uint256 private rndInit_ = 1 hours; // round timer starts at this uint256 private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 private rndMax_ = 1 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** address private adminAddress; mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => RSdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** //RSdatasets.Round public round_; // round data mapping (uint256 => RSdatasets.Round) public round_; // (rID => data) round data //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 60; // fee distribution uint256 public potSplit_ = 45; // pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { adminAddress = msg.sender; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (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 ratscam */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "non smart contract address only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data RSdatasets.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 RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _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 RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now)); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[rID_].keys, //0 round_[rID_].end, //1 round_[rID_].strt, //2 round_[rID_].pot, //3 round_[rID_].plyr, //4 plyr_[round_[rID_].plyr].addr, //5 plyr_[round_[rID_].plyr].name, //6 airDropTracker_ + (airDropPot_ * 1000) //7 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is end, fire endRound 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 RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } _rID = rID_; core(_rID, _pID, msg.value, _affID, _eventData_); } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is end, fire endRound 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 RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _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, _affID, _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 _affID, RSdatasets.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) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).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; // 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 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // 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); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rID) private view returns(uint256) { return((((round_[_rID].mask).mul(plyrRnds_[_pID][_rID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rID].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _eth) public view returns(uint256) { 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].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(RatBook), "only RatBook can call this function"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(RatBook), "only RatBook can call this function"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of ratscam if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = RatBook.getPlayerID(msg.sender); bytes32 _name = RatBook.getPlayerName(_pID); uint256 _laff = RatBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev 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, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.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(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; // grab our pot amount // add airdrop pot into the final pot uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; // calculate ppt for round mask uint256 _ppt = 0; if(round_[_rID].keys > 0) { _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); } uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards adminAddress.transfer(_com); // 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); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = 0; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = 0; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rID) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rID); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rID].mask = _earnings.add(plyrRnds_[_pID][_rID].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth * 5 / 100; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { // no affiliates, add to community _com += _aff; } // pay out team adminAddress.transfer(_com); return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot (20%) uint256 _pot = (_eth.mul(20) / 100); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit RSEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only owner can activate require( msg.sender == adminAddress, "only owner can activate" ); // can only be ran once require(activated_ == false, "ratscam already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now - rndGap_; round_[1].end = now + rndInit_; } function setNextRndTime(uint32 rndInit, uint32 rndInc, uint32 rndMax) public { // only owner require(msg.sender == adminAddress, "only owner can setNextRndTime"); rndInit_ = rndInit * 1 hours; rndInc_ = rndInc * 1 seconds; rndMax_ = rndMax * 1 hours; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library RSdatasets { //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 bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 laff; // last affiliate id used 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 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 } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library RSKeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //interface RatInterfaceForForwarder { // function deposit() external payable returns(bool); //} interface RatBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } }
returns all current round info needed for front end -functionhash- 0x747dff42 return total keys return time ends return time started return current pot return current player ID in lead return current player in leads address return current player in leads name return airdrop tracker & airdrop pot/ setup local rID
function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { uint256 _rID = rID_; return ( ); }
429,699
./full_match/11155111/0xD935524c4606035C5Ce45a9238863aa53ABFEECc/sources/contracts/swap.sol
Disapproves a given order Only an owner or manager can call this function. Checks that the order has not already been disapproved or cancelled. Also checks whether approvals are enabled, and checks that the order has not been fully filled yet. Finally, it marks the order as disapproved. orderId The id of the order to disapprove
function disapproveOrder(uint256 orderId) public onlyOwnerOrManager { require( !orders[orderId].status.isDisapproved, "Order already disapproved" ); require(!orders[orderId].status.isCancelled, "Order already cancelled"); require( swapApprovalsEnabled || txnApprovalsEnabled, "Approvals toggled off" ); require( orders[orderId].filledAmount < orders[orderId].amount, "Order already fully filled" ); orders[orderId].status.isDisapproved = true; orders[orderId].status.isApproved = false; orders[orderId].status.orderAccepted = false; }
3,832,208
./full_match/4/0x412CaD145f63cD1884b8bAE4F2413F2604709231/sources/contracts/ERC721.sol
Cannot overflow because because ownership is checked against decrement, and sum of all user balances can't exceed the max uint256 value.
function transfer(address to, uint256 tokenId) public virtual returns (bool success) { require(msg.sender == ownerOf[tokenId], "NOT_OWNER"); unchecked { balanceOf[msg.sender]--; balanceOf[to]++; } delete getApproved[tokenId]; ownerOf[tokenId] = to; emit Transfer(msg.sender, to, tokenId); success = true; } ERC-721 LOGIC
13,365,633
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.5.16; import "./GToken.sol"; import "./ERC3156FlashBorrowerInterface.sol"; import "./ERC3156FlashLenderInterface.sol"; /** * @title Wrapped native token interface */ interface WrappedNativeInterface { function deposit() external payable; function withdraw(uint256 wad) external; } /** * @title Cream's GWrappedNative Contract * @notice GTokens which wrap the native token * @author Cream */ contract GWrappedNative is GToken, GWrappedNativeInterface, GProtocolSeizeShareStorage { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param gTroller_ The address of the Gtroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( address underlying_, GtrollerInterface gTroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { // GToken initialize does the bulk of the work super.initialize(gTroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); WrappedNativeInterface(underlying); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives gTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for backward joeatibility * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint256 mintAmount) external returns (uint256) { (uint256 err, ) = mintInternal(mintAmount, false); require(err == 0, "mint failed"); } /** * @notice Sender supplies assets into the market and receives gTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for consistency * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mintNative() external payable returns (uint256) { (uint256 err, ) = mintInternal(msg.value, true); require(err == 0, "mint native failed"); } /** * @notice Sender redeems gTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for backward joeatibility * @param redeemTokens The number of gTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256) { require(redeemInternal(redeemTokens, false) == 0, "redeem failed"); } /** * @notice Sender redeems gTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for consistency * @param redeemTokens The number of gTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemNative(uint256 redeemTokens) external returns (uint256) { require(redeemInternal(redeemTokens, true) == 0, "redeem native failed"); } /** * @notice Sender redeems gTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for backward joeatibility * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256) { require(redeemUnderlyingInternal(redeemAmount, false) == 0, "redeem underlying failed"); } /** * @notice Sender redeems gTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for consistency * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256) { require(redeemUnderlyingInternal(redeemAmount, true) == 0, "redeem underlying native failed"); } /** * @notice Sender borrows assets from the protocol to their own address * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for backward joeatibility * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256) { require(borrowInternal(borrowAmount, false) == 0, "borrow failed"); } /** * @notice Sender borrows assets from the protocol to their own address * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for consistency * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowNative(uint256 borrowAmount) external returns (uint256) { require(borrowInternal(borrowAmount, true) == 0, "borrow native failed"); } /** * @notice Sender repays their own borrow * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for backward joeatibility * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 repayAmount) external returns (uint256) { (uint256 err, ) = repayBorrowInternal(repayAmount, false); require(err == 0, "repay failed"); } /** * @notice Sender repays their own borrow * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for consistency * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowNative() external payable returns (uint256) { (uint256 err, ) = repayBorrowInternal(msg.value, true); require(err == 0, "repay native failed"); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) { (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount, false); require(err == 0, "repay behalf failed"); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalfNative(address borrower) external payable returns (uint256) { (uint256 err, ) = repayBorrowBehalfInternal(borrower, msg.value, true); require(err == 0, "repay behalf native failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for backward joeatibility * @param borrower The borrower of this gToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param gTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint256 repayAmount, GTokenInterface gTokenCollateral ) external returns (uint256) { (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, gTokenCollateral, false); require(err == 0, "liquidate borrow failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for consistency * @param borrower The borrower of this gToken to be liquidated * @param gTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrowNative(address borrower, GTokenInterface gTokenCollateral) external payable returns (uint256) { (uint256 err, ) = liquidateBorrowInternal(borrower, msg.value, gTokenCollateral, true); require(err == 0, "liquidate borrow native failed"); } /** * @notice Get the max flash loan amount */ function maxFlashLoan() external view returns (uint256) { uint256 amount = 0; if (GtrollerInterfaceExtension(address(gTroller)).flashloanAllowed(address(this), address(0), amount, "")) { amount = getCashPrior(); } return amount; } /** * @notice Get the flash loan fees * @param amount amount of token to borrow */ function flashFee(uint256 amount) external view returns (uint256) { require( GtrollerInterfaceExtension(address(gTroller)).flashloanAllowed(address(this), address(0), amount, ""), "flashloan is paused" ); return div_(mul_(amount, flashFeeBips), 10000); } /** * @notice Flash loan funds to a given account. * @param receiver The receiver address for the funds * @param initiator flash loan initiator * @param amount The amount of the funds to be loaned * @param data The other data * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external nonReentrant returns (bool) { require(amount > 0, "flashLoan amount should be greater than zero"); require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); require( GtrollerInterfaceExtension(address(gTroller)).flashloanAllowed( address(this), address(receiver), amount, data ), "flashloan is paused" ); uint256 cashBefore = getCashPrior(); require(cashBefore >= amount, "INSUFFICIENT_LIQUIDITY"); // 1. calculate fee, 1 bips = 1/10000 uint256 totalFee = this.flashFee(amount); // 2. transfer fund to receiver doTransferOut(address(uint160(address(receiver))), amount, false); // 3. update totalBorrows totalBorrows = add_(totalBorrows, amount); // 4. execute receiver's callback function require( receiver.onFlashLoan(initiator, underlying, amount, totalFee, data) == keccak256("ERC3156FlashBorrowerInterface.onFlashLoan"), "IERC3156: Callback failed" ); // 5. take amount + fee from receiver, then check balance uint256 repaymentAmount = add_(amount, totalFee); doTransferIn(address(receiver), repaymentAmount, false); uint256 cashAfter = getCashPrior(); require(cashAfter == add_(cashBefore, totalFee), "BALANCE_INCONSISTENT"); // 6. update totalReserves and totalBorrows uint256 reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee); totalReserves = add_(totalReserves, reservesFee); totalBorrows = sub_(totalBorrows, amount); emit Flashloan(address(receiver), amount, totalFee, reservesFee); return true; } function() external payable { require(msg.sender == underlying, "only wrapped native contract could send native token"); } /** * @notice The sender adds to reserves. * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for backward joeatibility * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint256 addAmount) external returns (uint256) { require(_addReservesInternal(addAmount, false) == 0, "add reserves failed"); } /** * @notice The sender adds to reserves. * @dev Accrues interest whether or not the operation succeeds, unless reverted * Keep return in the function signature for consistency * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesNative() external payable returns (uint256) { require(_addReservesInternal(msg.value, true) == 0, "add reserves failed"); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint256) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256) { if (isNative) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); // Convert received native token to wrapped token WrappedNativeInterface(underlying).deposit.value(amount)(); return amount; } else { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); return sub_(balanceAfter, balanceBefore); } } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal { if (isNative) { // Convert wrapped token to native token WrappedNativeInterface(underlying).withdraw(amount); /* Send the Ether, with minimal gas and revert on failure */ to.transfer(amount); } else { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a joelaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { /* Fail if transfer not allowed */ uint256 allowed = gTroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.TRANSFER_JOETROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ accountTokens[src] = sub_(accountTokens[src], tokens); accountTokens[dst] = add_(accountTokens[dst], tokens); /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = sub_(startingAllowance, tokens); } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); return uint256(Error.NO_ERROR); } /** * @notice Get the account's gToken balances * @param account The address of the account */ function getGTokenBalanceInternal(address account) internal view returns (uint256) { return accountTokens[account]; } struct MintLocalVars { uint256 exchangeRateMantissa; uint256 mintTokens; uint256 actualMintAmount; } /** * @notice User supplies assets into the market and receives gTokens in exchange * @dev Assumes interest has already been accrued up to the current timestamp * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if mint not allowed */ uint256 allowed = gTroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.MINT_JOETROLLER_REJECTION, allowed), 0); } /* * Return if mintAmount is zero. * Put behind `mintAllowed` for accuring potential JOE rewards. */ if (mintAmount == 0) { return (uint256(Error.NO_ERROR), 0); } /* Verify market's block timestamp equals current block timestamp */ if (accrualBlockTimestamp != getBlockTimestamp()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; vars.exchangeRateMantissa = exchangeRateStoredInternal(); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The gToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the gToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative); /* * We get the current exchange rate and calculate the number of gTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); /* * We calculate the new total supply of gTokens and minter token balance, checking for overflow: * totalSupply = totalSupply + mintTokens * accountTokens[minter] = accountTokens[minter] + mintTokens */ totalSupply = add_(totalSupply, vars.mintTokens); accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens); /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); return (uint256(Error.NO_ERROR), vars.actualMintAmount); } struct RedeemLocalVars { uint256 exchangeRateMantissa; uint256 redeemTokens; uint256 redeemAmount; uint256 totalSupplyNew; uint256 accountTokensNew; } /** * @notice User redeems gTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current timestamp. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero. * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of gTokens to redeem into underlying * @param redeemAmountIn The number of underlying tokens to receive from redeeming gTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ vars.exchangeRateMantissa = exchangeRateStoredInternal(); /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint256 allowed = gTroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REDEEM_JOETROLLER_REJECTION, allowed); } /* * Return if redeemTokensIn and redeemAmountIn are zero. * Put behind `redeemAllowed` for accuring potential JOE rewards. */ if (redeemTokensIn == 0 && redeemAmountIn == 0) { return uint256(Error.NO_ERROR); } /* Verify market's block timestamp equals current block timestamp */ if (accrualBlockTimestamp != getBlockTimestamp()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ vars.totalSupplyNew = sub_(totalSupply, vars.redeemTokens); vars.accountTokensNew = sub_(accountTokens[redeemer], vars.redeemTokens); /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The gToken must handle variations between ERC-20 and ETH underlying. * On success, the gToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount, isNative); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ gTroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint256(Error.NO_ERROR); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another GToken. * Its absolutely critical to use msg.sender as the seizer gToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed gToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of gTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256) { /* Fail if seize not allowed */ uint256 allowed = gTroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_JOETROLLER_REJECTION, allowed); } /* * Return if seizeTokens is zero. * Put behind `seizeAllowed` for accuring potential JOE rewards. */ if (seizeTokens == 0) { return uint256(Error.NO_ERROR); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } uint256 protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa})); uint256 liquidatorSeizeTokens = sub_(seizeTokens, protocolSeizeTokens); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); uint256 protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: exchangeRateMantissa}), protocolSeizeTokens); /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens); accountTokens[liquidator] = add_(accountTokens[liquidator], liquidatorSeizeTokens); totalReserves = add_(totalReserves, protocolSeizeAmount); totalSupply = sub_(totalSupply, protocolSeizeTokens); /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); emit ReservesAdded(address(this), protocolSeizeAmount, totalReserves); return uint256(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Accrues interest and sets a new collateral seize share for the protocol using _setProtocolSeizeShareFresh * @dev Admin function to accrue interest and set a new collateral seize share * @return uint256 0=success, otherwise a failure (see ErrorReport.sol for details) */ function _setProtocolSeizeShare(uint256 newProtocolSeizeShareMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { return fail(Error(error), FailureInfo.SET_PROTOCOL_SEIZE_SHARE_ACCRUE_INTEREST_FAILED); } return _setProtocolSeizeShareFresh(newProtocolSeizeShareMantissa); } function _setProtocolSeizeShareFresh(uint256 newProtocolSeizeShareMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_ADMIN_CHECK); } // Verify market's block timestamp equals current block timestamp if (accrualBlockTimestamp != getBlockTimestamp()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_FRESH_CHECK); } if (newProtocolSeizeShareMantissa > protocolSeizeShareMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_PROTOCOL_SEIZE_SHARE_BOUNDS_CHECK); } uint256 oldProtocolSeizeShareMantissa = protocolSeizeShareMantissa; protocolSeizeShareMantissa = newProtocolSeizeShareMantissa; emit NewProtocolSeizeShare(oldProtocolSeizeShareMantissa, newProtocolSeizeShareMantissa); return uint256(Error.NO_ERROR); } }
Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. This will revert due to insufficient balance or insufficient allowance. This function returns the actual amount received, which may be less than `amount` if there is a fee attached to the transfer. Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value./ Sanity checks Convert received native token to wrapped token This is a non-standard ERC-20 This is a compliant ERC-20 This is an excessively non-compliant ERC-20, revert.
function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256) { if (isNative) { require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); WrappedNativeInterface(underlying).deposit.value(amount)(); return amount; EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { } case 32 { returndatacopy(0, 0, 32) } default { revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); return sub_(balanceAfter, balanceBefore); } }
992,443
./full_match/80001/0x0614Ff9C5aA8749F3064bFf4bF17A3cBD8fc41f2/sources/src/TipJar.sol
Overall, msg.sender always represents the address of the sender of the current function call. However, it can represent different entities (e.g., the deployer of the contract, the sender of the tip, etc.) depending on its location and use in the contract./
function tip() public payable { require(msg.value > 0, "You must send a tip amount"); emit TipReceived(msg.sender, msg.value); }
5,559,222
./partial_match/1/0x968348C6135C25e7160AD0671C8C9CA2eD2bb982/sources/contracts/eclp/GyroECLPPool.sol
When rateProvider{0,1} is provided, this returns the scaled price, suitable to compare rate scaled balances. To compare (decimal- but) not-rate-scaled balances, apply _adjustPrice() to the result./
function _getPrice( uint256[] memory balances, uint256 invariant, GyroECLPMath.Params memory eclpParams, GyroECLPMath.DerivedParams memory derivedECLPParams ) internal view returns (uint256 spotPrice) { spotPrice = GyroECLPMath.calcSpotPrice0in1(balances, eclpParams, derivedECLPParams, invariant.toInt256()); }
15,967,315
./partial_match/1/0x07AF91E4bB31AfF887Bb4ba9778E2B5388595969/sources/FIRE.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "FIRE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "FIRE::delegateBySig: invalid nonce"); require(now <= expiry, "FIRE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
9,375,293
pragma solidity ^0.5.10; import {TypedMemView} from "./TypedMemView.sol"; import {SafeMath} from "./SafeMath.sol"; library ViewCKB { using TypedMemView for bytes29; using SafeMath for uint; uint256 public constant PERIOD_BLOCKS = 24 * 450 * 7; // 1 week in blocks uint8 public constant NUMBER_SIZE = 4; // Size of Number in ckb molecule uint64 public constant NUMBER_MASK = 16777215; enum CKBTypes { Unknown, // 0x0 Script, // 0x1 Outpoint, CellInput, CellOutput, Bytes, H256, H160, Header, Nonce, RawHeader, Version, CompactTarget, Timestamp, BlockNumber, Epoch, ParentHash, TransactionsRoot, UnclesHash, HeaderVec, Transaction } /// @notice requires `memView` to be of a specified type /// @param memView a 29-byte view with a 5-byte type /// @param t the expected type (e.g. CKBTypes.Outpoint, CKBTypes.Script, etc) /// @return passes if it is the correct type, errors if not modifier typeAssert(bytes29 memView, CKBTypes t) { memView.assertType(uint40(t)); _; } /// @notice extracts the since as an integer from a CellInput /// @param _input the CellInput /// @return the since function since(bytes29 _input) internal pure typeAssert(_input, CKBTypes.CellInput) returns (uint64) { return uint64(_input.indexLEUint(0, 8)); } /// @notice extracts the outpoint from a CellInput /// @param _input the CellInput /// @return the outpoint as a typed memory function previousOutput(bytes29 _input) internal pure typeAssert(_input, CKBTypes.CellInput) returns (bytes29) { return _input.slice(8, 36, uint40(CKBTypes.Outpoint)); } /// @notice extracts the codeHash from a Script /// @param _input the Script /// @return the codeHash function codeHash(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Script) returns (bytes32) { uint256 startIndex = _input.indexLEUint(4, 4); return _input.index(startIndex, 32); } /// @notice extracts the hashType from a Script /// @param _input the Script /// @return the hashType function hashType(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Script) returns (uint8) { uint256 startIndex = _input.indexLEUint(8, 4); return uint8(_input.indexUint(startIndex, 1)); } /// @notice extracts the args from a Script /// @param _input the Script /// @return the args function args(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Script) returns (bytes29) { uint256 startIndex = _input.indexLEUint(12, 4) + NUMBER_SIZE; uint256 inputLength = _input.len(); return _input.slice(startIndex, inputLength - startIndex, uint40(CKBTypes.Bytes)); } /// @notice extracts the rawHeader from a Header /// @param _input the Header /// @return the rawHeader as a typed memory function rawHeader(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Header) returns (bytes29) { return _input.slice(0, 192, uint40(CKBTypes.RawHeader)); } /// @notice extracts the nonce from a Header /// @param _input the Header /// @return the nonce function nonce(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Header) returns (uint128) { return uint128(_input.indexLEUint(192, 16)); } /// @notice extracts the version from a RawHeader /// @param _input the RawHeader /// @return the version function version(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint32) { return uint32(_input.indexLEUint(0, 4)); } /// @notice extracts the compactTarget from a RawHeader /// @param _input the RawHeader /// @return the compactTarget function compactTarget(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint32) { return uint32(_input.indexLEUint(4, 4)); } /// @notice extracts the timestamp from a RawHeader /// @param _input the RawHeader /// @return the timestamp function timestamp(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint64) { return uint64(_input.indexLEUint(8, 8)); } /// @notice extracts the blockNumber from a RawHeader /// @param _input the RawHeader /// @return the blockNumber function blockNumber(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint64) { return uint64(_input.indexLEUint(16, 8)); } /// @notice extracts the epoch from a RawHeader /// @param _input the RawHeader /// @return the epoch function epoch(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint64) { return uint64(_input.indexLEUint(24, 8)) & NUMBER_MASK; } /// @notice extracts the parentHash from a RawHeader /// @param _input the RawHeader /// @return the parentHash function parentHash(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (bytes32) { return _input.index(32, 32); } /// @notice extracts the transactionsRoot from a RawHeader /// @param _input the RawHeader /// @return the transactionsRoot function transactionsRoot(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (bytes32) { return _input.index(64, 32); } /// @notice extracts the unclesHash from a RawHeader /// @param _input the RawHeader /// @return the unclesHash function unclesHash(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (bytes32) { return _input.index(128, 32); } /// @notice Index a header vector. /// @dev Errors on overruns /// @param _headers The header vector /// @param index The 0-indexed location of the header to get /// @return the typed header at `index` function indexHeaderVec(bytes29 _headers, uint256 index) internal pure typeAssert(_headers, CKBTypes.HeaderVec) returns (bytes29) { uint256 _start = 4 + index.mul(208); return _headers.slice(_start, 208, uint40(CKBTypes.Header)); } /// @notice return length of a header vector. /// @dev Errors on overruns /// @param _headers The header vector /// @return the length of a header vector. function lengthHeaderVec(bytes29 _headers) internal pure typeAssert(_headers, CKBTypes.HeaderVec) returns (uint32) { return uint32(_headers.indexLEUint(0, 4)); } }
extracts the since as an integer from a CellInput _input the CellInput return the since
function since(bytes29 _input) internal pure typeAssert(_input, CKBTypes.CellInput) returns (uint64) { return uint64(_input.indexLEUint(0, 8)); }
905,507
// SPDX-License-Identifier: Apache-2.0 /* Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.5; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol"; import "@0x/contracts-utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol"; import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol"; import "../vendor/ILiquidityProvider.sol"; import "../vendor/v3/IERC20Bridge.sol"; import "./ILiquidityProviderSandbox.sol"; /// @dev A permissionless contract through which the ZeroEx contract can /// safely trigger a trade on an external `ILiquidityProvider` contract. contract LiquidityProviderSandbox is ILiquidityProviderSandbox { using LibRichErrorsV06 for bytes; /// @dev Store the owner as an immutable. address public immutable owner; constructor(address owner_) public { owner = owner_; } /// @dev Allows only the (immutable) owner to call a function. modifier onlyOwner() virtual { if (msg.sender != owner) { LibOwnableRichErrorsV06.OnlyOwnerError( msg.sender, owner ).rrevert(); } _; } /// @dev Calls `sellTokenForToken` on the given `provider` contract to /// trigger a trade. /// @param provider The address of the on-chain liquidity provider. /// @param inputToken The token being sold. /// @param outputToken The token being bought. /// @param recipient The recipient of the bought tokens. /// @param minBuyAmount The minimum acceptable amount of `outputToken` to buy. /// @param auxiliaryData Auxiliary data supplied to the `provider` contract. function executeSellTokenForToken( ILiquidityProvider provider, IERC20TokenV06 inputToken, IERC20TokenV06 outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData ) external onlyOwner override { provider.sellTokenForToken( inputToken, outputToken, recipient, minBuyAmount, auxiliaryData ); } /// @dev Calls `sellEthForToken` on the given `provider` contract to /// trigger a trade. /// @param provider The address of the on-chain liquidity provider. /// @param outputToken The token being bought. /// @param recipient The recipient of the bought tokens. /// @param minBuyAmount The minimum acceptable amount of `outputToken` to buy. /// @param auxiliaryData Auxiliary data supplied to the `provider` contract. function executeSellEthForToken( ILiquidityProvider provider, IERC20TokenV06 outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData ) external onlyOwner override { provider.sellEthForToken( outputToken, recipient, minBuyAmount, auxiliaryData ); } /// @dev Calls `sellTokenForEth` on the given `provider` contract to /// trigger a trade. /// @param provider The address of the on-chain liquidity provider. /// @param inputToken The token being sold. /// @param recipient The recipient of the bought tokens. /// @param minBuyAmount The minimum acceptable amount of ETH to buy. /// @param auxiliaryData Auxiliary data supplied to the `provider` contract. function executeSellTokenForEth( ILiquidityProvider provider, IERC20TokenV06 inputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData ) external onlyOwner override { provider.sellTokenForEth( inputToken, payable(recipient), minBuyAmount, auxiliaryData ); } }
Calls `sellTokenForEth` on the given `provider` contract to trigger a trade. provider The address of the on-chain liquidity provider. inputToken The token being sold. recipient The recipient of the bought tokens. minBuyAmount The minimum acceptable amount of ETH to buy. auxiliaryData Auxiliary data supplied to the `provider` contract.
function executeSellTokenForEth( ILiquidityProvider provider, IERC20TokenV06 inputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData ) external onlyOwner override { provider.sellTokenForEth( inputToken, payable(recipient), minBuyAmount, auxiliaryData ); }
5,499,235
./partial_match/1/0x6098Dc88B1ff5C59c37b9571E3263Df29856c3b0/sources/PMU.sol
Trade start checkSet Fee for BuysSet Fee for Sells
function _transfer( address from, address to, uint256 amount ) private { require(to != address(0), "ERC20: transfer to the zero address"); require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if ( from != owner() && to != owner() ) { if (!tradingActive) { require( from == owner(), "TOKEN: This account cannot send tokens until trading is enabled" ); } require(amount <= _mxTransSize, "TOKEN: Max Transaction Limit"); if(to != v2PairAddr) { require(balanceOf(to) + amount < _mxWalletAmount, "TOKEN: Balance exceeds wallet size!"); } uint256 tokenAmountOfCont = balanceOf(address(this)); if (tokenAmountOfCont >= _swapLimitAt && !swappingNow && from != v2PairAddr && enabledSwap && !_isExcludedFromFee[from] && !_isExcludedFromFee[to] ) { swapAllTokens(tokenAmountOfCont); uint256 ethBalance = address(this).balance; if (ethBalance > 0) { sendEth(address(this).balance); } } } bool setFee = true; (_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != v2PairAddr && to != v2PairAddr) ) { setFee = false; if(from == v2PairAddr && to != address(uniswapV2Router)) { _marketingFee = _marketingTaxBuy; _standardFee = _buyTaxAmt; } if (to == v2PairAddr && from != address(uniswapV2Router)) { _marketingFee = _marketingTaxSell; _standardFee = _sellTaxAmt; } } _transferTokenAndFee(from, to, amount, setFee); }
3,557,207
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; /* $$$$$$$$\ $$\ $$$$$$$$\ $$\ $$ _____| $$ | \__$$ __|\__| $$ | $$$$$$\ $$$$$$\ $$$$$$\ $$\ $$\ $$$$$$$\ $$$$$$\ $$ | $$\ $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$$\ $$$$$\ $$ __$$\ $$ __$$\\_$$ _| $$ | $$ |$$ __$$\ $$ __$$\ $$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$ _____| $$ __|$$ / $$ |$$ | \__| $$ | $$ | $$ |$$ | $$ |$$$$$$$$ | $$ | $$ |$$ / $$ |$$$$$$$$ |$$ | \__|\$$$$$$\ $$ | $$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ | $$ |$$ ____| $$ | $$ |$$ | $$ |$$ ____|$$ | \____$$\ $$ | \$$$$$$ |$$ | \$$$$ |\$$$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$ |\$$$$$$$ |\$$$$$$$\ $$ | $$$$$$$ | \__| \______/ \__| \____/ \______/ \__| \__| \_______| \__| \__| \____$$ | \_______|\__| \_______/ $$\ $$ | \$$$$$$ | \______/ Fortune Tigers | 2022 | version 1.0 | ERC 721 */ import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract FortuneTigers is ERC721, Ownable { using Strings for uint256; uint256 public constant MAX = 388; uint256 public SALE_PRICE = 0.008 ether; uint256 public tokensMinted; string private _imgURI = "https://ipfs.io/ipfs/QmepFr4wZ7GkHkrsTvmHpFkg48wDKoe9ch4iAfKrUJ8Se1/"; address public OSProxy; constructor(address _OSProxy) ERC721("Fortune Tigers 2022", "FORTUNE") { OSProxy = _OSProxy; } //**** Mint/Purchase functions ****// /** * @dev Mint function */ function Buy(uint256 tokenQuantity) external payable { address wallet = msg.sender; uint256 tokenQty = tokenQuantity; uint256 totalMinted = tokensMinted; require(totalMinted + tokenQty <= MAX, "OUT_OF_STOCK"); require(SALE_PRICE * tokenQty <= msg.value, "INSUFFICIENT_ETH"); tokensMinted += tokenQty; for (uint256 i = 0; i < tokenQty; i++) { totalMinted++; _mint(wallet, totalMinted); } delete wallet; delete tokenQty; delete totalMinted; } /** * @dev giveaways */ function giveaway(address[] calldata receivers) external onlyOwner { uint256 totalMinted = tokensMinted; uint256 giftAddresses = receivers.length; require(totalMinted + giftAddresses <= MAX, "OUT_OF_STOCK"); tokensMinted += giftAddresses; for (uint256 i = 0; i < giftAddresses; i++) { totalMinted++; _mint(receivers[i], totalMinted); } delete giftAddresses; delete totalMinted; } //**** Owner functions ****// /** * @dev withdraw */ function withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * @dev set Image URI */ function setImageURI(string calldata URI) external onlyOwner { _imgURI = URI; } /** * @dev set Sale Price */ function setSalePrice(uint256 newPrice) external onlyOwner { SALE_PRICE = newPrice; } /** * @dev set OS Proxy address */ function setOSProxy(address Proxy) external onlyOwner { OSProxy = Proxy; } //**** View functions ****// function contractURI() public pure returns (string memory) { string memory output; string memory contractmeta = base64( bytes( string( abi.encodePacked( '{"name": "Fortune Tigers 2022", "description": "A collection of 388 unique Fortune Tigers (Mint @ https://fortunetigers.win). Welcome the Year of the Tiger 2022 with your very own Fortune Tiger! Time to get Lucky with your personal fortune and lucky set of numbers!", "image": "https://fortunetigers.win/images/preview.gif", "external_link": "https://fortunetigers.win"}' ) ) ) ); output = string(abi.encodePacked("data:application/json;base64,", contractmeta)); return output; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "Cannot query non-existent token"); return string(abi.encodePacked("data:application/json;base64,", base64(bytes(tokenURIstring(tokenId))))); } function tokenURIstring(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Cannot query non-existent token"); string memory output = string(abi.encodePacked(_imgURI, tokenId.toString(), ".png")); string memory json = string( abi.encodePacked( '{"name": "Fortune Tiger #', tokenId.toString(), '", "description": "A collection of 388 unique Fortune Tigers (Mint @ https://fortunetigers.win). Welcome the Year of the Tiger 2022 with your very own Fortune Tiger! Time to get Lucky with your personal fortune and lucky set of numbers!", "image":"', output, '"}' ) ); return json; } /** * @dev totalSupply() */ function totalSupply() public view virtual returns (uint256) { return tokensMinted; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(OSProxy); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** BASE 64 - Written by Brech Devos */ string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
set OS Proxy address/
function setOSProxy(address Proxy) external onlyOwner { OSProxy = Proxy; }
14,374,908
pragma solidity ^0.4.18; contract SafeMathLib { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint c = a + b; assert(c>=a); return c; } function safeDiv(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; } } /** * @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; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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); } /** * A token that defines fractional units as decimals. */ contract FractionalERC20 is ERC20 { uint8 public decimals; } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMathLib { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint256 amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint256)) allowed; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint _allowance = allowed[_from][msg.sender]; require(_to != address(0)); require(_value <= balances[_from]); require(_value <= _allowance); require(balances[_to] + _value > balances[_to]); balances[_to] = safeAdd(balances[_to],_value); balances[_from] = safeSub(balances[_from],_value); allowed[_from][msg.sender] = safeSub(_allowance,_value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @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] = safeAdd(allowed[msg.sender][_spender],_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = safeSub(balances[burner],_value); totalSupply = safeSub(totalSupply,_value); Burn(burner, _value); } } /** * Upgrade agent interface inspired by Lunyr. * * 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. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public pure returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardToken { /** 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. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - 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 indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); require((state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)); // Validate input value. require (value != 0); balances[msg.sender] = safeSub(balances[msg.sender],value); // Take tokens out from circulation totalSupply = safeSub(totalSupply,value); totalUpgraded = safeAdd(totalUpgraded,value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { require(canUpgrade()); require(agent != 0x0); // Only a master can designate the next agent require(msg.sender == upgradeMaster); // 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 constant 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 setUpgradeMaster(address master) public { require(master != 0x0); require(msg.sender == upgradeMaster); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public view returns(bool) { return true; } } /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is ERC20, Ownable { /* The finalizer contract that allows unlift 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; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { if(!released) { require(transferAgents[_sender]); } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (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 to the wild. * * Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } function transfer(address _to, uint _value) canTransfer(msg.sender) public returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) public returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableToken is StandardToken, Ownable { 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); event Mint(address indexed to, uint256 amount); /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint256 amount) onlyMintAgent canMint public returns(bool){ totalSupply = safeAdd(totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Mint(receiver, amount); Transfer(0, receiver, amount); return true; } /** * 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 crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** Make sure we are not done yet. */ modifier canMint() { require(!mintingFinished); _; } } /** * A crowdsaled 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 approve() mechanism * - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens) * */ contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken, BurnableToken { event UpdatedTokenInformation(string newName, string newSymbol); string public name; string public symbol; uint8 public decimals; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param _name Token name * @param _symbol Token symbol - should be all caps * @param _initialSupply How many tokens we start with * @param _decimals Number of decimal places * @param _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? Note that when the token becomes transferable the minting always ends. */ function CrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint8 _decimals, bool _mintable) public UpgradeableToken(msg.sender) { // Create any address, can be transferred // to team multisig via changeOwner(), // also remember to call setUpgradeMaster() owner = msg.sender; name = _name; symbol = _symbol; totalSupply = _initialSupply; decimals = _decimals; // Create initially all balance on the team multisig balances[owner] = totalSupply; if(totalSupply > 0) { Minted(owner, totalSupply); } // No more new supply allowed after the token creation if(!_mintable) { mintingFinished = true; require(totalSupply != 0); } } /** * When token is released to be transferable, enforce no new tokens can be created. */ function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality kick in only if the crowdsale was success. */ function canUpgrade() public view returns(bool) { return released && super.canUpgrade(); } /** * Owner can update token information here */ function setTokenInformation(string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } } /** * Finalize agent defines what happens at the end of succeseful crowdsale. * * - Allocate tokens for founders, bounties and community * - Make tokens transferable * - etc. */ contract FinalizeAgent { function isFinalizeAgent() public pure returns(bool) { return true; } /** Return true if we can run finalizeCrowdsale() properly. * * This is a safety check function that doesn't allow crowdsale to begin * unless the finalizer has been set up properly. */ function isSane() public view returns (bool); /** Called once by crowdsale finalize() if the sale was success. */ function finalizeCrowdsale() public ; } /** * Interface for defining crowdsale pricing. */ contract PricingStrategy { /** Interface declaration. */ function isPricingStrategy() public pure returns (bool) { return true; } /** Self check if all references are correctly set. * * Checks that pricing strategy matches crowdsale parameters. */ function isSane(address crowdsale) public view returns (bool) { return true; } /** * When somebody tries to buy tokens for X eth, calculate how many tokens they get. * * * @param value - What is the value of the transaction send in as wei * @param tokensSold - how much tokens have been sold this far * @param weiRaised - how much money has been raised this far * @param msgSender - who is the investor of this transaction * @param decimals - how many decimal units the token has * @return Amount of tokens the investor receives */ function calculatePrice(uint256 value, uint256 weiRaised, uint256 tokensSold, address msgSender, uint256 decimals) public constant returns (uint256 tokenAmount); } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract Allocatable is Ownable { /** List of agents that are allowed to allocate new tokens */ mapping (address => bool) public allocateAgents; event AllocateAgentChanged(address addr, bool state ); /** * Owner can allow a crowdsale contract to allocate new tokens. */ function setAllocateAgent(address addr, bool state) onlyOwner public { allocateAgents[addr] = state; AllocateAgentChanged(addr, state); } modifier onlyAllocateAgent() { // Only crowdsale contracts are allowed to allocate new tokens require(allocateAgents[msg.sender]); _; } } /** * Abstract base contract for token sales. * * Handle * - start and end dates * - accepting investments * - minimum funding goal and refund * - various statistics during the crowdfund * - different pricing strategies * - different investment policies (require server side customer id, allow only whitelisted addresses) * */ contract Crowdsale is Allocatable, Haltable, SafeMathLib { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; /* The token we are selling */ FractionalERC20 public token; /* Token Vesting Contract */ address public tokenVestingAddress; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint256 public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint256 public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint256 public endsAt; /* the number of tokens already sold through this contract*/ uint256 public tokensSold = 0; /* How many wei of funding we have raised */ uint256 public weiRaised = 0; /* How many distinct addresses have invested */ uint256 public investorCount = 0; /* How much wei we have returned back to the contract after a failed crowdfund. */ uint256 public loadedRefund = 0; /* How much wei we have given back to investors.*/ uint256 public weiRefunded = 0; /* Has this crowdsale been finalized */ bool public finalized; /* Do we need to have unique contributor id for each customer */ bool public requireCustomerId; /** * Do we verify that contributor has been cleared on the server side (accredited investors only). * This method was first used in FirstBlood crowdsale to ensure all contributors have accepted terms on sale (on the web). */ bool public requiredSignedAddress; /* Server side address that signed allowed contributors (Ethereum addresses) that can participate the crowdsale */ address public signerAddress; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => bool) public earlyParticipantWhitelist; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint256 public ownerTestValue; uint256 public earlyPariticipantWeiPrice =82815734989648; uint256 public whitelistBonusPercentage = 15; uint256 public whitelistPrincipleLockPercentage = 50; uint256 public whitelistBonusLockPeriod = 7776000; uint256 public whitelistPrincipleLockPeriod = 7776000; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed * - Refunding: Refunds are loaded on the contract for reclaim. */ enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} // A new investment was made event Invested(address investor, uint256 weiAmount, uint256 tokenAmount, uint128 customerId); // Refund was processed for a contributor event Refund(address investor, uint256 weiAmount); // The rules were changed what kind of investments we accept event InvestmentPolicyChanged(bool requireCustId, bool requiredSignedAddr, address signerAddr); // Address early participation whitelist status changed event Whitelisted(address addr, bool status); // Crowdsale end time has been changed event EndsAtChanged(uint256 endAt); // Crowdsale start time has been changed event StartAtChanged(uint256 endsAt); function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint256 _start, uint256 _end, uint256 _minimumFundingGoal, address _tokenVestingAddress) public { owner = msg.sender; token = FractionalERC20(_token); tokenVestingAddress = _tokenVestingAddress; setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; require(multisigWallet != 0); require(_start != 0); startsAt = _start; require(_end != 0); endsAt = _end; // Don't mess the dates require(startsAt < endsAt); // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; } /** * Don't expect to just send in money and get tokens. */ function() payable public { invest(msg.sender); } /** Function to set default vesting schedule parameters. */ function setDefaultWhitelistVestingParameters(uint256 _bonusPercentage, uint256 _principleLockPercentage, uint256 _bonusLockPeriod, uint256 _principleLockPeriod, uint256 _earlyPariticipantWeiPrice) onlyAllocateAgent public { whitelistBonusPercentage = _bonusPercentage; whitelistPrincipleLockPercentage = _principleLockPercentage; whitelistBonusLockPeriod = _bonusLockPeriod; whitelistPrincipleLockPeriod = _principleLockPeriod; earlyPariticipantWeiPrice = _earlyPariticipantWeiPrice; } /** * Make an investment. * * 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 private { uint256 tokenAmount; uint256 weiAmount = msg.value; // Determine if it's a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit require(earlyParticipantWhitelist[receiver]); require(weiAmount >= safeMul(15, uint(10 ** 18))); require(weiAmount <= safeMul(50, uint(10 ** 18))); tokenAmount = safeDiv(safeMul(weiAmount, uint(10) ** token.decimals()), earlyPariticipantWeiPrice); if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount); // Update totals weiRaised = safeAdd(weiRaised,weiAmount); tokensSold = safeAdd(tokensSold,tokenAmount); // Check that we did not bust the cap require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); if (safeAdd(whitelistPrincipleLockPercentage,whitelistBonusPercentage) > 0) { uint256 principleAmount = safeDiv(safeMul(tokenAmount, 100), safeAdd(whitelistBonusPercentage, 100)); uint256 bonusLockAmount = safeDiv(safeMul(whitelistBonusPercentage, principleAmount), 100); uint256 principleLockAmount = safeDiv(safeMul(whitelistPrincipleLockPercentage, principleAmount), 100); uint256 totalLockAmount = safeAdd(principleLockAmount, bonusLockAmount); TokenVesting tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); require(totalLockAmount <= tokenAmount); assignTokens(tokenVestingAddress,totalLockAmount); // set vesting with default schedule tokenVesting.setVesting(receiver, principleLockAmount, whitelistPrincipleLockPeriod, bonusLockAmount, whitelistBonusLockPeriod); } // assign remaining tokens to contributor if (tokenAmount - totalLockAmount > 0) { assignTokens(receiver, tokenAmount - totalLockAmount); } // Pocket the money require(multisigWallet.send(weiAmount)); // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, customerId); } else if(getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); require(tokenAmount != 0); if(investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount); // Update totals weiRaised = safeAdd(weiRaised,weiAmount); tokensSold = safeAdd(tokensSold,tokenAmount); // Check that we did not bust the cap require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)); assignTokens(receiver, tokenAmount); // Pocket the money require(multisigWallet.send(weiAmount)); // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, customerId); } else { // Unwanted state require(false); } } /** * allocate 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. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * @param weiPrice Price of a single full token in wei * */ function preallocate(address receiver, uint256 tokenAmount, uint256 weiPrice, uint256 principleLockAmount, uint256 principleLockPeriod, uint256 bonusLockAmount, uint256 bonusLockPeriod) public onlyAllocateAgent { uint256 weiAmount = (weiPrice * tokenAmount)/10**uint256(token.decimals()); // This can be also 0, we give out tokens for free uint256 totalLockAmount = 0; weiRaised = safeAdd(weiRaised,weiAmount); tokensSold = safeAdd(tokensSold,tokenAmount); investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount); // cannot lock more than total tokens totalLockAmount = safeAdd(principleLockAmount, bonusLockAmount); require(totalLockAmount <= tokenAmount); // assign locked token to Vesting contract if (totalLockAmount > 0) { TokenVesting tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); assignTokens(tokenVestingAddress,totalLockAmount); // set vesting with default schedule tokenVesting.setVesting(receiver, principleLockAmount, principleLockPeriod, bonusLockAmount, bonusLockPeriod); } // assign remaining tokens to contributor if (tokenAmount - totalLockAmount > 0) { assignTokens(receiver, tokenAmount - totalLockAmount); } // Tell us invest was success Invested(receiver, weiAmount, tokenAmount, 0); } /** * Track who is the customer making the payment so we can send thank you email. */ function investWithCustomerId(address addr, uint128 customerId) public payable { require(!requiredSignedAddress); require(customerId != 0); investInternal(addr, customerId); } /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { require(!requireCustomerId); require(!requiredSignedAddress); investInternal(addr, 0); } /** * Invest to tokens, recognize the payer and clear his address. * */ // function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable { // investWithSignedAddress(msg.sender, customerId, v, r, s); // } /** * Invest to tokens, recognize the payer. * */ function buyWithCustomerId(uint128 customerId) public payable { investWithCustomerId(msg.sender, customerId); } /** * The basic entry point to participate the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { invest(msg.sender); } /** * Finalize a succcesful crowdsale. * * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized require(!finalized); // Finalizing is optional. We only call it if we are given a finalizing agent. if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { finalizeAgent = addr; // Don't allow setting bad agent require(finalizeAgent.isFinalizeAgent()); } /** * 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); } /** * Allow addresses to do early participation. * * TODO: Fix spelling error in the name */ function setEarlyParicipantWhitelist(address addr, bool status) public onlyAllocateAgent { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } function setWhiteList(address[] _participants) public onlyAllocateAgent { require(_participants.length > 0); uint256 participants = _participants.length; for (uint256 j=0; j<participants; j++) { require(_participants[j] != 0); earlyParticipantWhitelist[_participants[j]] = true; Whitelisted(_participants[j], true); } } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) public onlyOwner { require(now <= time); endsAt = time; EndsAtChanged(endsAt); } /** * Allow crowdsale owner to begin early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setStartAt(uint time) public onlyOwner { startsAt = time; StartAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { pricingStrategy = _pricingStrategy; // Don't allow setting bad agent require(pricingStrategy.isPricingStrategy()); } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change require(investorCount <= MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE); multisigWallet = addr; } /** * Allow load refunds back on the contract for the refunding. * * The team can transfer the funds back on the smart contract in the case the minimum goal was not reached.. */ function loadRefund() public payable inState(State.Failure) { require(msg.value != 0); loadedRefund = safeAdd(loadedRefund,msg.value); } /** * Investors can claim refund. */ function refund() public inState(State.Refunding) { uint256 weiValue = investedAmountOf[msg.sender]; require(weiValue != 0); investedAmountOf[msg.sender] = 0; weiRefunded = safeAdd(weiRefunded,weiValue); Refund(msg.sender, weiValue); require(msg.sender.send(weiValue)); } /** * @return true if the crowdsale has raised enough money to be a succes */ function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public constant returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public constant returns (bool sane) { return pricingStrategy.isSane(address(this)); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. */ function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane(address(this))) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; else return State.Failure; } /** This is for manual testing of multisig wallet interaction */ function setOwnerTestValue(uint val) public onlyOwner { ownerTestValue = val; } /** Interface marker. */ function isCrowdsale() public pure returns (bool) { return true; } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { require(getState() == state); _; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param weiAmount The amount of wei the investor tries to invest in the current transaction * @param tokenAmount The amount of tokens we try to give to the investor in the current transaction * @param weiRaisedTotal What would be our total raised balance after this transaction * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public constant returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; } /** * At the end of the successful crowdsale allocate % bonus of tokens to the team. * * Unlock tokens. * * BonusAllocationFinal must be set as the minting agent for the MintableToken. * */ contract BonusFinalizeAgent is FinalizeAgent, SafeMathLib { CrowdsaleToken public token; Crowdsale public crowdsale; uint256 public allocatedTokens; uint256 tokenCap; address walletAddress; function BonusFinalizeAgent(CrowdsaleToken _token, Crowdsale _crowdsale, uint256 _tokenCap, address _walletAddress) public { token = _token; crowdsale = _crowdsale; //crowdsale address must not be 0 require(address(crowdsale) != 0); tokenCap = _tokenCap; walletAddress = _walletAddress; } /* Can we run finalize properly */ function isSane() public view returns (bool) { return (token.mintAgents(address(this)) == true) && (token.releaseAgent() == address(this)); } /** Called once by crowdsale finalize() if the sale was success. */ function finalizeCrowdsale() public { // if finalized is not being called from the crowdsale // contract then throw require (msg.sender == address(crowdsale)); // get the total sold tokens count. uint256 tokenSupply = token.totalSupply(); allocatedTokens = safeSub(tokenCap,tokenSupply); if ( allocatedTokens > 0) { token.mint(walletAddress, allocatedTokens); } token.releaseTokenTransfer(); } } /** * ICO crowdsale contract that is capped by amout of ETH. * * - Tokens are dynamically created during the crowdsale * * */ contract MintedEthCappedCrowdsale is Crowdsale { /* Maximum amount of wei this crowdsale can raise. */ uint public weiCap; function MintedEthCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint256 _start, uint256 _end, uint256 _minimumFundingGoal, uint256 _weiCap, address _tokenVestingAddress) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal,_tokenVestingAddress) public { weiCap = _weiCap; } /** * Called from invest() to confirm if the curret investment does not break our cap rule. */ function isBreakingCap(uint256 weiAmount, uint256 tokenAmount, uint256 weiRaisedTotal, uint256 tokensSoldTotal) public constant returns (bool limitBroken) { return weiRaisedTotal > weiCap; } function isCrowdsaleFull() public constant returns (bool) { return weiRaised >= weiCap; } /** * Dynamically create tokens and assign them to the investor. */ function assignTokens(address receiver, uint256 tokenAmount) private { MintableToken mintableToken = MintableToken(token); mintableToken.mint(receiver, tokenAmount); } } /// @dev Tranche based pricing with special support for pre-ico deals. /// Implementing "first price" tranches, meaning, that if byers order is /// covering more than one tranche, the price of the lowest tranche will apply /// to the whole order. contract EthTranchePricing is PricingStrategy, Ownable, SafeMathLib { uint public constant MAX_TRANCHES = 10; // This contains all pre-ICO addresses, and their prices (weis per token) mapping (address => uint256) public preicoAddresses; /** * Define pricing schedule using tranches. */ struct Tranche { // Amount in weis when this tranche becomes active uint amount; // How many tokens per wei you will get while this tranche is active uint price; } // Store tranches in a fixed array, so that it can be seen in a blockchain explorer // Tranche 0 is always (0, 0) // (TODO: change this when we confirm dynamic arrays are explorable) Tranche[10] public tranches; // How many active tranches we have uint public trancheCount; /// @dev Contruction, creating a list of tranches /// @param _tranches uint[] tranches Pairs of (start amount, price) function EthTranchePricing(uint[] _tranches) public { // Need to have tuples, length check require(!(_tranches.length % 2 == 1 || _tranches.length >= MAX_TRANCHES*2)); trancheCount = _tranches.length / 2; uint256 highestAmount = 0; for(uint256 i=0; i<_tranches.length/2; i++) { tranches[i].amount = _tranches[i*2]; tranches[i].price = _tranches[i*2+1]; // No invalid steps require(!((highestAmount != 0) && (tranches[i].amount <= highestAmount))); highestAmount = tranches[i].amount; } // We need to start from zero, otherwise we blow up our deployment require(tranches[0].amount == 0); // Last tranche price must be zero, terminating the crowdale require(tranches[trancheCount-1].price == 0); } /// @dev This is invoked once for every pre-ICO address, set pricePerToken /// to 0 to disable /// @param preicoAddress PresaleFundCollector address /// @param pricePerToken How many weis one token cost for pre-ico investors function setPreicoAddress(address preicoAddress, uint pricePerToken) public onlyOwner { preicoAddresses[preicoAddress] = pricePerToken; } /// @dev Iterate through tranches. You reach end of tranches when price = 0 /// @return tuple (time, price) function getTranche(uint256 n) public constant returns (uint, uint) { return (tranches[n].amount, tranches[n].price); } function getFirstTranche() private constant returns (Tranche) { return tranches[0]; } function getLastTranche() private constant returns (Tranche) { return tranches[trancheCount-1]; } function getPricingStartsAt() public constant returns (uint) { return getFirstTranche().amount; } function getPricingEndsAt() public constant returns (uint) { return getLastTranche().amount; } function isSane(address _crowdsale) public view returns(bool) { // Our tranches are not bound by time, so we can't really check are we sane // so we presume we are ;) // In the future we could save and track raised tokens, and compare it to // the Crowdsale contract. return true; } /// @dev Get the current tranche or bail out if we are not in the tranche periods. /// @param weiRaised total amount of weis raised, for calculating the current tranche /// @return {[type]} [description] function getCurrentTranche(uint256 weiRaised) private constant returns (Tranche) { uint i; for(i=0; i < tranches.length; i++) { if(weiRaised < tranches[i].amount) { return tranches[i-1]; } } } /// @dev Get the current price. /// @param weiRaised total amount of weis raised, for calculating the current tranche /// @return The current price or 0 if we are outside trache ranges function getCurrentPrice(uint256 weiRaised) public constant returns (uint256 result) { return getCurrentTranche(weiRaised).price; } /// @dev Calculate the current price for buy in amount. function calculatePrice(uint256 value, uint256 weiRaised, uint256 tokensSold, address msgSender, uint256 decimals) public constant returns (uint256) { uint256 multiplier = 10 ** decimals; // This investor is coming through pre-ico if(preicoAddresses[msgSender] > 0) { return safeMul(value, multiplier) / preicoAddresses[msgSender]; } uint256 price = getCurrentPrice(weiRaised); return safeMul(value, multiplier) / price; } function() payable public { revert(); // No money on this contract } } /** * Contract to enforce Token Vesting */ contract TokenVesting is Allocatable, SafeMathLib { address public TokenAddress; /** keep track of total tokens yet to be released, * this should be less than or equal to tokens held by this contract. */ uint256 public totalUnreleasedTokens; struct VestingSchedule { uint256 startAt; uint256 principleLockAmount; uint256 principleLockPeriod; uint256 bonusLockAmount; uint256 bonusLockPeriod; uint256 amountReleased; bool isPrincipleReleased; bool isBonusReleased; } mapping (address => VestingSchedule) public vestingMap; event VestedTokensReleased(address _adr, uint256 _amount); function TokenVesting(address _TokenAddress) public { TokenAddress = _TokenAddress; } /** Function to set/update vesting schedule. PS - Amount cannot be changed once set */ function setVesting(address _adr, uint256 _principleLockAmount, uint256 _principleLockPeriod, uint256 _bonusLockAmount, uint256 _bonuslockPeriod) public onlyAllocateAgent { VestingSchedule storage vestingSchedule = vestingMap[_adr]; // data validation require(safeAdd(_principleLockAmount, _bonusLockAmount) > 0); //startAt is set current time as start time. vestingSchedule.startAt = block.timestamp; vestingSchedule.bonusLockPeriod = safeAdd(block.timestamp,_bonuslockPeriod); vestingSchedule.principleLockPeriod = safeAdd(block.timestamp,_principleLockPeriod); // check if enough tokens are held by this contract ERC20 token = ERC20(TokenAddress); uint256 _totalAmount = safeAdd(_principleLockAmount, _bonusLockAmount); require(token.balanceOf(this) >= safeAdd(totalUnreleasedTokens, _totalAmount)); vestingSchedule.principleLockAmount = _principleLockAmount; vestingSchedule.bonusLockAmount = _bonusLockAmount; vestingSchedule.isPrincipleReleased = false; vestingSchedule.isBonusReleased = false; totalUnreleasedTokens = safeAdd(totalUnreleasedTokens, _totalAmount); vestingSchedule.amountReleased = 0; } function isVestingSet(address adr) public constant returns (bool isSet) { return vestingMap[adr].principleLockAmount != 0 || vestingMap[adr].bonusLockAmount != 0; } /** Release tokens as per vesting schedule, called by contributor */ function releaseMyVestedTokens() public { releaseVestedTokens(msg.sender); } /** Release tokens as per vesting schedule, called by anyone */ function releaseVestedTokens(address _adr) public { VestingSchedule storage vestingSchedule = vestingMap[_adr]; uint256 _totalTokens = safeAdd(vestingSchedule.principleLockAmount, vestingSchedule.bonusLockAmount); // check if all tokens are not vested require(safeSub(_totalTokens, vestingSchedule.amountReleased) > 0); // calculate total vested tokens till now uint256 amountToRelease = 0; if (block.timestamp >= vestingSchedule.principleLockPeriod && !vestingSchedule.isPrincipleReleased) { amountToRelease = safeAdd(amountToRelease,vestingSchedule.principleLockAmount); vestingSchedule.amountReleased = safeAdd(vestingSchedule.amountReleased, amountToRelease); vestingSchedule.isPrincipleReleased = true; } if (block.timestamp >= vestingSchedule.bonusLockPeriod && !vestingSchedule.isBonusReleased) { amountToRelease = safeAdd(amountToRelease,vestingSchedule.bonusLockAmount); vestingSchedule.amountReleased = safeAdd(vestingSchedule.amountReleased, amountToRelease); vestingSchedule.isBonusReleased = true; } // transfer vested tokens require(amountToRelease > 0); ERC20 token = ERC20(TokenAddress); token.transfer(_adr, amountToRelease); // decrement overall unreleased token count totalUnreleasedTokens = safeSub(totalUnreleasedTokens, amountToRelease); VestedTokensReleased(_adr, amountToRelease); } }
allocate 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. Investor count is not handled; it is assumed this goes for multiple investors and the token distribution happens outside the smart contract flow. No money is exchanged, as the crowdsale team already have received the payment. weiPrice Price of a single full token in wei/ cannot lock more than total tokens assign locked token to Vesting contract to prevent minting of tokens which will be useless as vesting amount cannot be updated set vesting with default schedule assign remaining tokens to contributor
function preallocate(address receiver, uint256 tokenAmount, uint256 weiPrice, uint256 principleLockAmount, uint256 principleLockPeriod, uint256 bonusLockAmount, uint256 bonusLockPeriod) public onlyAllocateAgent { uint256 totalLockAmount = 0; weiRaised = safeAdd(weiRaised,weiAmount); tokensSold = safeAdd(tokensSold,tokenAmount); investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount); totalLockAmount = safeAdd(principleLockAmount, bonusLockAmount); require(totalLockAmount <= tokenAmount); if (totalLockAmount > 0) { TokenVesting tokenVesting = TokenVesting(tokenVestingAddress); require(!tokenVesting.isVestingSet(receiver)); assignTokens(tokenVestingAddress,totalLockAmount); tokenVesting.setVesting(receiver, principleLockAmount, principleLockPeriod, bonusLockAmount, bonusLockPeriod); } if (tokenAmount - totalLockAmount > 0) { assignTokens(receiver, tokenAmount - totalLockAmount); } }
10,178,046
./full_match/43114/0xc9070B3EFE0aacC5AfB4B31C5DbDCA7C6B4bAAA9/sources/contracts/YieldWolf.sol
deposits stake tokens on behalf of another user _pid the pool id _depositAmount amount of tokens to transfer from msg.sender _to address of the beneficiary/
function depositTo( uint256 _pid, uint256 _depositAmount, address _to ) external { _deposit(_pid, _depositAmount, _to); }
4,507,336
/** #LUCK-INU #LUCK-INU features: 3% fee auto added to the liquidity pool 5% fee auto distributed to all holders 2% (5% when timer is under 10 minutes) fee auto added to the pot. Last 7 buyers before the timer runs out split 40% of the pot proportional to their buys. Absolute last buyer gets 30% of the pot. 30% carries over to next round. 50% Supply is burned at start. */ // SPDX-License-Identifier: BSD pragma solidity ^0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "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, "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, "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, "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, "modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract LUCKINU is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "LUCK-INU"; string private _symbol = "LUCK-INU"; uint8 private _decimals = 9; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 3; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _potFee = 2; uint256 private _previousPotFee = _potFee; uint256 public _potFeeExtra = 5; uint256 private _previousPotFeeExtra = _potFeeExtra; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap; struct GameSettings { uint256 maxTxAmount; // maximum number of tokens in one transfer uint256 tokenSwapThreshold; // number of tokens needed in contract to swap and sell uint256 minimumBuyForPotEligibility; //minimum buy to be eligible to win share of the pot uint256 tokensToAddOneSecond; //number of tokens that will add one second to the timer uint256 maxTimeLeft; //maximum number of seconds the timer can be uint256 potFeeExtraTimeLeftThreshold; //if timer is under this value, the potFeeExtra is used uint256 eliglblePlayers; //number of players eligible for winning share of the pot uint256 potPayoutPercent; // what percent of the pot is paid out, vs. carried over to next round uint256 lastBuyerPayoutPercent; //what percent of the paid-out-pot is paid to absolute last buyer } GameSettings public gameSettings; bool public gameIsActive = false; uint256 private roundNumber; uint256 private timeLeftAtLastBuy; uint256 private lastBuyBlock; uint256 private liquidityTokens; uint256 private potTokens; address private liquidityAddress; address private gameSettingsUpdaterAddress; address private presaleContractAddress; mapping (uint256 => Buyer[]) buyersByRound; modifier onlyGameSettingsUpdater() { require(_msgSender() == gameSettingsUpdaterAddress, "caller != game settings updater"); _; } event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event GameSettingsUpdated( uint256 maxTxAmount, uint256 tokenSwapThreshold, uint256 minimumBuyForPotEligibility, uint256 tokensToAddOneSecond, uint256 maxTimeLeft, uint256 potFeeExtraTimeLeftThreshold, uint256 eliglblePlayers, uint256 potPayoutPercent, uint256 lastBuyerPayoutPercent ); event GameSettingsUpdaterUpdated( address oldGameSettingsUpdater, address newGameSettingsUpdater ); event RoundStarted( uint256 number, uint256 potValue ); event Buy( bool indexed isEligible, address indexed buyer, uint256 amount, uint256 timeLeftBefore, uint256 timeLeftAfter, uint256 blockTime, uint256 blockNumber ); event RoundPayout( uint256 indexed roundNumber, address indexed buyer, uint256 amount, bool success ); event RoundEnded( uint256 number, address[] winners, uint256[] winnerAmountsRound ); enum TransferType { Normal, Buy, Sell, RemoveLiquidity } struct Buyer { address buyer; uint256 amount; uint256 timeLeftBefore; uint256 timeLeftAfter; uint256 blockTime; uint256 blockNumber; } constructor () public { gameSettings = GameSettings( 1000000 * 10**9, //maxTxAmount is 1 million tokens 200000 * 10**9, //tokenSwapThreshold is 200000 tokens 10000 * 10**9, //minimumBuyForPotEligibility is 10000 tokens 1000 * 10**9, //tokensToAddOneSecond is 1000 tokens 21600, //maxTimeLeft is 6 hours 600, //potFeeExtraTimeLeftThreshold is 10 minutes 7, //eliglblePlayers is 7 70, //potPayoutPercent is 70% 43 //lastBuyerPayoutPerent is 43% of the 70%, which is ~30% overall ); liquidityAddress = _msgSender(); gameSettingsUpdaterAddress = _msgSender(); _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[_msgSender()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } // for any non-zero value it updates the game settings to that value function updateGameSettings( uint256 maxTxAmount, uint256 tokenSwapThreshold, uint256 minimumBuyForPotEligibility, uint256 tokensToAddOneSecond, uint256 maxTimeLeft, uint256 potFeeExtraTimeLeftThreshold, uint256 eliglblePlayers, uint256 potPayoutPercent, uint256 lastBuyerPayoutPercent ) public onlyGameSettingsUpdater { if(maxTxAmount > 0) { require(maxTxAmount >= 1000000 * 10**9 && maxTxAmount <= 10000000 * 10**9); gameSettings.maxTxAmount = maxTxAmount; } if(tokenSwapThreshold > 0) { require(tokenSwapThreshold >= 100000 * 10**9 && tokenSwapThreshold <= 1000000 * 10**9); gameSettings.tokenSwapThreshold = tokenSwapThreshold; } if(minimumBuyForPotEligibility > 0) { require(minimumBuyForPotEligibility >= 1000 * 10**9 && minimumBuyForPotEligibility <= 100000 * 10**9); gameSettings.minimumBuyForPotEligibility = minimumBuyForPotEligibility; } if(tokensToAddOneSecond > 0) { require(tokensToAddOneSecond >= 100 * 10**9 && tokensToAddOneSecond <= 10000 * 10**9); gameSettings.tokensToAddOneSecond = tokensToAddOneSecond; } if(maxTimeLeft > 0) { require(maxTimeLeft >= 7200 && maxTimeLeft <= 86400); gameSettings.maxTimeLeft = maxTimeLeft; } if(potFeeExtraTimeLeftThreshold > 0) { require(potFeeExtraTimeLeftThreshold >= 60 && potFeeExtraTimeLeftThreshold <= 3600); gameSettings.potFeeExtraTimeLeftThreshold = potFeeExtraTimeLeftThreshold; } if(eliglblePlayers > 0) { require(eliglblePlayers >= 3 && eliglblePlayers <= 15); gameSettings.eliglblePlayers = eliglblePlayers; } if(potPayoutPercent > 0) { require(potPayoutPercent >= 30 && potPayoutPercent <= 99); gameSettings.potPayoutPercent = potPayoutPercent; } if(lastBuyerPayoutPercent > 0) { require(lastBuyerPayoutPercent >= 10 && lastBuyerPayoutPercent <= 60); gameSettings.lastBuyerPayoutPercent = lastBuyerPayoutPercent; } emit GameSettingsUpdated( maxTxAmount, tokenSwapThreshold, minimumBuyForPotEligibility, tokensToAddOneSecond, maxTimeLeft, potFeeExtraTimeLeftThreshold, eliglblePlayers, potPayoutPercent, lastBuyerPayoutPercent ); } function renounceGameSettingsUpdater() public virtual onlyGameSettingsUpdater { emit GameSettingsUpdaterUpdated(gameSettingsUpdaterAddress, address(0)); gameSettingsUpdaterAddress = address(0); } function setPresaleContractAddress(address _address) public onlyOwner { require(presaleContractAddress == address(0)); presaleContractAddress = _address; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount > allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance < zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be < supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be < total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function startGame() public onlyOwner { require(!gameIsActive); // start on round 1 roundNumber = roundNumber.add(1); timeLeftAtLastBuy = gameSettings.maxTimeLeft; lastBuyBlock = block.number; gameIsActive = true; emit RoundStarted( roundNumber, potValue() ); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidityAndPot, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidityAndPot); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidityAndPot = calculateLiquidityAndPotFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidityAndPot); return (tTransferAmount, tFee, tLiquidityAndPot); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidityAndPot, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidityAndPot = tLiquidityAndPot.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidityAndPot); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidityAndPot(uint256 tLiquidityAndPot) private { uint256 currentRate = _getRate(); uint256 rLiquidityAndPot = tLiquidityAndPot.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidityAndPot); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidityAndPot); //keep track of ratio of liquidity vs. pot uint256 potFee = currentPotFee(); uint256 totalFee = potFee.add(_liquidityFee); if(totalFee > 0) { potTokens = potTokens.add(tLiquidityAndPot.mul(potFee).div(totalFee)); liquidityTokens = liquidityTokens.add(tLiquidityAndPot.mul(_liquidityFee).div(totalFee)); } } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityAndPotFee(uint256 _amount) private view returns (uint256) { uint256 currentPotFee = currentPotFee(); return _amount.mul(_liquidityFee.add(currentPotFee)).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _potFee == 0 && _potFeeExtra == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousPotFee = _potFee; _previousPotFeeExtra = _potFeeExtra; _taxFee = 0; _liquidityFee = 0; _potFee = 0; _potFeeExtra = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _potFee = _previousPotFee; _potFeeExtra = _previousPotFeeExtra; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function getTransferType( address from, address to) private view returns (TransferType) { if(from == uniswapV2Pair) { if(to == address(uniswapV2Router)) { return TransferType.RemoveLiquidity; } return TransferType.Buy; } if(to == uniswapV2Pair) { return TransferType.Sell; } if(from == address(uniswapV2Router)) { return TransferType.RemoveLiquidity; } return TransferType.Normal; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "transfer from the zero address"); require(to != address(0), "transfer to the zero address"); require(amount > 0, "Transfer amount must be > 0"); TransferType transferType = getTransferType(from, to); if( gameIsActive && !inSwap && transferType != TransferType.RemoveLiquidity && from != liquidityAddress && to != liquidityAddress && from != presaleContractAddress ) { require(amount <= gameSettings.maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } completeRoundWhenNoTimeLeft(); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= gameSettings.tokenSwapThreshold; if( gameIsActive && overMinTokenBalance && !inSwap && transferType != TransferType.Buy && from != liquidityAddress && to != liquidityAddress ) { inSwap = true; //Calculate how much to swap and liquify, and how much to just swap for the pot uint256 totalTokens = liquidityTokens.add(potTokens); if(totalTokens > 0) { uint256 swapTokens = contractTokenBalance.mul(liquidityTokens).div(totalTokens); //add liquidity swapAndLiquify(swapTokens); } //sell the rest uint256 sellTokens = balanceOf(address(this)); swapTokensForEth(sellTokens); liquidityTokens = 0; potTokens = 0; inSwap = false; } //indicates if fee should be deducted from transfer bool takeFee = gameIsActive; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); if( gameIsActive && transferType == TransferType.Buy ) { handleBuyer(to, amount); } } function handleBuyer(address buyer, uint256 amount) private { int256 oldTimeLeft = timeLeft(); if(oldTimeLeft < 0) { return; } int256 newTimeLeft = oldTimeLeft + int256(amount / gameSettings.tokensToAddOneSecond); bool isEligible = buyer != address(uniswapV2Router) && !_isExcludedFromFee[buyer] && amount >= gameSettings.minimumBuyForPotEligibility; if(isEligible) { Buyer memory newBuyer = Buyer( buyer, amount, uint256(oldTimeLeft), uint256(newTimeLeft), block.timestamp, block.number ); Buyer[] storage buyers = buyersByRound[roundNumber]; bool added = false; // check if buyer would have a 2nd entry in last 7, and remove old one for(int256 i = int256(buyers.length) - 1; i >= 0 && i > int256(buyers.length) - int256(gameSettings.eliglblePlayers); i--) { Buyer storage existingBuyer = buyers[uint256(i)]; if(existingBuyer.buyer == buyer) { // shift all buyers after back one, and put new buyer at end of array for(uint256 j = uint256(i).add(1); j < buyers.length; j = j.add(1)) { buyers[j.sub(1)] = buyers[j]; } buyers[buyers.length.sub(1)] = newBuyer; added = true; break; } } if(!added) { buyers.push(newBuyer); } } if(newTimeLeft < 0) { newTimeLeft = 0; } else if(newTimeLeft > int256(gameSettings.maxTimeLeft)) { newTimeLeft = int256(gameSettings.maxTimeLeft); } timeLeftAtLastBuy = uint256(newTimeLeft); lastBuyBlock = block.number; emit Buy( isEligible, buyer, amount, uint256(oldTimeLeft), uint256(newTimeLeft), block.timestamp, block.number ); } function swapAndLiquify(uint256 swapAmount) private { // split the value able to be liquified into halves uint256 half = swapAmount.div(2); uint256 otherHalf = swapAmount.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidityAndPot); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidityAndPot); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidityAndPot) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidityAndPot(tLiquidityAndPot); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function potValue() public view returns (uint256) { return address(this).balance.mul(gameSettings.potPayoutPercent).div(100); } function timeLeft() public view returns (int256) { if(!gameIsActive) { return 0; } uint256 blocksSinceLastBuy = block.number.sub(lastBuyBlock); return int256(timeLeftAtLastBuy) - int256(blocksSinceLastBuy.mul(3)); } function currentPotFee() public view returns (uint256) { if(timeLeft() < int256(gameSettings.potFeeExtraTimeLeftThreshold)) { return _potFeeExtra; } return _potFee; } function completeRoundWhenNoTimeLeft() public { int256 secondsLeft = timeLeft(); if(secondsLeft >= 0) { return; } (address[] memory buyers, uint256[] memory payoutAmounts) = _getPayoutAmounts(); uint256 lastRoundNumber = roundNumber; roundNumber = roundNumber.add(1); timeLeftAtLastBuy = gameSettings.maxTimeLeft; lastBuyBlock = block.number; for(uint256 i = 0; i < buyers.length; i = i.add(1)) { uint256 amount = payoutAmounts[i]; if(amount > 0) { (bool success, ) = buyers[i].call { value: amount, gas: 5000 }(""); emit RoundPayout( lastRoundNumber, buyers[i], amount, success ); } } emit RoundEnded( lastRoundNumber, buyers, payoutAmounts ); emit RoundStarted( roundNumber, potValue() ); } function _getPayoutAmounts() internal view returns (address[] memory buyers, uint256[] memory payoutAmounts) { buyers = new address[](gameSettings.eliglblePlayers); payoutAmounts = new uint256[](gameSettings.eliglblePlayers); Buyer[] storage roundBuyers = buyersByRound[roundNumber]; if(roundBuyers.length > 0) { uint256 totalPayout = potValue(); uint256 lastBuyerPayout = totalPayout.mul(gameSettings.lastBuyerPayoutPercent).div(100); uint256 payoutLeft = totalPayout.sub(lastBuyerPayout); uint256 numberOfWinners = roundBuyers.length > gameSettings.eliglblePlayers ? gameSettings.eliglblePlayers : roundBuyers.length; uint256 amountLeft; for(int256 i = int256(roundBuyers.length) - 1; i >= int256(roundBuyers.length) - int256(numberOfWinners); i--) { amountLeft = amountLeft.add(roundBuyers[uint256(i)].amount); } uint256 returnIndex = 0; for(int256 i = int256(roundBuyers.length) - 1; i >= int256(roundBuyers.length) - int256(numberOfWinners); i--) { uint256 amount = roundBuyers[uint256(i)].amount; uint256 payout = 0; if(amountLeft > 0) { payout = payoutLeft.mul(amount).div(amountLeft); } amountLeft = amountLeft.sub(amount); payoutLeft = payoutLeft.sub(payout); buyers[returnIndex] = roundBuyers[uint256(i)].buyer; payoutAmounts[returnIndex] = payout; if(returnIndex == 0) { payoutAmounts[0] = payoutAmounts[0].add(lastBuyerPayout); } returnIndex = returnIndex.add(1); } } } function gameStats() external view returns (uint256 currentRoundNumber, int256 currentTimeLeft, uint256 currentPotValue, uint256 currentTimeLeftAtLastBuy, uint256 currentLastBuyBlock, uint256 currentBlockTime, uint256 currentBlockNumber, address[] memory lastBuyerAddress, uint256[] memory lastBuyerData) { currentRoundNumber = roundNumber; currentTimeLeft = timeLeft(); currentPotValue = potValue(); currentTimeLeftAtLastBuy = timeLeftAtLastBuy; currentLastBuyBlock = lastBuyBlock; currentBlockTime = block.timestamp; currentBlockNumber = block.number; lastBuyerAddress = new address[](gameSettings.eliglblePlayers); lastBuyerData = new uint256[](gameSettings.eliglblePlayers.mul(6)); Buyer[] storage buyers = buyersByRound[roundNumber]; uint256 iteration = 0; (, uint256[] memory payoutAmounts) = _getPayoutAmounts(); for(int256 i = int256(buyers.length) - 1; i >= 0; i--) { Buyer storage buyer = buyers[uint256(i)]; lastBuyerAddress[iteration] = buyer.buyer; lastBuyerData[iteration.mul(6).add(0)] = buyer.amount; lastBuyerData[iteration.mul(6).add(1)] = buyer.timeLeftBefore; lastBuyerData[iteration.mul(6).add(2)] = buyer.timeLeftAfter; lastBuyerData[iteration.mul(6).add(3)] = buyer.blockTime; lastBuyerData[iteration.mul(6).add(4)] = buyer.blockNumber; lastBuyerData[iteration.mul(6).add(5)] = payoutAmounts[iteration]; iteration = iteration.add(1); if(iteration == gameSettings.eliglblePlayers) { break; } } } }
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, "addition overflow"); return c; }
12,912,195
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Crowdsale/PausableCrowdsale.sol"; import "./Crowdsale/DisabableCrowdsale.sol"; contract GauCrowdsale is DisabableCrowdsale { constructor( uint256 __ethRate, address payable wallet, IERC20 gauf) DisabableCrowdsale( __ethRate, wallet, gauf) {} } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Crowdsale.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title PausableCrowdsale * @dev Extension of Crowdsale contract where purchases can be paused and unpaused by the pauser role. */ contract PausableCrowdsale is Crowdsale, Pausable, Ownable { address private _keeper; constructor(uint256 rate, address payable wallet, IERC20 token) Crowdsale(rate, wallet, token) { } modifier onlyKeeper(){ require(msg.sender == _keeper, 'onlyKeeper: Sender is not keeper'); _; } /** * @dev Implementation of set address of Keeper contract * Ownable functionality implemented to restrict access */ function setKeeper(address __keeper) public virtual onlyOwner { _keeper = __keeper; } /** * @dev Public implementation to get keeper address */ function keeper() public view returns(address){ return _keeper; } /** * @dev Public implementation of _pause function from Pausable. * Ownable functionality implemented to restrict access */ function pause() public virtual onlyOwner{ _pause(); } /** * @dev Public implementation of _unpause function from Pausable. * Ownable functionality implemented to restrict access */ function unpause() public virtual onlyOwner{ _unpause(); } /** * @dev Public implementation of _setNewEthRate from Crowdsale * onlyKeeperfunctionality implemented to restrict access * @param __newEthRate New rate of how many token units a buyer gets per wei. */ function setNewEthRate(uint256 __newEthRate) public onlyKeeper { super._setNewEthRate(__newEthRate); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use super to concatenate validations. * Adds the validation that the crowdsale must not be paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) override virtual internal view whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./PausableCrowdsale.sol"; import "../utils/Disabable.sol"; contract DisabableCrowdsale is PausableCrowdsale, Disabable { constructor( uint256 __ethRate, address payable wallet, IERC20 gauf) PausableCrowdsale( __ethRate, wallet, gauf) {} /** * @dev Implements the clean up before disabling the whole contract * after this, the whole crowdsale is totally useless, there should no * remain any kind of assets in the contract, and each public function * should revert. * * Note: there is no way to enable a contract again (turning disabled = true) * so this operation is irreversible */ function disable() public onlyOwner { //Get the amount of tokens remaining in the contract IERC20 _token = token(); uint256 amount = _token.balanceOf(address(this)); //return the amount of tokens left to the wallet if any if(amount > 0){ address _owner = owner(); _deliverTokens(_owner, amount); } //Finally we disable the whole smart contract _disable(); } /** * @dev Implementation of set address of Keeper contract * Ownable functionality implemented to restrict access */ function setKeeper(address __keeper) public override isNotDisabled onlyOwner { super.setKeeper(__keeper); } /** * @dev Public implementation of _pause function from Pausable. * Ownable functionality implemented to restrict access */ function pause() public override isNotDisabled onlyOwner{ super.pause(); } /** * @dev Public implementation of _unpause function from Pausable. * Ownable functionality implemented to restrict access */ function unpause() public override isNotDisabled onlyOwner{ super.unpause(); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use super to concatenate validations. * Adds the validation that the crowdsale must not be paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) override virtual internal view isNotDisabled { return super._preValidatePurchase(_beneficiary, _weiAmount); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.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 conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _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 ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _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 GaufPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * Event for rate change logging * @param amount amount of tokens purchased */ event RateUpdated(uint256 amount); /** * @param __rate Number of token units a buyer gets per wei * @dev 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 ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param __wallet Address where collected funds will be forwarded to * @param __token Address of the token being sold */ constructor (uint256 __rate, address payable __wallet, IERC20 __token) { require(__rate > 0, "Crowdsale: rate is 0"); require(__wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(__token) != address(0), "Crowdsale: token is the zero address"); _rate = __rate; _wallet = __wallet; _token = __token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ receive () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev Sets a new rate of how many token units a buyer gets per wei. * @param __newEthRate New rate of how many token units a buyer gets per wei. */ function _setNewEthRate(uint256 __newEthRate) internal virtual { _rate = __newEthRate; emit RateUpdated( __newEthRate); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant 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 GaufPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual{ require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @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 view virtual { // solhint-disable-previous-line no-empty-blocks } /** * @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 virtual{ _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual{ _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 virtual{ // solhint-disable-previous-line no-empty-blocks } /** * @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 virtual returns (uint256) { return weiAmount.mul(10**18).div(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic way to disable a smart contract * forever. Unlike to a pausable functionality, a disabled smart contract can't * be enable back. * * 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 * `isNotDisabled`, which can be applied to your functions to disable their. * * It provides a virtual function `disable` which should be used to make a clean * up of the whole system previous disabling the smart contract * */ abstract contract Disabable is Context { bool private disabled = false; event Disabled(); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { } /** * @dev Throws if disable is true */ modifier isNotDisabled() { require(disabled == false, "Disabable: This contract is disabled"); _; } /** * @dev Return the value of disabled */ function isDisable() public view returns(bool){ return disabled; } /** * @dev Disable the whole contract, functions that implements * `isNotDisabled()` modifier will revert . * * Note: there is no way to enable a contract again (turning disabled = true) * so this operation is irreversible */ function _disable() internal virtual isNotDisabled{ disabled = true; emit Disabled(); } }
Public implementation of _unpause function from Pausable. Ownable functionality implemented to restrict access/
function unpause() public virtual onlyOwner{ _unpause(); }
1,640,963
// SPDX-License-Identifier: MIT // File contracts/utils/introspection/IERC165.sol /** INTO THE METAVERSE https://twitter.com/adidasoriginals https://discord.com/invite/pixelvault */ 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 contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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 contracts/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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/utils/Strings.sol 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 contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. 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 { // 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 contracts/token/ERC721/extensions/ERC721URIStorage.sol pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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; } } pragma solidity ^0.8.0; contract AdidasOriginals is ERC721URIStorage, Ownable{ event mintOriginals (address indexed minter, uint256 startWith, uint256 times); uint256 public totalOriginal; uint256 public totalCount = 30000; //bruhTotal uint256 public maxBatch = 20; // bruhBatch uint256 public price = 0.2 ether; string public baseURI; bool public started; uint addressRegistryCount; constructor() ERC721("AdidasOriginals", "AO") { } modifier mintEnabled() { require(started, "not started"); _; } function totalSupply() public view virtual returns (uint256) { return totalOriginal; } function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } function changePrice(uint256 _newPrice) public onlyOwner { price = _newPrice; } function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner { _setTokenURI(_tokenId, _tokenURI); } function setNormalStart(bool _start) public onlyOwner { started = _start; } function mintOriginal(uint256 _times) payable public mintEnabled { require(_times >0 && _times <= maxBatch, "mint wrong number"); require(totalOriginal + _times <= totalCount, "too much"); require(msg.value == _times * price, "value error"); payable(owner()).transfer(msg.value); emit mintOriginals(_msgSender(), totalOriginal+1, _times); for(uint256 i=0; i< _times; i++){ _mint(_msgSender(), 1 + totalOriginal++); } } function adminMint(uint256 _times) payable public onlyOwner { require(_times >0 && _times <= maxBatch, "mint wrong number"); require(totalOriginal + _times <= totalCount, "too much"); require(msg.value == _times * price, "value error"); payable(owner()).transfer(msg.value); emit mintOriginals(_msgSender(), totalOriginal+1, _times); for(uint256 i=0; i< _times; i++){ _mint(_msgSender(), 1 + totalOriginal++); } } function adminMintGiveaways(address _addr) public onlyOwner { require(totalOriginal + 1 <= totalCount, "Mint amount will exceed total collection amount."); emit mintOriginals(_addr, totalOriginal+1, 1); _mint(_addr, 1 + totalOriginal++); } }
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); INTO THE METAVERSE }
6,118,505
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.0; interface ILendingPoolAddressesProviderV2 { /** * @notice Get the current address for Aave LendingPool * @dev Lending pool is the core contract on which to call deposit */ function getLendingPool() external view returns (address); } interface IAaveATokenV2 { /** * @notice returns the current total aToken balance of _user all interest collected included. * To obtain the user asset principal balance with interests excluded , ERC20 non-standard * method principalBalanceOf() can be used. */ function balanceOf(address _user) external view returns(uint256); } interface IAaveLendingPoolV2 { /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param reserve the address of the reserve * @param amount the amount to be deposited * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function deposit( address reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev withdraws the assets of user. * @param reserve the address of the reserve * @param amount the underlying amount to be redeemed * @param to address that will receive the underlying **/ function withdraw( address reserve, uint256 amount, address to ) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } } } } 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"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } 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; } } abstract contract AbstractIntegration is IPlatformIntegration, ImmutableModule, ReentrancyGuard { event PTokenAdded(address indexed _bAsset, address _pToken); event Deposit(address indexed _bAsset, address _pToken, uint256 _amount); event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount); event PlatformWithdrawal(address indexed bAsset, address pToken, uint256 totalAmount, uint256 userAmount); // mAsset has write access address public immutable mAssetAddress; // bAsset => pToken (Platform Specific Token Address) mapping(address => address) public override bAssetToPToken; // Full list of all bAssets supported here address[] internal bAssetsMapped; /** * @param _nexus Address of the Nexus * @param _mAsset Address of mAsset */ constructor( address _nexus, address _mAsset ) ReentrancyGuard() ImmutableModule(_nexus) { require(_mAsset != address(0), "Invalid mAsset address"); mAssetAddress = _mAsset; } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyMasset() { require(msg.sender == mAssetAddress, "Only the mAsset can execute"); _; } /*************************************** CONFIG ****************************************/ /** * @dev Provide support for bAsset by passing its pToken address. * This method can only be called by the system Governor * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function setPTokenAddress(address _bAsset, address _pToken) external onlyGovernor { _setPTokenAddress(_bAsset, _pToken); } /** * @dev Provide support for bAsset by passing its pToken address. * Add to internal mappings and execute the platform specific, * abstract method `_abstractSetPToken` * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function _setPTokenAddress(address _bAsset, address _pToken) internal { require(bAssetToPToken[_bAsset] == address(0), "pToken already set"); require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses"); bAssetToPToken[_bAsset] = _pToken; bAssetsMapped.push(_bAsset); emit PTokenAdded(_bAsset, _pToken); _abstractSetPToken(_bAsset, _pToken); } function _abstractSetPToken(address _bAsset, address _pToken) internal virtual; /** * @dev Simple helper func to get the min of two values */ function _min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } // External // Libs /** * @title AaveV2Integration * @author Stability Labs Pty. Ltd. * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */ contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable basketManager; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _mAsset Address of mAsset * @param _platformAddress Generic platform address */ constructor( address _nexus, address _mAsset, address _platformAddress, address _basketManager ) AbstractIntegration(_nexus, _mAsset) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; basketManager = _basketManager; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); // Official checksummed AAVE token address // https://ethplorer.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 address aaveToken = address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); MassetHelpers.safeInfiniteApprove(aaveToken, liquidator); emit RewardTokenApproved(address(aaveToken), liquidator); } /*************************************** CORE ****************************************/ /** * @dev Modifier to allow function calls only from the Governor. */ modifier massetOrManager() { require(msg.sender == mAssetAddress || msg.sender == basketManager, "Only mAsset or basketManager can execute"); _; } /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override massetOrManager nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if(_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyMasset nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyMasset nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if(_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyMasset nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken(address _bAsset, address /*_pToken*/) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
Approves Liquidator to spend reward tokens/ Official checksummed AAVE token address https:ethplorer.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9
function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); address aaveToken = address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); MassetHelpers.safeInfiniteApprove(aaveToken, liquidator); emit RewardTokenApproved(address(aaveToken), liquidator); }
626,318
./full_match/100/0x3e1672EA518dc3CD670C930E290c4A9B2c55403B/sources/contracts/GivBacksRelayer/GIVBacksRelayer.sol
@inheritdoc IGIVBacksRelayer
function hashBatch( uint256 _nonce, address[] calldata recipients, uint256[] calldata amounts ) external pure override returns (bytes32) { return _hashBatch(_nonce, recipients, amounts); }
14,265,690
./partial_match/4/0x30308D033E6Faecf5Be7171D606757C8141dA39E/sources/Voting.sol
mapping field below is equivalent to an associative array or hash./ Solidity doesn't let you pass in an array of strings in the constructor (yet)./ This is the constructor which will be called once when you/
function Voting(bytes32[] candidateNames) public { candidateList = candidateNames; }
8,538,189
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) external restricted { last_completed_migration = completed; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/INut.sol"; import "./lib/Governable.sol"; contract Nut is ERC20, Governable, INut { using SafeMath for uint; address public distributor; uint public constant MAX_TOKENS = 1000000 ether; // total amount of NUT tokens uint public constant SINK_FUND = 200000 ether; // 20% of tokens goes to sink fund constructor (string memory name, string memory symbol, address sinkAddr) ERC20(name, symbol) { _mint(sinkAddr, SINK_FUND); __Governable__init(); } /// @dev Set the new distributor function setNutDistributor(address addr) external onlyGov { distributor = addr; } /// @dev Mint nut tokens to receipt function mint(address receipt, uint256 amount) external override { require(msg.sender == distributor, "must be called by distributor"); require(amount.add(this.totalSupply()) < MAX_TOKENS, "cannot mint more than MAX_TOKENS"); _mint(receipt, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface INut { function mint(address receipt, uint amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/Initializable.sol"; contract Governable is Initializable { address public governor; address public pendingGovernor; modifier onlyGov() { require(msg.sender == governor, 'bad gov'); _; } function __Governable__init() internal initializer { governor = msg.sender; } function __Governable__init(address _governor) internal initializer { governor = _governor; } /// @dev Set the pending governor, which will be the governor once accepted. /// @param addr The address of the pending governor. function setPendingGovernor(address addr) external onlyGov { pendingGovernor = addr; } /// @dev Accept to become the new governor. Must be called by the pending governor. function acceptGovernor() external { require(msg.sender == pendingGovernor, 'no pend'); pendingGovernor = address(0); governor = msg.sender; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/INutDistributor.sol"; import "./interfaces/INut.sol"; import "./interfaces/IPriceOracle.sol"; import "./lib/Governable.sol"; /* This contract distributes nut tokens based on staking unstaking during the staking period. It generates an array of "value times blocks" for each token/lender pair and "total value times block" for each token. It then distributes the rewards across the array. One issue is that each unstake/stake requires a calculation to determine the fraction of the pool owned by a lender. To avoid having to loop across all epochs and use up gas, this algorithm relies on the fact that all future epochs have the same value. So the vtb and totalVtb arrays keep an index of the last epoch in which there was a partial stake and unstake of tokens and then the epochs beyond that all of the same value which is stored in futureVtbMap and futureTotalVtbMap. */ contract NutDistributor is Governable, INutDistributor { using SafeMath for uint; using SafeERC20 for IERC20; struct Echo { uint id; uint endBlock; uint amount; } address public nutmeg; address public nut; address public oracle; uint public constant MAX_NUM_POOLS = 256; uint public DIST_START_BLOCK; // starting block of echo 0 uint public constant NUM_EPOCH = 15; // # of epochs uint public BLOCKS_PER_EPOCH; // # of blocks per epoch uint public constant DIST_START_AMOUNT = 250000 ether; // # of tokens distributed at epoch 0 uint public constant DIST_MIN_AMOUNT = 18750 ether; // min # of tokens distributed at any epoch uint public CURRENT_EPOCH; mapping(address => bool) addedPoolMap; address[] public pools; mapping(uint => Echo) public echoMap; mapping(uint => bool) public distCompletionMap; // the term vtb is short for value times blocks mapping(address => uint[15]) public totalVtbMap; // pool => total vtb, i.e., valueTimesBlocks. mapping(address => uint[15]) public totalNutMap; // pool => total Nut awarded. mapping(address => mapping( address => uint[15] ) ) public vtbMap; // pool => lender => vtb. mapping(address => uint) futureTotalVtbMap; mapping(address => mapping( address => uint) ) futureVtbMap; mapping(address => uint) futureTotalVtbEpoch; mapping(address => mapping( address => uint) ) futureVtbEpoch; modifier onlyNutmeg() { require(msg.sender == nutmeg, 'only nutmeg can call'); _; } /// @dev Set the Nutmeg function setNutmegAddress(address addr) external onlyGov { nutmeg = addr; } /// @dev Set the oracle function setPriceOracle(address addr) external onlyGov { oracle = addr; } function initialize(address nutAddr, address _governor) public initializer{ nut = nutAddr; DIST_START_BLOCK = block.number; BLOCKS_PER_EPOCH = 80640; __Governable__init(_governor); // config echoMap which indicates how many tokens will be distributed at each epoch for (uint i = 0; i < NUM_EPOCH; i++) { Echo storage echo = echoMap[i]; echo.id = i; echo.endBlock = DIST_START_BLOCK.add(BLOCKS_PER_EPOCH.mul(i.add(1))); uint amount = DIST_START_AMOUNT.div(i.add(1)); if (amount < DIST_MIN_AMOUNT) { amount = DIST_MIN_AMOUNT; } echo.amount = amount; } } function inNutDistribution() external override view returns(bool) { return (block.number >= DIST_START_BLOCK && block.number < DIST_START_BLOCK.add(BLOCKS_PER_EPOCH.mul(NUM_EPOCH))); } /// @notice Update valueTimesBlocks of pools and the lender when they stake or unstake /// @param token Base token of the pool. /// @param lender Address of the lender. /// @param incAmount to stake or unstake /// @param decAmount false=subtract/unstake true=add/stake function updateVtb(address token, address lender, uint incAmount, uint decAmount) external override onlyNutmeg { require(block.number >= DIST_START_BLOCK, 'updateVtb: invalid block number'); require(incAmount == 0 || decAmount == 0, 'updateVtb: update amount is invalid'); uint amount = incAmount.add(decAmount); require(amount > 0, 'updateVtb: update amount should be positive'); // get current epoch CURRENT_EPOCH = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); if (CURRENT_EPOCH >= NUM_EPOCH) return; _fillVtbGap(token, lender); _fillTotalVtbGap(token); uint dv = echoMap[CURRENT_EPOCH].endBlock.sub( block.number ).mul(amount); uint epochDv = BLOCKS_PER_EPOCH.mul(amount); if (incAmount > 0) { vtbMap[token][lender][CURRENT_EPOCH] = vtbMap[token][lender][CURRENT_EPOCH].add(dv); totalVtbMap[token][CURRENT_EPOCH] = totalVtbMap[token][CURRENT_EPOCH].add(dv); futureVtbMap[token][lender] = futureVtbMap[token][lender].add(epochDv); futureTotalVtbMap[token] = futureTotalVtbMap[token].add(epochDv); } else { vtbMap[token][lender][CURRENT_EPOCH] = vtbMap[token][lender][CURRENT_EPOCH].sub(dv); totalVtbMap[token][CURRENT_EPOCH] = totalVtbMap[token][CURRENT_EPOCH].sub(dv); futureVtbMap[token][lender] = futureVtbMap[token][lender].sub(epochDv); futureTotalVtbMap[token] = futureTotalVtbMap[token].sub(epochDv); } if (!addedPoolMap[token]) { pools.push(token); addedPoolMap[token] = true; } } // @dev This function fills the array between the last epoch at which things were calculated and the current epoch. function _fillVtbGap(address token, address lender) internal { if (futureVtbEpoch[token][lender] > CURRENT_EPOCH || CURRENT_EPOCH >= NUM_EPOCH ) return; uint futureVtb = futureVtbMap[token][lender]; for (uint i = futureVtbEpoch[token][lender]; i <= CURRENT_EPOCH; i++) { vtbMap[token][lender][i] = futureVtb; } futureVtbEpoch[token][lender] = CURRENT_EPOCH.add(1); } // @dev This function fills the array between the last epoch at which things were calculated and the current epoch. function _fillTotalVtbGap(address token) internal { if (futureTotalVtbEpoch[token] > CURRENT_EPOCH || CURRENT_EPOCH >= NUM_EPOCH ) return; uint futureTotalVtb = futureTotalVtbMap[token]; for (uint i = futureTotalVtbEpoch[token]; i <= CURRENT_EPOCH; i++) { totalVtbMap[token][i] = futureTotalVtb; } futureTotalVtbEpoch[token] = CURRENT_EPOCH.add(1); } /// @dev Distribute NUT tokens for the previous epoch function distribute() external onlyGov { require(oracle != address(0), 'distribute: no oracle available'); // get current epoch uint currEpochId = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); require(currEpochId > 0, 'distribute: nut token distribution not ready'); require(currEpochId < NUM_EPOCH.add(1), 'distribute: nut token distribution is over'); // distribute the nut tokens for the previous epoch. uint prevEpochId = currEpochId.sub(1); require(!distCompletionMap[prevEpochId], 'distribute: distribution is completed'); // mint nut tokens uint amount = echoMap[prevEpochId].amount; INut(nut).mint(address(this), amount); uint numOfPools = pools.length < MAX_NUM_POOLS ? pools.length : MAX_NUM_POOLS; uint sumOfDv; uint actualSumOfNut; for (uint i = 0; i < numOfPools; i++) { uint price = IPriceOracle(oracle).getPrice(pools[i]); uint dv = price.mul(getTotalVtb(pools[i],prevEpochId)); sumOfDv = sumOfDv.add(dv); } if (sumOfDv > 0) { for (uint i = 0; i < numOfPools; i++) { uint price = IPriceOracle(oracle).getPrice(pools[i]); uint dv = price.mul(getTotalVtb(pools[i], prevEpochId)); uint nutAmount = dv.mul(amount).div(sumOfDv); actualSumOfNut = actualSumOfNut.add(nutAmount); totalNutMap[pools[i]][prevEpochId] = nutAmount; } } require(actualSumOfNut <= amount, "distribute: overflow"); distCompletionMap[prevEpochId] = true; } /// @dev Collect Nut tokens function collect() external { uint epochId = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); require(epochId > 0, 'collect: distribution is completed'); address lender = msg.sender; uint numOfPools = pools.length < MAX_NUM_POOLS ? pools.length : MAX_NUM_POOLS; uint totalAmount; for (uint i = 0; i < numOfPools; i++) { address pool = pools[i]; for (uint j = 0; j < epochId && j < NUM_EPOCH; j++) { uint vtb = getVtb(pool, lender, j); if (vtb > 0 && getTotalVtb(pool, j) > 0) { uint amount = vtb.mul(totalNutMap[pool][j]).div(getTotalVtb(pool, j)); totalAmount = totalAmount.add(amount); vtbMap[pool][lender][j] = 0; } } } if (totalAmount > 0) { require( IERC20(nut).approve(address(this), 0), 'distributor approve failed' ); require( IERC20(nut).approve(address(this), totalAmount), 'NutDist approve amount failed' ); require( IERC20(nut).transferFrom(address(this), lender, totalAmount), 'NutDist transfer failed' ); } } /// @dev getCollectionAmount get the # of NUT tokens for collection function getCollectionAmount() external view returns(uint) { uint epochId = (block.number.sub(DIST_START_BLOCK)).div(BLOCKS_PER_EPOCH); require(epochId > 0, 'getCollectionAmount: distribution is completed'); address lender = msg.sender; uint numOfPools = pools.length < MAX_NUM_POOLS ? pools.length : MAX_NUM_POOLS; uint totalAmount; for (uint i = 0; i < numOfPools; i++) { address pool = pools[i]; for (uint j = 0; j < epochId && j < NUM_EPOCH; j++) { uint vtb = getVtb(pool, lender, j); if (vtb > 0 && getTotalVtb(pool, j) > 0) { uint amount = vtb.mul(totalNutMap[pool][j]).div(getTotalVtb(pool, j)); totalAmount = totalAmount.add(amount); } } } return totalAmount; } function getVtb(address pool, address lender, uint i) public view returns(uint) { require(i < NUM_EPOCH, 'vtb idx err'); return i < futureVtbEpoch[pool][lender] ? vtbMap[pool][lender][i] : futureVtbMap[pool][lender]; } function getTotalVtb(address pool, uint i) public view returns (uint) { require(i < NUM_EPOCH, 'totalVtb idx err'); return i < futureTotalVtbEpoch[pool] ? totalVtbMap[pool][i] : futureTotalVtbMap[pool]; } //@notice output version string function getVersionString() external virtual pure returns (string memory) { return "1"; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface INutDistributor { function updateVtb(address token, address lender, uint incAmount, uint decAmount) external; function inNutDistribution() external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IPriceOracle { function getPrice(address token) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import './lib/Governable.sol'; import './lib/Math.sol'; import "./interfaces/IAdapter.sol"; import "./interfaces/INutmeg.sol"; import "./interfaces/INutDistributor.sol"; import "./interfaces/IPriceOracle.sol"; contract Nutmeg is Initializable, Governable, INutmeg { using SafeMath for uint; using SafeERC20 for IERC20; address public nutDistributor; address public nut; uint private constant INVALID_POSITION_ID = type(uint).max; uint private constant NOT_LOCKED = 0; uint private constant LOCKED = 1; uint private constant TRANCHE_BBB = uint(Tranche.BBB); uint private constant TRANCHE_A = uint(Tranche.A); uint private constant TRANCHE_AA = uint(Tranche.AA); uint private constant MULTIPLIER = 10**18; uint private constant NUM_BLOCK_PER_YEAR = 2102400; address private constant INVALID_ADAPTER = address(2); uint public constant MAX_NUM_POOL = 256; uint public constant LIQUIDATION_COMMISSION = 5; uint public constant MAX_INTEREST_RATE_PER_BLOCK = 100000; // 1000.00% uint public constant MIN_INTEREST_RATE_PER_BLOCK = 500; // 5.00% uint public constant VERSION_ID = 1; uint public POOL_LOCK; uint public EXECUTION_LOCK; uint public STAKE_COUNTER; uint public POSITION_COUNTER; uint public CURR_POSITION_ID; address public CURR_SENDER; address public CURR_ADAPTER; // treasury pool array and map address[] public pools; // array of treasury pools mapping(address => Pool) public poolMap; // baseToken => pool mapping. // stake mapping(address => mapping (address => Stake[3])) public stakeMap; // baseToken => sender => tranche. mapping(address => uint[]) lenderStakeMap; // all stakes of a lender. address => stakeId // adapter address[] public adapters; mapping(address => bool) public adapterMap; // position mapping(uint => Position) public positionMap; mapping(address => uint[]) borrowerPositionMap; // all positions of a borrower. address => positionId mapping(address => mapping(address => uint)) minNut4Borrowers; // pool => adapter => uint /// @dev Reentrancy lock guard. modifier poolLock() { require(POOL_LOCK == NOT_LOCKED, 'pl lck'); POOL_LOCK = LOCKED; _; POOL_LOCK = NOT_LOCKED; } /// @dev Reentrancy lock guard for execution. modifier inExecution() { require(CURR_POSITION_ID != INVALID_POSITION_ID, 'not exc'); require(CURR_ADAPTER == msg.sender, 'bad adpr'); require(EXECUTION_LOCK == NOT_LOCKED, 'exc lock'); EXECUTION_LOCK = LOCKED; _; EXECUTION_LOCK = NOT_LOCKED; } /// @dev Accrue interests in a pool modifier accrue(address token) { accrueInterest(token); _; } /// @dev Initialize the smart contract, using msg.sender as the first governor. function initialize(address _governor) external initializer { __Governable__init(_governor); POOL_LOCK = NOT_LOCKED; EXECUTION_LOCK = NOT_LOCKED; STAKE_COUNTER = 1; POSITION_COUNTER = 1; CURR_POSITION_ID = INVALID_POSITION_ID; CURR_ADAPTER = INVALID_ADAPTER; } function setNutDistributor(address addr) external onlyGov { nutDistributor = addr; } function setNut(address addr) external onlyGov { nut = addr; } function setMinNut4Borrowers(address poolAddr, address adapterAddr, uint val) external onlyGov { require(adapterMap[adapterAddr], 'setMin no adpr'); Pool storage pool = poolMap[poolAddr]; require(pool.isExists, 'setMin no pool'); minNut4Borrowers[poolAddr][adapterAddr] = val; } /// @notice Get all stake IDs of a lender function getStakeIds(address lender) external override view returns (uint[] memory){ return lenderStakeMap[lender]; } /// @notice Get all position IDs of a borrower function getPositionIds(address borrower) external override view returns (uint[] memory){ return borrowerPositionMap[borrower]; } /// @notice Return current position ID function getCurrPositionId() external override view returns (uint) { return CURR_POSITION_ID; } /// @notice Return next position ID function getNextPositionId() external override view returns (uint) { return POSITION_COUNTER; } /// @notice Get position information function getPosition(uint id) external override view returns (Position memory) { return positionMap[id]; } /// @dev get current sender function getCurrSender() external override view returns (address) { return CURR_SENDER; } /// @dev Get all treasury pools function getPools() external view returns (address[] memory) { return pools; } /// @dev Get a specific pool given address function getPool(address addr) external view returns (Pool memory) { return poolMap[addr]; } /// @dev Add a new treasury pool. /// @param token The underlying base token for the pool, e.g., DAI. /// @param interestRate The interest rate per block of Tranche A. function addPool(address token, uint interestRate) external poolLock onlyGov { require(pools.length < MAX_NUM_POOL, 'addPl pl > max'); require(_isInterestRateValid(interestRate), 'addPl bad ir'); Pool storage pool = poolMap[token]; require(!pool.isExists, 'addPl pool exts'); pool.isExists = true; pool.baseToken = token; pool.interestRates = [interestRate.div(2), interestRate, interestRate.mul(2)]; pools.push(token); emit addPoolEvent(token, interestRate); pool.lossMultiplier = [ MULTIPLIER, MULTIPLIER, MULTIPLIER ]; } /// @dev Update interest rate of the pool /// @param token The underlying base token for the pool, e.g., DAI. /// @param interestRate The interest rate per block of Tranche A. Input 316 for 3.16% APY function updateInterestRates(address token, uint interestRate) external poolLock onlyGov { require(_isInterestRateValid(interestRate), 'upIR bad ir'); Pool storage pool = poolMap[token]; require(pool.isExists, 'upIR no pool'); pool.interestRates = [interestRate.div(2), interestRate, interestRate.mul(2)]; } function _isInterestRateValid(uint interestRate) internal pure returns(bool) { return (interestRate <= MAX_INTEREST_RATE_PER_BLOCK && interestRate >= MIN_INTEREST_RATE_PER_BLOCK); } /// @notice Stake to a treasury pool. /// @param token The contract address of the base token of the pool. /// @param tranche The tranche of the pool, 0 - AA, 1 - A, 2 - BBB. /// @param principal The amount of principal function stake(address token, uint tranche, uint principal) external poolLock accrue(token) { require(tranche < 3, 'stk bad trnch'); require(principal > 0, 'stk bad prpl'); Pool storage pool = poolMap[token]; require(pool.isExists, 'stk no pool'); if (tranche == TRANCHE_BBB) { require(principal.add(pool.principals[TRANCHE_BBB]) <= pool.principals[TRANCHE_AA], 'stk BBB full'); } // 1. transfer the principal to the pool. IERC20(pool.baseToken).safeTransferFrom(msg.sender, address(this), principal); // 2. add or update a stake Stake storage stk = stakeMap[token][msg.sender][tranche]; uint sumIpp = pool.sumIpp[tranche]; uint scaledPrincipal = 0; if (stk.id == 0) { // new stk stk.id = STAKE_COUNTER++; stk.status = StakeStatus.Open; stk.owner = msg.sender; stk.pool = token; stk.tranche = tranche; } else { // add liquidity to an existing stk scaledPrincipal = _scaleByLossMultiplier( stk, stk.principal ); uint interest = scaledPrincipal.mul( sumIpp.sub(stk.sumIppStart)).div(MULTIPLIER); stk.earnedInterest = _scaleByLossMultiplier(stk, stk.earnedInterest ).add(interest); } stk.sumIppStart = sumIpp; stk.principal = scaledPrincipal.add(principal); stk.lossZeroCounterBase = pool.lossZeroCounter[tranche]; stk.lossMultiplierBase = pool.lossMultiplier[tranche]; lenderStakeMap[stk.owner].push(stk.id); // update pool information pool.principals[tranche] = pool.principals[tranche].add(principal); updateInterestRateAdjustment(token); if (INutDistributor(nutDistributor).inNutDistribution()) { INutDistributor(nutDistributor).updateVtb(token, stk.owner, principal, 0); } emit stakeEvent(token, msg.sender, tranche, principal, stk.id); } /// @notice Unstake from a treasury pool. /// @param token The address of the pool. /// @param tranche The tranche of the pool, 0 - AA, 1 - A, 2 - BBB. /// @param amount The amount of principal that owner want to withdraw function unstake(address token, uint tranche, uint amount) external poolLock accrue(token) { require(tranche < 3, 'unstk bad trnch'); Pool storage pool = poolMap[token]; Stake storage stk = stakeMap[token][msg.sender][tranche]; require(stk.id > 0, 'unstk no dpt'); uint activePrincipal = _scaleByLossMultiplier( stk, stk.principal ); require(amount > 0 && amount <= activePrincipal, 'unstk bad amt'); require(stk.status == StakeStatus.Open, 'unstk bad status'); // get the available amount to remove uint withdrawAmt = _getWithdrawAmount(poolMap[stk.pool], amount); uint interest = activePrincipal.mul(pool.sumIpp[tranche].sub(stk.sumIppStart)).div(MULTIPLIER); uint totalInterest = _scaleByLossMultiplier( stk, stk.earnedInterest ).add(interest); if (totalInterest > pool.interests[tranche]) { // unlikely, but just in case. totalInterest = pool.interests[tranche]; } // transfer liquidity to the lender uint actualWithdrawAmt = withdrawAmt.add(totalInterest); IERC20(pool.baseToken).safeTransfer(msg.sender, actualWithdrawAmt); // update stake information stk.principal = activePrincipal.sub(withdrawAmt); stk.sumIppStart = pool.sumIpp[tranche]; stk.lossZeroCounterBase = pool.lossZeroCounter[tranche]; stk.lossMultiplierBase = pool.lossMultiplier[tranche]; stk.earnedInterest = 0; if (stk.principal == 0) { stk.status = StakeStatus.Closed; } // update pool principal and interest information pool.principals[tranche] = pool.principals[tranche].sub(withdrawAmt); pool.interests[tranche] = pool.interests[tranche].sub(totalInterest); updateInterestRateAdjustment(token); if (INutDistributor(nutDistributor).inNutDistribution() && withdrawAmt > 0) { INutDistributor(nutDistributor).updateVtb(token, stk.owner, 0, withdrawAmt); } emit unstakeEvent(token, msg.sender, tranche, withdrawAmt, stk.id); } function _scaleByLossMultiplier(Stake memory stk, uint quantity) internal view returns (uint) { Pool memory pool = poolMap[stk.pool]; return stk.lossZeroCounterBase < pool.lossZeroCounter[stk.tranche] ? 0 : quantity.mul( pool.lossMultiplier[stk.tranche] ).div( stk.lossMultiplierBase ); } /// @notice Accrue interest for a given pool. /// @param token Address of the pool. function accrueInterest(address token) internal { Pool storage pool = poolMap[token]; require(pool.isExists, 'accrIr no pool'); uint totalLoan = Math.sumOf3UintArray(pool.loans); uint currBlock = block.number; if (currBlock <= pool.latestAccruedBlock) return; if (totalLoan > 0 ) { uint interestRate = pool.interestRates[TRANCHE_A]; if (!pool.isIrAdjustPctNegative) { interestRate = interestRate.mul(pool.irAdjustPct.add(100)).div(100); } else { interestRate = interestRate.mul(uint(100).sub(pool.irAdjustPct)).div(100); } uint rtb = interestRate.mul(currBlock.sub(pool.latestAccruedBlock)); // update pool sumRtb. pool.sumRtb = pool.sumRtb.add(rtb); // update tranche sumIpp. for (uint idx = 0; idx < pool.loans.length; idx++) { if (pool.principals[idx] > 0) { uint interest = (pool.loans[idx].mul(rtb)).div(NUM_BLOCK_PER_YEAR.mul(10000)); pool.interests[idx] = pool.interests[idx].add(interest); pool.sumIpp[idx]= pool.sumIpp[idx].add(interest.mul(MULTIPLIER).div(pool.principals[idx])); } } } pool.latestAccruedBlock = block.number; } /// @notice Get pool information /// @param token The base token function getPoolInfo(address token) external view override returns(uint, uint, uint) { Pool memory pool = poolMap[token]; require(pool.isExists, 'getPolInf no pol'); return (Math.sumOf3UintArray(pool.principals), Math.sumOf3UintArray(pool.loans), pool.totalCollateral); } /// @notice Get interest a position need to pay /// @param token Address of the pool. /// @param posId Position ID. function getPositionInterest(address token, uint posId) public override view returns(uint) { Pool storage pool = poolMap[token]; require(pool.isExists, 'getPosIR no pool'); Position storage pos = positionMap[posId]; require(pos.baseToken == pool.baseToken, 'getPosIR bad match'); return Math.sumOf3UintArray(pos.loans).mul(pool.sumRtb.sub(pos.sumRtbStart)).div( NUM_BLOCK_PER_YEAR.mul(10000) ); } /// @dev Update the interest rate adjustment of the pool /// @param token Address of the pool function updateInterestRateAdjustment(address token) public { Pool storage pool = poolMap[token]; require(pool.isExists, 'updtIRAdj no pool'); uint totalPrincipal = Math.sumOf3UintArray(pool.principals); uint totalLoan = Math.sumOf3UintArray(pool.loans); if (totalPrincipal > 0 ) { uint urPct = totalLoan >= totalPrincipal ? 100 : totalLoan.mul(100).div(totalPrincipal); if (urPct > 90) { // 0% + 50 * (UR - 90%) pool.irAdjustPct = urPct.sub(90).mul(50); pool.isIrAdjustPctNegative = false; } else if (urPct < 90) { // UR - 90% pool.irAdjustPct = (uint(90).sub(urPct)); pool.isIrAdjustPctNegative = true; } } } function _getWithdrawAmount(Pool memory pool, uint amount) internal pure returns (uint) { uint availPrincipal = Math.sumOf3UintArray(pool.principals).sub( Math.sumOf3UintArray(pool.loans) ); return amount > availPrincipal ? availPrincipal : amount; } /// @dev Get the collateral ratio of the pool. /// @param baseToken Base token of the pool. /// @param baseAmt The collateral from the borrower. function _getCollateralRatioPct(address baseToken, uint baseAmt) public view returns (uint) { Pool storage pool = poolMap[baseToken]; require(pool.isExists, '_getCollRatPct no pool'); uint totalPrincipal = Math.sumOf3UintArray(pool.principals); uint totalLoan = Math.sumOf3UintArray(pool.loans); uint urPct = (totalPrincipal == 0) ? 100 : ((totalLoan.add(baseAmt)).mul(100)).div(totalPrincipal); if (urPct > 100) { // not likely, but just in case. urPct = 100; } if (urPct > 90) { // 10% + 9 * (UR - 90%) return (urPct.sub(90).mul(9)).add(10); } // 10% - 0.1 * (90% - UR) return (urPct.div(10)).add(1); } /// @notice Get the maximum available borrow amount /// @param baseToken Base token of the pool /// @param baseAmt The collateral from the borrower function getMaxBorrowAmount(address baseToken, uint baseAmt) public override view returns (uint) { uint crPct = _getCollateralRatioPct(baseToken, baseAmt); return (baseAmt.mul(100).div(crPct)).sub(baseAmt); } /// @notice Get stakes of a user in a pool /// @param token The address of the pool /// @param owner The address of the owner function getStake(address token, address owner) public view returns (Stake[3] memory) { return stakeMap[token][owner]; } /// @dev Add adapter to Nutmeg /// @param token The address of the adapter function addAdapter(address token) external poolLock onlyGov { adapters.push(token); adapterMap[token] = true; } /// @dev Remove adapter from Nutmeg /// @param token The address of the adapter function removeAdapter(address token) external poolLock onlyGov { adapterMap[token] = false; } /// @notice Borrow tokens from the pool. Must only be called by adapter while under execution. /// @param baseToken The token to borrow from the pool. /// @param collToken The token borrowers got from the 3rd party pool. /// @param baseAmt The amount of collateral from borrower. /// @param borrowAmt The amount of tokens to borrow, x time leveraged already. function borrow(address baseToken, address collToken, uint baseAmt, uint borrowAmt) external override accrue(baseToken) inExecution { // check pool and position. Pool storage pool = poolMap[baseToken]; require(pool.isExists, 'brw no pool'); Position storage position = positionMap[CURR_POSITION_ID]; require(position.baseToken == address(0), 'brw no rebrw'); // check borrowAmt uint maxBorrowAmt = getMaxBorrowAmount(baseToken, baseAmt); require(borrowAmt <= maxBorrowAmt, "brw too bad"); require(borrowAmt > baseAmt, "brw brw < coll"); // check available principal per tranche. uint[3] memory availPrincipals; for (uint i = 0; i < 3; i++) { availPrincipals[i] = pool.principals[i].sub(pool.loans[i]); } uint totalAvailPrincipal = Math.sumOf3UintArray(availPrincipals); require(borrowAmt <= totalAvailPrincipal, 'brw asset low'); // calculate loan amount from each tranche. uint[3] memory loans; for (uint i = 0; i < 3; i++) { loans[i] = borrowAmt.mul(availPrincipals[i]).div(totalAvailPrincipal); } loans[2] = borrowAmt.sub(loans[0].add(loans[1])); // handling rounding numbers // transfer base tokens from borrower to contract as the collateral. IERC20(pool.baseToken).safeApprove(address(this), 0); IERC20(pool.baseToken).safeApprove(address(this), baseAmt); IERC20(pool.baseToken).safeTransferFrom(position.owner, address(this), baseAmt); // transfer borrowed assets to the adapter IERC20(pool.baseToken).safeTransfer(msg.sender, borrowAmt); // update position information position.status = PositionStatus.Open; position.baseToken = pool.baseToken; position.collToken = collToken; position.baseAmt = baseAmt; position.borrowAmt = borrowAmt; position.loans = loans; position.sumRtbStart = pool.sumRtb; borrowerPositionMap[position.owner].push(position.id); // update pool information for (uint i = 0; i < 3; i++) { pool.loans[i] = pool.loans[i].add(loans[i]); } pool.totalCollateral = pool.totalCollateral.add(baseAmt); updateInterestRateAdjustment(baseToken); } function _getRepayAmount(uint[3] memory loans, uint totalAmt) public pure returns(uint[3] memory) { uint totalLoan = Math.sumOf3UintArray(loans); uint amount = totalLoan < totalAmt ? totalLoan : totalAmt; uint[3] memory repays = [uint(0), uint(0), uint(0)]; for (uint i; i < 3; i++) { repays[i] = (loans[i].mul(amount)).div(totalLoan); } repays[2] = amount.sub(repays[0].add(repays[1])); return repays; } /// @notice Repay tokens to the pool and close the position. Must only be called while under execution. /// @param baseToken The token to borrow from the pool. /// @param repayAmt The amount of base token repaid from adapter. function repay(address baseToken, uint repayAmt) external override accrue(baseToken) inExecution { Position storage pos = positionMap[CURR_POSITION_ID]; Pool storage pool = poolMap[pos.baseToken]; require(pool.isExists, 'rpy no pool'); require(adapterMap[pos.adapter] && msg.sender == pos.adapter, 'repay: no such adapter'); uint totalLoan = Math.sumOf3UintArray(pos.loans); // owe to lenders uint interest = getPositionInterest(pool.baseToken, pos.id); // already paid to lenders uint totalRepayAmt = repayAmt.add(pos.baseAmt).sub(interest); // total amount used for repayment uint change = totalRepayAmt > totalLoan ? totalRepayAmt.sub(totalLoan) : 0; // profit of the borrower // transfer total redeemed amount from adapter to the pool IERC20(baseToken).safeTransferFrom(msg.sender, address(this), repayAmt); if (totalRepayAmt < totalLoan) { pos.repayDeficit = totalLoan.sub(totalRepayAmt); } uint[3] memory repays = _getRepayAmount(pos.loans, repayAmt); // update position information pos.status = PositionStatus.Closed; for (uint i; i < 3; i++) { pos.loans[i] = pos.loans[i].sub(repays[i]); } // update pool information pool.totalCollateral = pool.totalCollateral.sub(pos.baseAmt); for (uint i; i < 3; i++) { pool.loans[i] = pool.loans[i].sub(repays[i]); } // send profit, if any to the borrower. if (change > 0) { IERC20(baseToken).safeTransfer(pos.owner, change); } } /// @notice Liquidate a position when conditions are satisfied /// @param baseToken The base token of the pool. /// @param liquidateAmt The repay amount from adapter. function liquidate( address baseToken, uint liquidateAmt) external override accrue(baseToken) inExecution { Position storage pos = positionMap[CURR_POSITION_ID]; Pool storage pool = poolMap[baseToken]; require(pool.isExists, 'lqt no pool'); require(pool.baseToken == baseToken, "lqt base no match"); require(adapterMap[pos.adapter] && msg.sender == pos.adapter, 'lqt no adpr'); require(liquidateAmt > 0, 'lqt bad rpy'); // transfer liquidateAmt of base tokens from adapter to pool. IERC20(baseToken).safeTransferFrom(msg.sender, address(this), liquidateAmt); uint totalLoan = Math.sumOf3UintArray(pos.loans); uint interest = getPositionInterest(pool.baseToken, pos.id); uint totalRepayAmt = liquidateAmt.add(pos.baseAmt).sub(interest); // total base tokens from liquidated uint bonusAmt = LIQUIDATION_COMMISSION.mul(totalRepayAmt).div(100); // bonus for liquidator. uint repayAmt = totalRepayAmt.sub(bonusAmt); // amount to pay lenders and the borrower uint change = totalLoan < repayAmt ? repayAmt.sub(totalLoan) : 0; uint[3] memory repays = _getRepayAmount(pos.loans, liquidateAmt); // transfer bonus to the liquidator. IERC20(baseToken).safeTransfer(tx.origin, bonusAmt); // update position information pos.status = PositionStatus.Liquidated; for (uint i; i < 3; i++) { pos.loans[i] = pos.loans[i].sub(repays[i]); } // update pool information pool.totalCollateral = pool.totalCollateral.sub(pos.baseAmt); for (uint i; i < 3; i++) { pool.loans[i] = pool.loans[i].sub(repays[i]); } // send leftover to position owner if (change > 0) { IERC20(baseToken).safeTransfer(pos.owner, change); } if (totalRepayAmt < totalLoan) { pos.repayDeficit = totalLoan.sub(totalRepayAmt); } } /// @notice Settle credit event callback /// @param baseToken Base token of the pool. /// @param collateralLoss Loss to be distributed /// @param poolLoss Loss to be distributed function distributeCreditLosses( address baseToken, uint collateralLoss, uint poolLoss) external override accrue(baseToken) inExecution { Pool storage pool = poolMap[baseToken]; require(pool.isExists, 'dstCrd no pool'); require(collateralLoss <= pool.totalCollateral, 'dstCrd col high'); if (collateralLoss >= 0) { pool.totalCollateral = pool.totalCollateral.sub(collateralLoss); } if (poolLoss == 0) { return; } uint totalPrincipal = Math.sumOf3UintArray(pool.principals); uint runningLoss = poolLoss; for (uint i = 0; i < 3; i++) { uint j = 3 - i - 1; // The running totals are based on the principal, // however, when I calculate the multipliers, I // take into account accured interest uint tranchePrincipal = pool.principals[j]; uint trancheValue = pool.principals[j] + pool.interests[j]; // Do not scale pool.sumIpp. Since I am scaling the // principal, this will cause the interest rate // calcuations to take into account the losses when // a lender position is unstaked. if (runningLoss >= tranchePrincipal) { pool.principals[j] = 0; pool.interests[j] = 0; pool.lossZeroCounter[j] = block.number; pool.lossMultiplier[j] = MULTIPLIER; runningLoss = runningLoss.sub(tranchePrincipal); } else { uint valueRemaining = tranchePrincipal.sub(runningLoss); pool.principals[j] = pool.principals[j].mul(valueRemaining).div(trancheValue); pool.interests[j] = pool.interests[j].mul(valueRemaining).div(trancheValue); pool.lossMultiplier[j] = valueRemaining.mul(MULTIPLIER).div(trancheValue); break; } } // subtract the pool loss from the total loans // this keeps principal - loans the same so that // we have a correct accounting of the amount of // liquidity available for borrows. uint totalLoans = pool.loans[0].add(pool.loans[1]).add(pool.loans[2]); totalPrincipal = (poolLoss <= totalPrincipal) ? totalPrincipal.sub(poolLoss) : 0; totalLoans = (poolLoss <= totalLoans) ? totalLoans.sub(poolLoss) : 0; for (uint i = 0; i < pool.loans.length; i++) { pool.loans[i] = totalPrincipal == 0 ? 0 : totalLoans.mul(pool.principals[i]).div(totalPrincipal); } } /// @notice Add collateral token to position. Must be called during execution. /// @param posId Position id /// @param collAmt The amount of the collateral token from 3rd party pool. function addCollToken(uint posId, uint collAmt) external override inExecution { Position storage pos = positionMap[CURR_POSITION_ID]; require(pos.id == posId, "addCollTk bad pos"); pos.collAmt = collAmt; } function getEarnedInterest( address token, address owner, Tranche tranche ) external view returns (uint256) { Pool storage pool = poolMap[token]; require(pool.isExists, 'gtErndIr no pool'); Stake memory stk = getStake(token, owner)[uint(tranche)]; return _scaleByLossMultiplier( stk, stk.earnedInterest.add( stk.principal.mul( pool.sumIpp[uint(tranche)].sub(stk.sumIppStart) ).div(MULTIPLIER)) ); } /// ------------------------------------------------------------------- /// functions to adapter function beforeExecution( uint posId, IAdapter adapter ) internal { require(POOL_LOCK == NOT_LOCKED, 'pol lck'); POOL_LOCK = LOCKED; address adapterAddr = address(adapter); require(adapterMap[adapterAddr], 'no adpr'); if (posId == 0) { // create a new position posId = POSITION_COUNTER++; positionMap[posId].id = posId; positionMap[posId].owner = msg.sender; positionMap[posId].adapter = adapterAddr; } else { require(posId < POSITION_COUNTER, 'no pos'); require(positionMap[posId].status == PositionStatus.Open, 'only open pos'); } CURR_POSITION_ID = posId; CURR_ADAPTER = adapterAddr; CURR_SENDER = msg.sender; } function afterExecution() internal { CURR_POSITION_ID = INVALID_POSITION_ID; CURR_ADAPTER = INVALID_ADAPTER; POOL_LOCK = NOT_LOCKED; CURR_SENDER = address(0); } function openPosition( uint posId, IAdapter adapter, address baseToken, address collToken, uint baseAmt, uint borrowAmt ) external { uint balance = IERC20(nut).balanceOf(msg.sender); require(minNut4Borrowers[baseToken][address(adapter)] <= balance, 'NUT low'); beforeExecution(posId, adapter); adapter.openPosition( baseToken, collToken, baseAmt, borrowAmt ); afterExecution(); } function closePosition( uint posId, IAdapter adapter ) external returns (uint) { beforeExecution(posId, adapter); uint redeemAmt = adapter.closePosition(); afterExecution(); return redeemAmt; } function liquidatePosition( uint posId, IAdapter adapter ) external { beforeExecution(posId, adapter); adapter.liquidate(); afterExecution(); } function settleCreditEvent( IAdapter adapter, address baseToken, uint collateralLoss, uint poolLoss ) onlyGov external { beforeExecution(0, adapter); adapter.settleCreditEvent( baseToken, collateralLoss, poolLoss ); afterExecution(); } function getMaxUnstakePrincipal(address token, address owner, uint tranche) external view returns (uint) { Stake memory stk = stakeMap[token][owner][tranche]; return _getWithdrawAmount(poolMap[stk.pool], stk.principal); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; library Math { using SafeMath for uint; function sumOf3UintArray(uint[3] memory data) internal pure returns(uint) { return data[0].add(data[1]).add(data[2]); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IAdapter { function openPosition( address baseToken, address collToken, uint collAmount, uint borrowAmount ) external; function closePosition() external returns (uint); function liquidate() external; function settleCreditEvent( address baseToken, uint collateralLoss, uint poolLoss) external; event openPositionEvent(uint positionId, address caller, uint baseAmt, uint borrowAmount); event closePositionEvent(uint positionId, address caller, uint amount); event liquidateEvent(uint positionId, address caller); event creditEvent(address token, uint collateralLoss, uint poolLoss); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; interface INutmeg { enum Tranche {AA, A, BBB} enum StakeStatus {Uninitialized, Open, Closed, Settled} enum PositionStatus {Uninitialized, Open, Closed, Liquidated, Settled} struct Pool { bool isExists; address baseToken; // base token of this pool, e.g., WETH, DAI. uint[3] interestRates; // interest rate per block of each tranche. supposed to be updated everyday. uint[3] principals; // principals of each tranche, from lenders uint[3] loans; // loans of each tranche, from borrowers. uint[3] interests; // interests accrued from loans for each tranche. uint totalCollateral; // total collaterals in base token from borrowers. uint latestAccruedBlock; // the block number of the latest interest accrual action. uint sumRtb; // sum of interest rate per block (after adjustment) times # of blocks uint irAdjustPct; // interest rate adjustment in percentage, e.g., 1, 99. bool isIrAdjustPctNegative; // whether interestRateAdjustPct is negative uint[3] sumIpp; // sum of interest per principal. uint[3] lossMultiplier; uint[3] lossZeroCounter; } struct Stake { uint id; StakeStatus status; address owner; address pool; uint tranche; // tranche of the pool, 0 - AA, 1 - A, 2 - BBB. uint principal; uint sumIppStart; uint earnedInterest; uint lossMultiplierBase; uint lossZeroCounterBase; } struct Position { uint id; // id of the position. PositionStatus status; // status of the position, Open, Close, and Liquidated. address owner; // borrower's address address adapter; // adapter's address address baseToken; // base token that the borrower borrows from the pool address collToken; // collateral token that the borrower got from 3rd party pool. uint[3] loans; // loans of all tranches uint baseAmt; // amount of the base token the borrower put into pool as the collateral. uint collAmt; // amount of collateral token the borrower got from 3rd party pool. uint borrowAmt; // amount of base tokens borrowed from the pool. uint sumRtbStart; // rate times block when the position is created. uint repayDeficit; // repay pool loss } struct NutDist { uint endBlock; uint amount; } /// @dev Get all stake IDs of a lender function getStakeIds(address lender) external view returns (uint[] memory); /// @dev Get all position IDs of a borrower function getPositionIds(address borrower) external view returns (uint[] memory); /// @dev Get the maximum available borrow amount function getMaxBorrowAmount(address token, uint collAmount) external view returns(uint); /// @dev Get the current position while under execution. function getCurrPositionId() external view returns (uint); /// @dev Get the next position ID while under execution. function getNextPositionId() external view returns (uint); /// @dev Get the current sender while under execution function getCurrSender() external view returns (address); function getPosition(uint id) external view returns (Position memory); function getPositionInterest(address token, uint positionId) external view returns(uint); function getPoolInfo(address token) external view returns(uint, uint, uint); /// @dev Add Collateral token from the 3rd party pool to a position function addCollToken(uint posId, uint collAmt) external; /// @dev Borrow tokens from the pool. function borrow(address token, address collAddr, uint baseAmount, uint borrowAmount) external; /// @dev Repays tokens to the pool. function repay(address token, uint repayAmount) external; /// @dev Liquidate a position when conditions are satisfied function liquidate(address token, uint repayAmount) external; /// @dev Settle credit event function distributeCreditLosses( address baseToken, uint collateralLoss, uint poolLoss) external; event addPoolEvent(address bank, uint interestRateA); event stakeEvent(address bank, address owner, uint tranche, uint amount, uint depId); event unstakeEvent(address bank, address owner, uint tranche, uint amount, uint depId); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ICERC20.sol"; import "../interfaces/IAdapter.sol"; import "../interfaces/INutmeg.sol"; import "../lib/Governable.sol"; import "../lib/Math.sol"; contract CompoundAdapter is Governable, IAdapter { using SafeERC20 for IERC20; using SafeMath for uint; struct PosInfo { uint posId; uint collAmt; uint sumIpcStart; } INutmeg public immutable nutmeg; uint private constant MULTIPLIER = 10**18; address[] public baseTokens; // array of base tokens mapping(address => bool) public baseTokenMap; // e.g., Dai mapping(address => address) public tokenPairs; // Dai -> cDai or cDai -> Dai; mapping(address => uint) public totalMintAmt; mapping(address => uint) public sumIpcMap; mapping(uint => PosInfo) public posInfoMap; mapping(address => uint) public totalLoan; mapping(address => uint) public totalCollateral; mapping(address => uint) public totalLoss; constructor(INutmeg nutmegAddr) { nutmeg = nutmegAddr; __Governable__init(); } modifier onlyNutmeg() { require(msg.sender == address(nutmeg), 'only nutmeg can call'); _; } /// @dev Add baseToken collToken pairs function addTokenPair(address baseToken, address collToken) external onlyGov { baseTokenMap[baseToken] = true; tokenPairs[baseToken] = collToken; baseTokens.push(baseToken); } /// @dev Remove baseToken collToken pairs function removeTokenPair(address baseToken) external onlyGov { baseTokenMap[baseToken] = false; tokenPairs[baseToken] = address(0); } /// @notice Open a position. /// @param baseToken Base token of the position. /// @param collToken Collateral token of the position. /// @param baseAmt Amount of collateral in base token. /// @param borrowAmt Amount of base token to be borrowed from nutmeg. function openPosition(address baseToken, address collToken, uint baseAmt, uint borrowAmt) external onlyNutmeg override { require(baseAmt > 0, 'openPosition: invalid base amount'); require(baseTokenMap[baseToken], 'openPosition: invalid baseToken address'); require(tokenPairs[baseToken] == collToken, 'openPosition: invalid cToken address'); uint posId = nutmeg.getCurrPositionId(); INutmeg.Position memory pos = nutmeg.getPosition(posId); require(nutmeg.getCurrSender() == pos.owner, 'openPosition: only owner can initialize this call'); require(IERC20(baseToken).balanceOf(pos.owner) >= baseAmt, 'openPosition: insufficient balance'); // check borrowAmt uint maxBorrowAmt = nutmeg.getMaxBorrowAmount(baseToken, baseAmt); require(borrowAmt <= maxBorrowAmt, "openPosition: borrowAmt exceeds maximum"); require(borrowAmt > baseAmt, "openPosition: borrowAmt is less than collateral"); // borrow base tokens from nutmeg nutmeg.borrow(baseToken, collToken, baseAmt, borrowAmt); _increaseDebtAndCollateral(baseToken, posId); // mint collateral tokens from compound pos = nutmeg.getPosition(posId); (uint result, uint mintAmt) = _doMint(pos, borrowAmt); require(result == 0, 'opnPos: _doMint fail'); if (mintAmt > 0) { uint currSumIpc = _calcLatestSumIpc(collToken); totalMintAmt[collToken] = totalMintAmt[collToken].add(mintAmt); PosInfo storage posInfo = posInfoMap[posId]; posInfo.sumIpcStart = currSumIpc; posInfo.collAmt = mintAmt; // add mintAmt to the position in nutmeg. nutmeg.addCollToken(posId, mintAmt); } emit openPositionEvent(posId, nutmeg.getCurrSender(), baseAmt, borrowAmt); } /// @notice Close a position by the borrower function closePosition() external onlyNutmeg override returns (uint) { uint posId = nutmeg.getCurrPositionId(); INutmeg.Position memory pos = nutmeg.getPosition(posId); require(pos.owner == nutmeg.getCurrSender(), 'closePosition: original caller is not the owner'); uint collAmt = _getCollTokenAmount(pos); (uint result, uint redeemAmt) = _doRedeem(pos, collAmt); require(result == 0, 'clsPos: rdm fail'); // allow nutmeg to receive redeemAmt from the adapter IERC20(pos.baseToken).safeApprove(address(nutmeg), 0); IERC20(pos.baseToken).safeApprove(address(nutmeg), redeemAmt); // repay to nutmeg _decreaseDebtAndCollateral(pos.baseToken, pos.id, redeemAmt); nutmeg.repay(pos.baseToken, redeemAmt); pos = nutmeg.getPosition(posId); totalLoss[pos.baseToken] = totalLoss[pos.baseToken].add(pos.repayDeficit); totalMintAmt[pos.collToken] = totalMintAmt[pos.collToken].sub(pos.collAmt); emit closePositionEvent(posId, nutmeg.getCurrSender(), redeemAmt); return redeemAmt; } /// @notice Liquidate a position function liquidate() external override onlyNutmeg { uint posId = nutmeg.getCurrPositionId(); INutmeg.Position memory pos = nutmeg.getPosition(posId); require(_okToLiquidate(pos), 'liquidate: position is not ready for liquidation yet.'); uint amount = _getCollTokenAmount(pos); (uint result, uint redeemAmt) = _doRedeem(pos, amount); require(result == 0, 'lqdte: rdm fail'); IERC20(pos.baseToken).safeApprove(address(nutmeg), 0); IERC20(pos.baseToken).safeApprove(address(nutmeg), redeemAmt); // liquidate the position in nutmeg. _decreaseDebtAndCollateral(pos.baseToken, posId, redeemAmt); nutmeg.liquidate(pos.baseToken, redeemAmt); pos = nutmeg.getPosition(posId); totalLoss[pos.baseToken] = totalLoss[pos.baseToken].add(pos.repayDeficit); totalMintAmt[pos.collToken] = totalMintAmt[pos.collToken].sub(pos.collAmt); emit liquidateEvent(posId, nutmeg.getCurrSender()); } /// @notice Get value of credit tokens function creditTokenValue(address baseToken) public returns (uint) { address collToken = tokenPairs[baseToken]; require(collToken != address(0), "settleCreditEvent: invalid collateral token" ); uint collTokenBal = ICERC20(collToken).balanceOf(address(this)); return collTokenBal.mul(ICERC20(collToken).exchangeRateCurrent()); } /// @notice Settle credit event /// @param baseToken The base token address function settleCreditEvent( address baseToken, uint collateralLoss, uint poolLoss) external override onlyNutmeg { require(baseTokenMap[baseToken] , "settleCreditEvent: invalid base token" ); require(collateralLoss <= totalCollateral[baseToken], "settleCreditEvent: invalid collateral" ); require(poolLoss <= totalLoan[baseToken], "settleCreditEvent: invalid poolLoss" ); nutmeg.distributeCreditLosses(baseToken, collateralLoss, poolLoss); emit creditEvent(baseToken, collateralLoss, poolLoss); totalLoss[baseToken] = 0; totalLoan[baseToken] = totalLoan[baseToken].sub(poolLoss); totalCollateral[baseToken] = totalCollateral[baseToken].sub(collateralLoss); } function _increaseDebtAndCollateral(address token, uint posId) internal { INutmeg.Position memory pos = nutmeg.getPosition(posId); for (uint i = 0; i < 3; i++) { totalLoan[token] = totalLoan[token].add(pos.loans[i]); } totalCollateral[token] = totalCollateral[token].add(pos.baseAmt); } /// @dev decreaseDebtAndCollateral function _decreaseDebtAndCollateral(address token, uint posId, uint redeemAmt) internal { INutmeg.Position memory pos = nutmeg.getPosition(posId); uint totalLoans = pos.loans[0] + pos.loans[1] + pos.loans[2]; if (redeemAmt >= totalLoans) { totalLoan[token] = totalLoan[token].sub(totalLoans); } else { totalLoan[token] = totalLoan[token].sub(redeemAmt); } totalCollateral[token] = totalCollateral[token].sub(pos.baseAmt); } /// @dev Do the mint from the 3rd party pool.this function _doMint(INutmeg.Position memory pos, uint amount) internal returns(uint, uint) { uint balBefore = ICERC20(pos.collToken).balanceOf(address(this)); require(IERC20(pos.baseToken).approve(pos.collToken, 0), '_doMint approve error'); require(IERC20(pos.baseToken).approve(pos.collToken, amount), '_doMint approve amount error'); uint result = ICERC20(pos.collToken).mint(amount); require(result == 0, '_doMint mint error'); uint balAfter = ICERC20(pos.collToken).balanceOf(address(this)); uint mintAmount = balAfter.sub(balBefore); return (result, mintAmount); } /// @dev Do the redeem from the 3rd party pool. function _doRedeem(INutmeg.Position memory pos, uint amount) internal returns(uint, uint) { uint balBefore = IERC20(pos.baseToken).balanceOf(address(this)); uint result = ICERC20(pos.collToken).redeem(amount); uint balAfter = IERC20(pos.baseToken).balanceOf(address(this)); uint redeemAmt = balAfter.sub(balBefore); return (result, redeemAmt); } /// @dev Get the amount of collToken a position. function _getCollTokenAmount(INutmeg.Position memory pos) internal returns(uint) { uint currSumIpc = _calcLatestSumIpc(pos.collToken); PosInfo storage posInfo = posInfoMap[pos.id]; uint interest = posInfo.collAmt.mul(currSumIpc.sub(posInfo.sumIpcStart)).div(MULTIPLIER); return posInfo.collAmt.add(interest); } /// @dev Calculate the latest sumIpc. /// @param collToken The cToken. function _calcLatestSumIpc(address collToken) internal returns(uint) { uint balance = ICERC20(collToken).balanceOf(address(this)); uint mintBalance = totalMintAmt[collToken]; uint interest = mintBalance > balance ? mintBalance.sub(balance) : 0; uint currIpc = (mintBalance == 0) ? 0 : (interest.mul(MULTIPLIER)).div(mintBalance); if (currIpc > 0){ sumIpcMap[collToken] = sumIpcMap[collToken].add(currIpc); } return sumIpcMap[collToken]; } /// @dev Check if the position is eligible to be liquidated. function _okToLiquidate(INutmeg.Position memory pos) internal view returns(bool) { bool ok = false; uint interest = nutmeg.getPositionInterest(pos.baseToken, pos.id); if (interest.mul(2) >= pos.baseAmt) { ok = true; } return ok; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICERC20 { function mint(uint) external returns (uint); function redeem(uint) external returns (uint); function transfer(address dst, uint amount) external returns (bool); function balanceOf(address) external view returns (uint); function redeemUnderlying(uint) external returns (uint); function exchangeRateCurrent() external returns (uint); function supplyRatePerBlock() external returns (uint); function approve(address spender, uint amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IWETH { function balanceOf(address user) external returns (uint); function approve(address to, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function deposit() external payable; function withdraw(uint) external; } // SPDX-License-Identifier: MIT // Modified from original alphahomora which used 0.6.12 pragma solidity 0.7.6; interface ICErc20 { function decimals() external returns (uint8); function underlying() external returns (address); function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function balanceOf(address user) external view returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../Nutmeg.sol"; // @notice This contract is a version of Nutmeg that contains additional // interfaces for testing contract NutmegAltA is Nutmeg { //@notice output version string function getVersionString() external virtual pure returns (string memory) { return "nutmegalta"; } } contract NutmegAltB is Nutmeg { //@notice output version string function getVersionString() external virtual pure returns (string memory) { return "nutmegaltb"; } } import "../NutDistributor.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // @notice This contract is a version of NutDistributor that allows // the epoch intervals to be changed for testing contract NutDistributorAltA is NutDistributor { //@notice output version string function getVersionString() external virtual pure override returns (string memory) { return "nutdistributoralta"; } } contract NutDistributorAltB is NutDistributor { //@notice output version string function getVersionString() external virtual pure override returns (string memory) { return "nutdistributoraltb"; } } import "./MockERC20.sol"; contract MockERC20AltA is MockERC20("MockERC20AltA", "MOCKERC20ALTA", 18) { } contract MockERC20AltB is MockERC20("MockERC20AltB", "MOCKERC20ALTB", 18) { } contract MockERC20AltC is MockERC20("MockERC20AltC", "MOCKERC20ALTC", 6) { } import "./MockCERC20.sol"; contract MockCERC20AltA is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base(tokenAddr, "MockCERC20 AltA", "MOCKCERC20ALTA", 18) { } } contract MockCERC20AltB is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base(tokenAddr, "MockCERC20 AltB", "MOCKCERC20ALTB", 18) { } } contract MockCERC20AltC is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base(tokenAddr, "MockCERC20 AltC", "MOCKCERC20ALTC", 6) { } } import "../adapters/CompoundAdapter.sol"; import "../interfaces/INutmeg.sol"; contract CompoundAdapterAltA is CompoundAdapter { constructor(INutmeg nutmegAddr) CompoundAdapter(nutmegAddr) { } } contract CompoundAdapterAltB is CompoundAdapter { constructor(INutmeg nutmegAddr) CompoundAdapter(nutmegAddr) { } } // SPDX-License-Identifier: MIT // Mock ERC20 token for testing pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) ERC20(name, symbol) { _setupDecimals(decimals); } function mint(address to, uint amount) external { _mint(to, amount); } } // SPDX-License-Identifier: MIT // Mock ERC20 token for testing pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/ICERC20.sol"; contract MockCERC20Base is ICERC20, ERC20 { address public immutable token; using SafeERC20 for IERC20; using SafeMath for uint; uint private constant MULTIPLIER = 10**18; uint public exchangeRate; bool public returnError; constructor( address tokenAddr, string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) { token = tokenAddr; exchangeRate = MULTIPLIER; returnError = false; _setupDecimals(decimals_); } function mint(uint amount) external override returns (uint) { if (returnError) return 1; IERC20(token).safeTransferFrom(msg.sender, address(this), amount); _mint(msg.sender, amount.mul(MULTIPLIER).div(exchangeRate)); return 0; } function redeem(uint amount) external override returns (uint) { if (returnError) return 1; IERC20(token).safeTransfer( msg.sender, amount.mul(exchangeRate).div(MULTIPLIER) ); _burn(msg.sender, amount); return 0; } function redeemUnderlying(uint amount) external override returns (uint) { if (returnError) return 1; IERC20(token).safeTransfer(msg.sender, amount); _burn( msg.sender, amount.mul(MULTIPLIER).div(exchangeRate) ); return 0; } function exchangeRateCurrent() external view override returns (uint) { return exchangeRate; } function supplyRatePerBlock() external pure override returns (uint) { return 0; } function balanceOf(address account) public override(ERC20, ICERC20) view returns (uint) { return ERC20.balanceOf(account); } function approve(address account, uint amount) public override(ERC20, ICERC20) returns (bool) { return ERC20.approve(account, amount); } function transfer(address dst, uint amount) public override(ERC20, ICERC20) returns (bool) { return ERC20.transfer(dst, amount); } function setExchangeRate(uint e) external { exchangeRate = e; } function setError(bool b) external { returnError = b; } } contract MockCERC20 is MockCERC20Base { constructor(address tokenAddr) MockCERC20Base( tokenAddr, "MockCERC20", "MCERC20", 18 ) { } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import './IERC20Mock.sol'; // Export ICEther interface for mainnet-fork testing. interface ICEtherMock is IERC20Mock { function mint() external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Export IERC20 interface for mainnet-fork testing. interface IERC20Mock is IERC20 { function name() external view returns (string memory); function owner() external view returns (address); function issue(uint) external; function issue(address, uint) external; function mint(address, uint) external; function mint( address, uint, uint ) external returns (bool); function configureMinter(address, uint) external returns (bool); function masterMinter() external view returns (address); function deposit() external payable; function deposit(uint) external; function decimals() external view returns (uint); function target() external view returns (address); function erc20Impl() external view returns (address); function custodian() external view returns (address); function requestPrint(address, uint) external returns (bytes32); function confirmPrint(bytes32) external; function invest(uint) external; function increaseSupply(uint) external; function supplyController() external view returns (address); function getModules() external view returns (address[] memory); function addMinter(address) external; function governance() external view returns (address); function core() external view returns (address); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function symbol() external view returns (string memory); function getFinalTokens() external view returns (address[] memory); function joinPool(uint, uint[] memory) external; function getBalance(address) external view returns (uint); function createTokens(uint) external returns (bool); function resolverAddressesRequired() external view returns (bytes32[] memory addresses); function exchangeRateStored() external view returns (uint); function accrueInterest() external returns (uint); function resolver() external view returns (address); function repository(bytes32) external view returns (address); function underlying() external view returns (address); function mint(uint) external returns (uint); function redeem(uint) external returns (uint); function redeemUnderlying(uint) external returns (uint); function minter() external view returns (address); function borrow(uint) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IUNISWAP { function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual payable returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../lib/Math.sol'; contract Formula { using SafeMath for uint; constructor (){} function div(uint a, uint b) external pure returns(uint){ return a.div(b); } function mul(uint a, uint b) external pure returns(uint){ return a.mul(b); } function add(uint a, uint b) external pure returns(uint){ return a.add(b); } function sub(uint a, uint b) external pure returns(uint){ return a.sub(b); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/proxy/Initializable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import '../adapters/CompoundAdapter.sol'; import '../interfaces/IAdapter.sol'; import '../interfaces/INutmeg.sol'; contract MockAdapter is CompoundAdapter { using SafeERC20 for IERC20; using SafeMath for uint; event Received(address, uint); address public immutable weth; constructor(INutmeg nutmegAddr, address wethAddr) CompoundAdapter(nutmegAddr) { weth = wethAddr; } function test() external pure { } function testFail() external pure { require(false, "fail"); } function testBorrow(uint amount) external { INutmeg(nutmeg).borrow(weth, address(this), amount-10, amount); } function testCurrPositionId(uint pos) external view { uint posret = INutmeg(nutmeg).getCurrPositionId(); require(pos == posret, 'testCurrentPosition failed'); } function testPosition(uint pos) external view { INutmeg.Position memory p = INutmeg(nutmeg).getPosition(pos); require(p.id == pos, 'testPosition failed'); } function testRepay(address token, uint repayAmount) external { INutmeg(nutmeg).repay(token, repayAmount); } receive() external payable { emit Received(msg.sender, msg.value); } } /* Local Variables: */ /* mode: javascript */ /* js-indent-level: 2 */ /* End: */ // SPDX-License-Identifier: MIT // Mock WETH token for testing pragma solidity 0.7.6; contract MockWETH { string public constant name = 'Wrapped Ether'; string public constant symbol = 'WETH'; uint8 public constant decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; receive() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint wad) external { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; payable(msg.sender).transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() external view returns (uint) { return address(this).balance; } function approve(address guy, uint wad) external returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != type(uint).max) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../NutDistributor.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // @notice This contract is a version of NutDistributor that allows // the epoch intervals to be changed for testing contract TestNutDistributor is NutDistributor { using SafeMath for uint; function initialize ( address nutAddr, address _governor, uint blocks_per_epoch ) external initializer { initialize(nutAddr, _governor); BLOCKS_PER_EPOCH = blocks_per_epoch; // config echoMap which indicates how many tokens will be distributed at each epoch for (uint i = 0; i < NUM_EPOCH; i++) { Echo storage echo = echoMap[i]; echo.id = i; echo.endBlock = DIST_START_BLOCK.add(BLOCKS_PER_EPOCH.mul(i.add(1))); uint amount = DIST_START_AMOUNT.div(i.add(1)); if (amount < DIST_MIN_AMOUNT) { amount = DIST_MIN_AMOUNT; } echo.amount = amount; } } //@notice output version string function getVersionString() external virtual pure override returns (string memory) { return "test.nutdistrib"; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../Nutmeg.sol"; // @notice This contract is a version of Nutmeg that contains additional // interfaces for testing contract TestNutmeg is Nutmeg { function _testSetBaseAmt ( uint posId, uint baseAmt ) external { positionMap[posId].baseAmt = baseAmt; } function _forceAccrueInterest( address token ) external { accrueInterest(token); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../lib/Governable.sol'; import "../interfaces/IPriceOracle.sol"; contract PriceOracle is IPriceOracle, Governable { mapping(address => uint) public priceMap; event setPriceEvent(address token, uint price); constructor() { __Governable__init(); } /// @notice Return the value of the given token in ETH. /// @param token The ERC20 token function getPrice(address token) external view override returns (uint) { uint price = priceMap[token]; require(price != 0, 'getPrice: price not found.'); return price; } /// @notice Set the prices of the given tokens. /// @param tokens The tokens to set the prices. /// @param prices The prices of tokens. function setPrices(address[] memory tokens, uint[] memory prices) external onlyGov { require(tokens.length == prices.length, 'setPrices: lengths do not match'); for (uint i = 0; i < tokens.length; i++) { priceMap[tokens[i]] = prices[i]; emit setPriceEvent(tokens[i], prices[i]); } } } // 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; /* * @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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.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 !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
This function fills the array between the last epoch at which things were calculated and the current epoch.
function _fillVtbGap(address token, address lender) internal { if (futureVtbEpoch[token][lender] > CURRENT_EPOCH || CURRENT_EPOCH >= NUM_EPOCH ) return; uint futureVtb = futureVtbMap[token][lender]; for (uint i = futureVtbEpoch[token][lender]; i <= CURRENT_EPOCH; i++) { vtbMap[token][lender][i] = futureVtb; } futureVtbEpoch[token][lender] = CURRENT_EPOCH.add(1); }
1,495,826
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; struct Airline { bool registered; bool funded; } struct Flight { bool isRegistered; uint8 statusCode; uint256 takeOff; uint256 landing; address airline; string flightRef; uint price; string from; string to; mapping(address => bool) bookings; mapping(address => uint) insurances; } address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false address public firstAirline; address[] internal passengers; mapping(address => bool) public authorizedCallers; // Addresses allowed to call this contract mapping(address => Airline) public airlines; mapping(bytes32 => Flight) public flights; mapping(address => uint) public withdrawals; uint public registeredAirlinesCount; bytes32[] public flightKeys; uint public indexFlightKeys = 0; event Paid(address recipient, uint amount); event Funded(address airline); event AirlineRegistered(address origin, address newAirline); event Credited(address passenger, uint amount); constructor(address _firstAirline) public { contractOwner = msg.sender; firstAirline = _firstAirline; registeredAirlinesCount = 1; airlines[firstAirline].registered = true; } /** * Modifiers help avoid duplication of code. They are typically used to validate something * before a function is allowed to be executed. */ // 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 } // Modifier that requires the "ContractOwner" account to be the function caller modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } // Modifier that requires caller to be previously authorized address modifier requireCallerAuthorized() { require(authorizedCallers[msg.sender] == true, "Caller is not authorized to call this function"); _; } // TODO: add comments and rename modifier differentModeRequest(bool status) { require(status != operational, "Contract already in the state requested"); _; } modifier requireFlightRegistered(bytes32 flightKey) { require(flights[flightKey].isRegistered, "This flight does not exist"); _; } // TODO: add comments and rename modifier valWithinRange(uint val, uint low, uint up) { require(val < up, "Value higher than max allowed"); require(val > low, "Value lower than min allowed"); _; } // TODO: add comments and rename modifier notYetProcessed(bytes32 flightKey) { require(flights[flightKey].statusCode == 0, "This flight has already been processed"); _; } /** * Utility Functions */ function isOperational() public view returns(bool) { return operational; } // 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 differentModeRequest(mode) { operational = mode; } function authorizeCaller(address callerAddress) external requireContractOwner requireIsOperational { authorizedCallers[callerAddress] = true; } function hasFunded(address airlineAddress) external view returns (bool _hasFunded) { _hasFunded = airlines[airlineAddress].funded; } function isRegistered(address airlineAddress) external view returns (bool _registered) { _registered = airlines[airlineAddress].registered; } function getFlightKey(string flightRef, string destination, uint256 timestamp) public pure returns (bytes32) { // TODO return keccak256(abi.encodePacked(flightRef, destination, timestamp)); } function paxOnFlight(string flightRef, string destination, uint256 timestamp, address passenger) public view returns (bool onFlight) { bytes32 flightKey = getFlightKey(flightRef, destination, timestamp); onFlight = flights[flightKey].bookings[passenger]; } function subscribedInsurance(string flightRef, string destination, uint256 timestamp, address passenger) public view returns (uint amount) { bytes32 flightKey = getFlightKey(flightRef, destination, timestamp); amount = flights[flightKey].insurances[passenger]; } function getFlightPrice(bytes32 flightKey) external view returns (uint price) { price = flights[flightKey].price; } // Add an airline to the registration queue // Can only be called from FlightSuretyApp contract function registerAirline(address airlineAddress, address originAddress) external requireIsOperational requireCallerAuthorized { registeredAirlinesCount++; airlines[airlineAddress].registered = true; emit AirlineRegistered(originAddress, airlineAddress); } function registerFlight(uint _takeOff, uint _landing, string _flight, uint _price, string _from, string _to, address originAddress) external requireIsOperational requireCallerAuthorized { require(_takeOff > now, "A flight cannot take off in the past"); require(_landing > _takeOff, "A flight cannot land before taking off"); Flight memory flight = Flight(true, 0, _takeOff, _landing, originAddress, _flight, _price, _from, _to); bytes32 flightKey = keccak256(abi.encodePacked(_flight, _to, _landing)); flights[flightKey] = flight; indexFlightKeys = flightKeys.push(flightKey).sub(1); } // Buy insurance for a flight // TODO: rename to buy function book(bytes32 flightKey, uint amount, address originAddress) external requireIsOperational requireCallerAuthorized requireFlightRegistered(flightKey) payable { Flight storage flight = flights[flightKey]; flight.bookings[originAddress] = true; flight.insurances[originAddress] = amount; passengers.push(originAddress); withdrawals[flight.airline] = flight.price; } // Credits payouts to insurees function creditInsurees(bytes32 flightKey) internal requireIsOperational requireFlightRegistered(flightKey) { Flight storage flight = flights[flightKey]; for (uint i = 0; i < passengers.length; i++) { withdrawals[passengers[i]] = flight.insurances[passengers[i]]; emit Credited(passengers[i], flight.insurances[passengers[i]]); } } // Transfers eligible payout funds to insuree function pay(address originAddress) external requireIsOperational requireCallerAuthorized { // Check-Effect-Interaction pattern to protect against re-entracy attack // 1. Check require(withdrawals[originAddress] > 0, "No amount to be transferred to this address"); // 2. Effect uint amount = withdrawals[originAddress]; withdrawals[originAddress] = 0; // 3. Interaction originAddress.transfer(amount); emit Paid(originAddress, amount); } // 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 originAddress) public requireIsOperational requireCallerAuthorized payable { airlines[originAddress].funded = true; emit Funded(originAddress); } function processFlightStatus(bytes32 flightKey, uint8 statusCode) external requireFlightRegistered(flightKey) requireIsOperational requireCallerAuthorized notYetProcessed(flightKey) { // 1. Check Flight storage flight = flights[flightKey]; // 2. Effect flight.statusCode = statusCode; // 3. Interact // 20 = "flight delay due to airline" if (statusCode == 20) { creditInsurees(flightKey); } } // Fallback function for funding smart contract. function() external requireCallerAuthorized payable { require(msg.data.length == 0); fund(msg.sender); } }
Add an airline to the registration queue Can only be called from FlightSuretyApp contract
function registerAirline(address airlineAddress, address originAddress) external requireIsOperational requireCallerAuthorized { registeredAirlinesCount++; airlines[airlineAddress].registered = true; emit AirlineRegistered(originAddress, airlineAddress); }
15,788,852
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Proof of a witnessed event by CENNZnet validators struct CENNZnetEventProof { // The Id (nonce) of the event uint256 eventId; // The validator set Id which witnessed the event uint32 validatorSetId; // v,r,s are sparse arrays expected to align w public key in 'validators' // i.e. v[i], r[i], s[i] matches the i-th validator[i] // v part of validator signatures uint8[] v; // r part of validator signatures bytes32[] r; // s part of validator signatures bytes32[] s; // The validator addresses address[] validators; } // Provides methods for verifying messages from the CENNZnet validator set contract CENNZnetBridge is Ownable { // map from validator set nonce to keccak256 digest of validator ECDSA addresses (i.e bridge session keys) // these should be encoded in sorted order matching `pallet_session::Module<T>::validators()` to create the digest // signatures from a threshold of these addresses are considered approved by the CENNZnet protocol mapping(uint => bytes32) public validatorSetDigests; // Nonce for validator set changes uint32 public activeValidatorSetId; // Message nonces. // CENNZnet will only validate one message per nonce. // Claiming out of order is ok. mapping(uint => bool) public eventIds; // Fee for CENNZnet message verification // Offsets bridge upkeep costs i.e updating the validator set uint public verificationFee = 1e15; // Acceptance threshold in % uint public thresholdPercent = 60; // Number of eras before a bridge message will be considered expired uint public proofTTL = 3; // Whether the bridge is active or not bool public active = true; // Max reward paid out to successful caller of `setValidator` uint public maxRewardPayout = 1e18; event SetValidators(bytes32 validatorSetDigest, uint reward, uint32 validatorSetId); // Verify a message was authorised by CENNZnet validators. // Callable by anyone. // Caller must provide `verificationFee`. // Requires signatures from a threshold CENNZnet validators at proof.validatorSetId. // Requires proof is not older than `proofTTL` eras // Halts on failure // // Parameters: // - message: the unhashed message data packed wide w validatorSetId & eventId e.g. `abi.encode(arg0, arg2, validatorSetId, eventId);` // - proof: Signed witness material generated by CENNZnet proving 'message' function verifyMessage(bytes calldata message, CENNZnetEventProof calldata proof) payable external { require(active, "bridge inactive"); uint256 eventId = proof.eventId; require(!eventIds[eventId], "eventId replayed"); require(msg.value >= verificationFee || msg.sender == address(this), "must supply verification fee"); uint32 validatorSetId = proof.validatorSetId; require(validatorSetId <= activeValidatorSetId, "future validator set"); require(activeValidatorSetId - validatorSetId <= proofTTL, "expired proof"); address[] memory _validators = proof.validators; // audit item #1 require(_validators.length > 0, "invalid validator set"); require(keccak256(abi.encode(_validators)) == validatorSetDigests[validatorSetId], "unexpected validator digest"); bytes32 digest = keccak256(message); uint acceptanceTreshold = (_validators.length * thresholdPercent / 100); uint witnessCount; bytes32 ommited; for (uint i; i < _validators.length; i++) { // check signature omitted == bytes32(0) if(proof.r[i] != ommited) { // check signature require(_validators[i] == ecrecover(digest, proof.v[i], proof.r[i], proof.s[i]), "signature invalid"); witnessCount += 1; // have we got proven consensus? if(witnessCount >= acceptanceTreshold) { break; } } } require(witnessCount >= acceptanceTreshold, "not enough signatures"); eventIds[eventId] = true; } // Update the known CENNZnet validator set // // Requires signatures from a threshold of current CENNZnet validators // v,r,s are sparse arrays expected to align w addresses / public key in 'validators' // i.e. v[i], r[i], s[i] matches the i-th validator[i] function setValidators( address[] calldata newValidators, uint32 newValidatorSetId, CENNZnetEventProof calldata proof ) external payable { require(newValidators.length > 0, "empty validator set"); require(newValidatorSetId > activeValidatorSetId , "validator set id replayed"); bytes memory message = abi.encode(newValidators, newValidatorSetId, proof.validatorSetId, proof.eventId); this.verifyMessage(message, proof); // update set digest and active id bytes32 validatorSetDigest = keccak256(abi.encode(newValidators)); validatorSetDigests[newValidatorSetId] = validatorSetDigest; activeValidatorSetId = newValidatorSetId; // return accumulated fees to the sender as a reward, capped at `maxRewardPayout` uint reward = Math.min(address(this).balance, maxRewardPayout); (bool sent, ) = msg.sender.call{value: reward}(""); require(sent, "Failed to send Ether"); emit SetValidators(validatorSetDigest, reward, newValidatorSetId); } // Admin functions // force set the active CENNZnet validator set function forceActiveValidatorSet(address[] calldata _validators, uint32 validatorSetId) external onlyOwner { require(_validators.length > 0, "empty validator set"); require(validatorSetId >= activeValidatorSetId, "set is historic"); validatorSetDigests[validatorSetId] = keccak256(abi.encode(_validators)); activeValidatorSetId = validatorSetId; } // Force set a historic CENNZnet validator set // Sets older than proofTTL are not modifiable (since they cannot produce valid proofs any longer) function forceHistoricValidatorSet(address[] calldata _validators, uint32 validatorSetId) external onlyOwner { require(_validators.length > 0, "empty validator set"); require(validatorSetId + proofTTL > activeValidatorSetId, "set is inactive"); validatorSetDigests[validatorSetId] = keccak256(abi.encode(_validators)); } // Set the TTL for historic validator set proofs function setProofTTL(uint newTTL) external onlyOwner { proofTTL = newTTL; } // Set the max reward payout for `setValidator` incentive function setMaxRewardPayout(uint newMaxRewardPayout) external onlyOwner { maxRewardPayout = newMaxRewardPayout; } // Set the fee for verify messages function setVerificationFee(uint newFee) external onlyOwner { verificationFee = newFee; } // Set the threshold % required for proof verification function setThreshold(uint newThresholdPercent) external onlyOwner { require(newThresholdPercent <= 100, "percent must be <= 100"); thresholdPercent = newThresholdPercent; } // Activate/deactivate the bridge function setActive(bool active_) external onlyOwner { active = active_; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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; } }
Update the known CENNZnet validator set Requires signatures from a threshold of current CENNZnet validators v,r,s are sparse arrays expected to align w addresses / public key in 'validators' i.e. v[i], r[i], s[i] matches the i-th validator[i] update set digest and active id return accumulated fees to the sender as a reward, capped at `maxRewardPayout`
function setValidators( address[] calldata newValidators, uint32 newValidatorSetId, CENNZnetEventProof calldata proof ) external payable { require(newValidators.length > 0, "empty validator set"); require(newValidatorSetId > activeValidatorSetId , "validator set id replayed"); bytes memory message = abi.encode(newValidators, newValidatorSetId, proof.validatorSetId, proof.eventId); this.verifyMessage(message, proof); bytes32 validatorSetDigest = keccak256(abi.encode(newValidators)); validatorSetDigests[newValidatorSetId] = validatorSetDigest; activeValidatorSetId = newValidatorSetId; uint reward = Math.min(address(this).balance, maxRewardPayout); require(sent, "Failed to send Ether"); emit SetValidators(validatorSetDigest, reward, newValidatorSetId); }
1,434,987
pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IERC20Burnable.sol"; import {YearnVaultAdapterWithIndirection} from "./adapters/YearnVaultAdapterWithIndirection.sol"; import {VaultWithIndirection} from "./libraries/alchemist/VaultWithIndirection.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; // ___ __ __ _ ___ __ _ // / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) // / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _ // /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_) // // .___________..______ ___ .__ __. _______..___ ___. __ __ .___________. _______ .______ // | || _ \ / \ | \ | | / || \/ | | | | | | || ____|| _ \ // `---| |----`| |_) | / ^ \ | \| | | (----`| \ / | | | | | `---| |----`| |__ | |_) | // | | | / / /_\ \ | . ` | \ \ | |\/| | | | | | | | | __| | / // | | | |\ \----. / _____ \ | |\ | .----) | | | | | | `--' | | | | |____ | |\ \----. // |__| | _| `._____|/__/ \__\ |__| \__| |_______/ |__| |__| \______/ |__| |_______|| _| `._____| /** * @dev Implementation of the {IERC20Burnable} 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 {IERC20Burnable-approve}. */ contract TransmuterB is Context { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; using Address for address; using VaultWithIndirection for VaultWithIndirection.Data; using VaultWithIndirection for VaultWithIndirection.List; address public constant ZERO_ADDRESS = address(0); uint256 public transmutationPeriod; address public alToken; address public token; mapping(address => uint256) public depositedAlTokens; mapping(address => uint256) public tokensInBucket; mapping(address => uint256) public realisedTokens; mapping(address => uint256) public lastDividendPoints; mapping(address => bool) public userIsKnown; mapping(uint256 => address) public userList; uint256 public nextUser; uint256 public totalSupplyAltokens; uint256 public buffer; uint256 public lastDepositBlock; ///@dev values needed to calculate the distribution of base asset in proportion for alTokens staked uint256 public pointMultiplier = 10e18; uint256 public totalDividendPoints; uint256 public unclaimedDividends; /// @dev alchemist addresses whitelisted mapping (address => bool) public whiteList; /// @dev addresses whitelisted to run keepr jobs (harvest) mapping (address => bool) public keepers; /// @dev The threshold above which excess funds will be deployed to yield farming activities uint256 public plantableThreshold = 5000000000000000000000000; // 5mm /// @dev The % margin to trigger planting or recalling of funds uint256 public plantableMargin = 5; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can perform emergency activities address public sentinel; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public pause; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added mapping(YearnVaultAdapterWithIndirection => bool) public adapters; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. VaultWithIndirections before the last element are considered inactive and are expected to be cleared. VaultWithIndirection.List private _vaults; /// @dev make sure the contract is only initialized once. bool public initialized; /// @dev mapping of user account to the last block they acted mapping(address => uint256) public lastUserAction; /// @dev number of blocks to delay between allowed user actions uint256 public minUserActionDelay; event GovernanceUpdated( address governance ); event PendingGovernanceUpdated( address pendingGovernance ); event SentinelUpdated( address sentinel ); event TransmuterPeriodUpdated( uint256 newTransmutationPeriod ); event TokenClaimed( address claimant, address token, uint256 amountClaimed ); event AlUsdStaked( address staker, uint256 amountStaked ); event AlUsdUnstaked( address staker, uint256 amountUnstaked ); event Transmutation( address transmutedTo, uint256 amountTransmuted ); event ForcedTransmutation( address transmutedBy, address transmutedTo, uint256 amountTransmuted ); event Distribution( address origin, uint256 amount ); event WhitelistSet( address whitelisted, bool state ); event KeepersSet( address[] keepers, bool[] states ); event PlantableThresholdUpdated( uint256 plantableThreshold ); event PlantableMarginUpdated( uint256 plantableMargin ); event MinUserActionDelayUpdated( uint256 minUserActionDelay ); event ActiveVaultUpdated( YearnVaultAdapterWithIndirection indexed adapter ); event PauseUpdated( bool status ); event FundsRecalled( uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue ); event FundsHarvested( uint256 withdrawnAmount, uint256 decreasedValue ); event RewardsUpdated( address treasury ); event MigrationComplete( address migrateTo, uint256 fundsMigrated ); constructor(address _alToken, address _token, address _governance) public { require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov"); governance = _governance; alToken = _alToken; token = _token; transmutationPeriod = 500000; minUserActionDelay = 1; pause = true; } ///@return displays the user's share of the pooled alTokens. function dividendsOwing(address account) public view returns (uint256) { uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]); return depositedAlTokens[account].mul(newDividendPoints).div(pointMultiplier); } /// @dev Checks that caller is not a eoa. /// /// This is used to prevent contracts from interacting. modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "no contract calls"); _; } ///@dev modifier to fill the bucket and keep bookkeeping correct incase of increase/decrease in shares modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } ///@dev modifier add users to userlist. Users are indexed in order to keep track of when a bond has been filled modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } ///@dev run the phased distribution of the buffered funds modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; // check if there is something in bufffer if (_buffer > 0) { // NOTE: if last deposit was updated in the same block as the current call // then the below logic gates will fail //calculate diffrence in time uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); // distribute all if bigger than timeframe if(deltaTime >= transmutationPeriod) { _toDistribute = _buffer; } else { //needs to be bigger than 0 cuzz solidity no decimals if(_buffer.mul(deltaTime) > transmutationPeriod) { _toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod); } } // factually allocate if any needs distribution if(_toDistribute > 0){ // remove from buffer buffer = _buffer.sub(_toDistribute); // increase the allocation increaseAllocations(_toDistribute); } } // current timeframe is now the last lastDepositBlock = _currentBlock; _; } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; } /// @dev A modifier which checks if caller is a keepr. modifier onlyKeeper() { require(keepers[msg.sender], "Transmuter: !keeper"); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; } /// @dev checks that the block delay since a user's last action is longer than the minium delay /// modifier ensureUserActionDelay() { require(block.number.sub(lastUserAction[msg.sender]) >= minUserActionDelay, "action delay not met"); lastUserAction[msg.sender] = block.number; _; } ///@dev set the transmutationPeriod variable /// /// sets the length (in blocks) of one full distribution phase function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov() { transmutationPeriod = newTransmutationPeriod; emit TransmuterPeriodUpdated(transmutationPeriod); } ///@dev claims the base token after it has been transmuted /// ///This function reverts if there is no realisedToken balance function claim() public noContractAllowed() { address sender = msg.sender; require(realisedTokens[sender] > 0); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; ensureSufficientFundsExistLocally(value); IERC20Burnable(token).safeTransfer(sender, value); emit TokenClaimed(sender, token, value); } ///@dev Withdraws staked alTokens from the transmuter /// /// This function reverts if you try to draw more tokens than you deposited /// ///@param amount the amount of alTokens to unstake function unstake(uint256 amount) public noContractAllowed() updateAccount(msg.sender) { // by calling this function before transmuting you forfeit your gained allocation address sender = msg.sender; require(depositedAlTokens[sender] >= amount,"Transmuter: unstake amount exceeds deposited amount"); depositedAlTokens[sender] = depositedAlTokens[sender].sub(amount); totalSupplyAltokens = totalSupplyAltokens.sub(amount); IERC20Burnable(alToken).safeTransfer(sender, amount); emit AlUsdUnstaked(sender, amount); } ///@dev Deposits alTokens into the transmuter /// ///@param amount the amount of alTokens to stake function stake(uint256 amount) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) checkIfNewUser() { require(!pause, "emergency pause enabled"); // requires approval of AlToken first address sender = msg.sender; //require tokens transferred in; IERC20Burnable(alToken).safeTransferFrom(sender, address(this), amount); totalSupplyAltokens = totalSupplyAltokens.add(amount); depositedAlTokens[sender] = depositedAlTokens[sender].add(amount); emit AlUsdStaked(sender, amount); } /// @dev Converts the staked alTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket /// /// once the alToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim() /// /// reverts if there are no pendingdivs or tokensInBucket function transmute() public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; // check bucket overflow if (pendingz > depositedAlTokens[sender]) { diff = pendingz.sub(depositedAlTokens[sender]); // remove overflow pendingz = depositedAlTokens[sender]; } // decrease altokens depositedAlTokens[sender] = depositedAlTokens[sender].sub(pendingz); // BURN ALTOKENS IERC20Burnable(alToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow increaseAllocations(diff); // add payout realisedTokens[sender] = realisedTokens[sender].add(pendingz); emit Transmutation(sender, pendingz); } /// @dev Executes transmute() on another account that has had more base tokens allocated to it than alTokens staked. /// /// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action /// /// This function reverts if the address to transmute is not over-filled. /// /// @param toTransmute address of the account you will force transmute. function forceTransmute(address toTransmute) public noContractAllowed() ensureUserActionDelay() runPhasedDistribution() updateAccount(msg.sender) updateAccount(toTransmute) checkIfNewUser() { //load into memory address sender = msg.sender; uint256 pendingz = tokensInBucket[toTransmute]; // check restrictions require( pendingz > depositedAlTokens[toTransmute], "Transmuter: !overflow" ); // empty bucket tokensInBucket[toTransmute] = 0; // calculaate diffrence uint256 diff = pendingz.sub(depositedAlTokens[toTransmute]); // remove overflow pendingz = depositedAlTokens[toTransmute]; // decrease altokens depositedAlTokens[toTransmute] = 0; // BURN ALTOKENS IERC20Burnable(alToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow tokensInBucket[sender] = tokensInBucket[sender].add(diff); // add payout realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz); uint256 value = realisedTokens[toTransmute]; ensureSufficientFundsExistLocally(value); // force payout of realised tokens of the toTransmute address realisedTokens[toTransmute] = 0; IERC20Burnable(token).safeTransfer(toTransmute, value); emit ForcedTransmutation(sender, toTransmute, value); } /// @dev Transmutes and unstakes all alTokens /// /// This function combines the transmute and unstake functions for ease of use function exit() public noContractAllowed() { transmute(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Transmutes and claims all converted base tokens. /// /// This function combines the transmute and claim functions while leaving your remaining alTokens staked. function transmuteAndClaim() public noContractAllowed() { transmute(); claim(); } /// @dev Transmutes, claims base tokens, and withdraws alTokens. /// /// This function helps users to exit the transmuter contract completely after converting their alTokens to the base pair. function transmuteClaimAndWithdraw() public noContractAllowed() { transmute(); claim(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Distributes the base token proportionally to all alToken stakers. /// /// This function is meant to be called by the Alchemist contract for when it is sending yield to the transmuter. /// Anyone can call this and add funds, idk why they would do that though... /// /// @param origin the account that is sending the tokens to be distributed. /// @param amount the amount of base tokens to be distributed to the transmuter. function distribute(address origin, uint256 amount) public onlyWhitelisted() runPhasedDistribution() { require(!pause, "emergency pause enabled"); IERC20Burnable(token).safeTransferFrom(origin, address(this), amount); buffer = buffer.add(amount); _plantOrRecallExcessFunds(); emit Distribution(origin, amount); } /// @dev Allocates the incoming yield proportionally to all alToken stakers. /// /// @param amount the amount of base tokens to be distributed in the transmuter. function increaseAllocations(uint256 amount) internal { if(totalSupplyAltokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add( amount.mul(pointMultiplier).div(totalSupplyAltokens) ); unclaimedDividends = unclaimedDividends.add(amount); } else { buffer = buffer.add(amount); } } /// @dev Gets the status of a user's staking position. /// /// The total amount allocated to a user is the sum of pendingdivs and inbucket. /// /// @param user the address of the user you wish to query. /// /// returns user status function userInfo(address user) public view returns ( uint256 depositedAl, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedAl = depositedAlTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedAlTokens[user]).div(totalSupplyAltokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedAl, _pendingdivs, _inbucket, _realised); } /// @dev Gets the status of multiple users in one call /// /// This function is used to query the contract to check for /// accounts that have overfilled positions in order to check /// who can be force transmuted. /// /// @param from the first index of the userList /// @param to the last index of the userList /// /// returns the userList with their staking status in paginated form. function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; address[] memory _theUserList = new address[](delta); //user uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod); if(block.number.sub(lastDepositBlock) > transmutationPeriod){ _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedAlTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } /// @dev Gets info on the buffer /// /// This function is used to query the contract to get the /// latest state of the buffer /// /// @return _toDistribute the amount ready to be distributed /// @return _deltaBlocks the amount of time since the last phased distribution /// @return _buffer the amount in the buffer function bufferInfo() public view returns (uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer){ _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(transmutationPeriod); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov() { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance,"!pendingGovernance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } /// @dev Sets the whitelist /// /// This function reverts if the caller is not governance /// /// @param _toWhitelist the address to alter whitelist permissions. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyGov() { whiteList[_toWhitelist] = _state; emit WhitelistSet(_toWhitelist, _state); } /// @dev Sets the keeper list /// /// This function reverts if the caller is not governance /// /// @param _keepers the accounts to set states for. /// @param _states the accounts states. function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() { uint256 n = _keepers.length; for(uint256 i = 0; i < n; i++) { keepers[_keepers[i]] = _states[i]; } emit KeepersSet(_keepers, _states); } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(YearnVaultAdapterWithIndirection _adapter) external onlyGov { require(!initialized, "Transmuter: already initialized"); require(rewards != ZERO_ADDRESS, "Transmuter: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } function migrate(YearnVaultAdapterWithIndirection _adapter) external onlyGov() { _updateActiveVault(_adapter); } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal { require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0."); require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultWithIndirection.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (address) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return address(_vault.adapter); } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Recalls funds from active vault if less than amt exist locally /// /// @param amt amount of funds that need to exist locally to fulfill pending request function ensureSufficientFundsExistLocally(uint256 amt) internal { uint256 currentBal = IERC20Burnable(token).balanceOf(address(this)); if (currentBal < amt) { uint256 diff = amt - currentBal; // get enough funds from active vault to replenish local holdings & fulfill claim request _recallExcessFundsFromActiveVault(plantableThreshold.add(diff)); } } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function recallAllFundsFromVault(uint256 _vaultId) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallAllFundsFromVault(_vaultId); } /// @dev Recalls all planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds function _recallAllFundsFromVault(uint256 _vaultId) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdrawAll(address(this)); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function recallFundsFromVault(uint256 _vaultId, uint256 _amount) external { require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel"); _recallFundsFromVault(_vaultId, _amount); } /// @dev Recalls planted funds from a target vault /// /// @param _vaultId the id of the vault from which to recall funds /// @param _amount the amount of funds to recall function _recallFundsFromVault(uint256 _vaultId, uint256 _amount) internal { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); } /// @dev Recalls planted funds from the active vault /// /// @param _amount the amount of funds to recall function _recallFundsFromActiveVault(uint256 _amount) internal { _recallFundsFromVault(_vaults.lastIndex(), _amount); } /// @dev Plants or recalls funds from the active vault /// /// This function plants excess funds in an external vault, or recalls them from the external vault /// Should only be called as part of distribute() function _plantOrRecallExcessFunds() internal { // check if the transmuter holds more funds than plantableThreshold uint256 bal = IERC20Burnable(token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; // if total funds above threshold, send funds to vault VaultWithIndirection.Data storage _activeVault = _vaults.last(); _activeVault.deposit(plantAmt); } else if (bal < plantableThreshold.sub(marginVal)) { // if total funds below threshold, recall funds from vault // first check that there are enough funds in vault uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } } /// @dev Recalls up to the harvestAmt from the active vault /// /// This function will recall less than harvestAmt if only less is available /// /// @param _recallAmt the amount to harvest from the active vault function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal { VaultWithIndirection.Data storage _activeVault = _vaults.last(); uint256 activeVaultVal = _activeVault.totalValue(); if (activeVaultVal < _recallAmt) { _recallAmt = activeVaultVal; } if (_recallAmt > 0) { _recallFundsFromActiveVault(_recallAmt); } } /// @dev Sets the address of the sentinel /// /// @param _sentinel address of the new sentinel function setSentinel(address _sentinel) external onlyGov() { require(_sentinel != ZERO_ADDRESS, "Transmuter: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the threshold of total held funds above which excess funds will be planted in yield farms. /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableThreshold the new plantable threshold. function setPlantableThreshold(uint256 _plantableThreshold) external onlyGov() { plantableThreshold = _plantableThreshold; emit PlantableThresholdUpdated(_plantableThreshold); } /// @dev Sets the plantableThreshold margin for triggering the planting or recalling of funds on harvest /// /// This function reverts if the caller is not the current governance. /// /// @param _plantableMargin the new plantable margin. function setPlantableMargin(uint256 _plantableMargin) external onlyGov() { plantableMargin = _plantableMargin; emit PlantableMarginUpdated(_plantableMargin); } /// @dev Sets the minUserActionDelay /// /// This function reverts if the caller is not the current governance. /// /// @param _minUserActionDelay the new min user action delay. function setMinUserActionDelay(uint256 _minUserActionDelay) external onlyGov() { minUserActionDelay = _minUserActionDelay; emit MinUserActionDelayUpdated(_minUserActionDelay); } /// @dev Sets if the contract should enter emergency exit mode. /// /// There are 2 main reasons to pause: /// 1. Need to shut down deposits in case of an emergency in one of the vaults /// 2. Need to migrate to a new transmuter /// /// While the transmuter is paused, deposit() and distribute() are disabled /// /// @param _pause if the contract should enter emergency exit mode. function setPause(bool _pause) external { require(msg.sender == governance || msg.sender == sentinel, "!(gov || sentinel)"); pause = _pause; emit PauseUpdated(_pause); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external onlyKeeper() returns (uint256, uint256) { VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(rewards); emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov() { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "Transmuter: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Migrates transmuter funds to a new transmuter /// /// @param migrateTo address of the new transmuter function migrateFunds(address migrateTo) external onlyGov() { require(migrateTo != address(0), "cannot migrate to 0x0"); require(pause, "migrate: set emergency exit first"); // leave enough funds to service any pending transmutations uint256 totalFunds = IERC20Burnable(token).balanceOf(address(this)); uint256 migratableFunds = totalFunds.sub(totalSupplyAltokens, "not enough funds to service stakes"); IERC20Burnable(token).approve(migrateTo, migratableFunds); ITransmuter(migrateTo).distribute(address(this), migratableFunds); emit MigrationComplete(migrateTo, migratableFunds); } }
Updates the active vault. This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. _adapter the adapter for the new active vault.
function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal { require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0."); require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch."); require(!adapters[_adapter], "Adapter already in use"); adapters[_adapter] = true; _vaults.push(VaultWithIndirection.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); }
2,510,744
./partial_match/42/0x4E657A526b7f12695A9388b6462CA4eFBF68AC2D/sources/CompoundLeverageModule.sol
Invoke redeem from SetToken. If cEther, then also wrap ETH into WETH./ Compound's redeem function signature is: redeemUnderlying(uint256 _underlyingAmount)
function _redeemUnderlying(ISetToken _setToken, address _cToken, uint256 _redeemNotional) internal { bytes memory redeemCallData = abi.encodeWithSignature("redeemUnderlying(uint256)", _redeemNotional); bytes memory returndata = _setToken.invoke(_cToken, 0, redeemCallData); require( abi.decode(returndata, (uint256)) == 0, "Redeem failed" ); if (_cToken == cEther) { _setToken.invokeWrapWETH(weth, _redeemNotional); } }
9,090,610
/** *Submitted for verification at Etherscan.io on 2020-03-17 */ pragma solidity ^0.5.15; // https://github.com/makerdao/dss/blob/master/src/jug.sol contract JugAbstract { function drip(bytes32) external returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/pot.sol contract PotAbstract { function drip() external returns (uint256); function dsr() public view returns (uint256); function chi() public view returns (uint256); function rho() public view returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/vat.sol contract VatAbstract { function dai(address) public view returns (uint256); function sin(address) public view returns (uint256); } // https://github.com/makerdao/dss/blob/master/src/vow.sol contract VowAbstract { function sin(uint256) public view returns (uint256); function Sin() public view returns (uint256); function Ash() public view returns (uint256); function bump() public view returns (uint256); function hump() public view returns (uint256); function flap() external returns (uint256); function heal(uint256) external; } // https://github.com/makerdao/sai/blob/master/src/pit.sol contract GemPitAbstract { function burn(address) public; } // https://github.com/dapphub/ds-token/blob/master/src/token.sol contract DSTokenAbstract { function balanceOf(address) external view returns (uint256); } // 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() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL if (now == pa.rho()) return pa.chi(); return rmul(rpow(pa.dsr(), now - pa.rho(), ONE), pa.chi()); } // Pass the Pot Abstract for additional operations function pot() public view returns (PotAbstract) { //inject PUBLIC FUNC TO EXTERNAL return pa; } } // 1111111 1=111)) HADAIKEN // // Optimized contract for performing some or all of the functions that // keep Multi-Collateral Dai running. contract Hadaiken { address constant internal PIT = address(0x69076e44a9C70a67D5b79d95795Aba299083c275); address constant internal MKR = address(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2); address constant internal JUG = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1); address constant internal POT = address(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7); address constant internal VAT = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); address constant internal VOW = address(0xA950524441892A31ebddF91d3cEEFa04Bf454466); GemPitAbstract constant internal pit = GemPitAbstract(PIT); DSTokenAbstract constant internal gem = DSTokenAbstract(MKR); JugAbstract constant internal jug = JugAbstract(JUG); PotAbstract constant internal pot = PotAbstract(POT); VowAbstract constant internal vow = VowAbstract(VOW); VatAbstract constant internal vat = VatAbstract(VAT); PotHelper internal poth; bytes32 constant internal ETH_A = bytes32("ETH-A"); bytes32 constant internal BAT_A = bytes32("BAT-A"); bytes32 constant internal USDC_A = bytes32("USDC-A"); constructor() public { poth = new PotHelper(POT); } // Raw System Debt function _rawSysDebt() internal view returns (uint256) { return (vat.sin(VOW) - vow.Sin() - vow.Ash()); } function rawSysDebt() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return _rawSysDebt(); } function _sysSurplusThreshold() internal view returns (uint256) { return (vat.sin(VOW) + vow.bump() + vow.hump()); } function sysSurplusThreshold() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return _sysSurplusThreshold(); } // Saves you money. function heal() public { //inject PUBLIC FUNC TO EXTERNAL _heal(); } // Returns the amount of debt healed if you're curious about that sort of thing. function healStat() public returns (uint256 sd) { //inject PUBLIC FUNC TO EXTERNAL sd = _rawSysDebt(); _heal(); } // No return here. I want to save gas and who cares. function _heal() internal { vow.heal(_rawSysDebt()); } // Return the new chi value after drip. function drip() public returns (uint256 chi) { //inject PUBLIC FUNC TO EXTERNAL chi = pot.drip(); _dripIlks(); } // Returns a simulated chi value function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL return poth.drop(); } function _dripPot() internal { pot.drip(); } function dripIlks() public { //inject PUBLIC FUNC TO EXTERNAL _dripIlks(); } function _dripIlks() internal { jug.drip(ETH_A); jug.drip(BAT_A); jug.drip(USDC_A); } function kickable() public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL return _kickable(); } // Can we bump an auction? function _kickable() internal view returns (bool) { // Assume heal is called prior to kick. // require(vat.dai(address(this)) >= add(add(vat.sin(address(this)), bump), hump), "Vow/insufficient-surplus"); // require(sub(sub(vat.sin(address(this)), Sin), Ash) == 0, "Vow/debt-not-zero"); return (vat.dai(VOW) >= _sysSurplusThreshold()); } // Burn all of the MKR in the Sai Pit function finishhim() public returns (uint256 burned) { //inject PUBLIC FUNC TO EXTERNAL burned = gem.balanceOf(PIT); _finishhim(); } function _finishhim() internal { pit.burn(MKR); } // Kick off an auction and return the auction ID function ccccombobreaker() public returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL _heal(); // Flap requires debt == 0 return vow.flap(); } // Kick off an auction and throw away id function _ccccombobreaker() internal { vow.flap(); } // Kitchen sink. Call this early and often. function hadaiken() public { //inject PUBLIC FUNC TO EXTERNAL _dripPot(); // Update the chi _dripIlks(); // Updates the Ilk rates _heal(); // Cancel out system debt with system surplus if (_kickable()) { _ccccombobreaker(); } // Start an auction } }
Kick off an auction and throw away id
function _ccccombobreaker() internal { vow.flap(); return vow.flap(); }
7,265,622
./full_match/3/0xf8b954D3290b31a8017936221D06d1A674446FA2/sources/browser/YFKA.sol
POST PRESALE. OWNERSHIP TRANSFERRED TO SMART CONTRACT
function mint(address to, uint256 amount) onlyOwner public { require(presaleRunning == false || tuning == true); balances[to] = balances[to].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(this), msg.sender, amount); }
8,109,000
// Sources flattened with hardhat v2.1.1 https://hardhat.org // File contracts/interfaces/IERC20.sol pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/IMaintainersRegistry.sol pragma solidity ^0.6.12; /** * IMaintainersRegistry contract. * @author Nikola Madjarevic * Date created: 8.5.21. * Github: madjarevicn */ interface IMaintainersRegistry { function isMaintainer(address _address) external view returns (bool); } // File contracts/system/HordUpgradable.sol pragma solidity ^0.6.12; /** * HordUpgradables contract. * @author Nikola Madjarevic * Date created: 8.5.21. * Github: madjarevicn */ contract HordUpgradable { address public hordCongress; IMaintainersRegistry public maintainersRegistry; // Only maintainer modifier modifier onlyMaintainer { require(maintainersRegistry.isMaintainer(msg.sender), "HordUpgradable: Restricted only to Maintainer"); _; } // Only chainport congress modifier modifier onlyHordCongress { require(msg.sender == hordCongress, "HordUpgradable: Restricted only to HordCongress"); _; } function setCongressAndMaintainers( address _hordCongress, address _maintainersRegistry ) internal { hordCongress = _hordCongress; maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } function setMaintainersRegistry( address _maintainersRegistry ) public onlyHordCongress { maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC1155/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File contracts/interfaces/IHordTicketFactory.sol pragma solidity ^0.6.12; /** * IHordTicketFactory contract. * @author Nikola Madjarevic * Date created: 11.5.21. * Github: madjarevicn */ interface IHordTicketFactory is IERC1155 { function getTokenSupply(uint tokenId) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/introspection/[email protected] 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); } // File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] 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); } } } } // File @openzeppelin/contracts-upgradeable/proxy/[email protected] // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {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)); } } // File @openzeppelin/contracts-upgradeable/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract 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; } // File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable { function __ERC1155Receiver_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); } function __ERC1155Receiver_init_unchained() internal initializer { _registerInterface( ERC1155ReceiverUpgradeable(address(0)).onERC1155Received.selector ^ ERC1155ReceiverUpgradeable(address(0)).onERC1155BatchReceived.selector ); } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev _Available since v3.1._ */ contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable { function __ERC1155Holder_init() internal initializer { __ERC165_init_unchained(); __ERC1155Receiver_init_unchained(); __ERC1155Holder_init_unchained(); } function __ERC1155Holder_init_unchained() internal initializer { } function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } uint256[50] private __gap; } // File contracts/libraries/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File contracts/HordTicketManager.sol pragma solidity 0.6.12; /** * HordTicketManager contract. * @author Nikola Madjarevic * Date created: 11.5.21. * Github: madjarevicn */ contract HordTicketManager is HordUpgradable, ERC1155HolderUpgradeable { using SafeMath for *; // Minimal time to stake in order to be eligible for claiming NFT uint256 public minTimeToStake; // Minimal amount to stake in order to be eligible for claiming NFT uint256 public minAmountToStake; // Token being staked IERC20 public stakingToken; // Factory of Hord tickets IHordTicketFactory public hordTicketFactory; // Mapping championId to tokenIds mapping (uint256 => uint256[]) internal championIdToMintedTokensIds; // Users stake struct UserStake { uint256 amountStaked; uint256 amountOfTicketsGetting; uint256 unlockingTime; bool isWithdrawn; } /// @dev Mapping user address to tokenId to stakes for that token mapping(address => mapping(uint => UserStake[])) public addressToTokenIdToStakes; // Count number of reserved tickets for tokenId mapping(uint256 => uint256) internal tokenIdToNumberOfTicketsReserved; event TokensStaked( address user, uint amountStaked, uint inFavorOfTokenId, uint numberOfTicketsReserved, uint unlockingTime ); event NFTsClaimed( address beneficiary, uint256 amountUnstaked, uint256 amountTicketsClaimed, uint tokenId ); function initialize( address _hordCongress, address _maintainersRegistry, address _stakingToken, uint256 _minTimeToStake, uint256 _minAmountToStake ) public initializer { // Set hord congress and maintainers registry setCongressAndMaintainers(_hordCongress, _maintainersRegistry); // Set staking token stakingToken = IERC20(_stakingToken); // Set minimal time to stake tokens minTimeToStake = _minTimeToStake; // Set minimal amount to stake minAmountToStake = _minAmountToStake; } /** * @notice Set hord ticket factory contract. After set first time, * can be changed only by HordCongress * @param _hordTicketFactory is the address of HordTicketFactory contract */ function setHordTicketFactory(address _hordTicketFactory) public { // Initial setting is allowed during deployment, after that only congress can change it if(address(hordTicketFactory) != address(0)) { require(msg.sender == hordCongress); } // Set hord ticket factory hordTicketFactory = IHordTicketFactory(_hordTicketFactory); } /** * @notice Set minimal time to stake, callable only by HordCongress * @param _minimalTimeToStake is minimal amount of time (seconds) user has to stake * staking token in order to be eligible to claim NFT */ function setMinTimeToStake( uint256 _minimalTimeToStake ) onlyHordCongress external { minTimeToStake = _minimalTimeToStake; } /** * @notice Set minimal amount to stake, callable only by HordCongress * @param _minimalAmountToStake is minimal amount of tokens (WEI) user has to stake * in order to be eligible to claim NFT */ function setMinAmountToStake( uint256 _minimalAmountToStake ) onlyHordCongress external { minAmountToStake = _minimalAmountToStake; } /** * @notice Map token id with champion id * @param tokenId is the ID of the token (representing token class / series) * @param championId is the ID of the champion */ function addNewTokenIdForChampion( uint tokenId, uint championId ) external { require(msg.sender == address(hordTicketFactory), "Only Hord Ticket factory can issue a call to this function"); // Push token Id to champion id championIdToMintedTokensIds[championId].push(tokenId); } /** * @notice Stake and reserve NFTs, per specific staking rules * @param tokenId is the ID of the token being staked (class == series) * @param numberOfTickets is representing how many NFTs of same series user wants to get */ function stakeAndReserveNFTs( uint tokenId, uint numberOfTickets ) public { // Get number of reserved tickets uint256 numberOfTicketsReserved = tokenIdToNumberOfTicketsReserved[tokenId]; // Check there's enough tickets to get require(numberOfTicketsReserved.add(numberOfTickets)<= hordTicketFactory.getTokenSupply(tokenId), "Not enough tickets to sell."); // Fixed stake per ticket uint amountOfTokensToStake = minAmountToStake.mul(numberOfTickets); // Transfer tokens from user stakingToken.transferFrom( msg.sender, address(this), amountOfTokensToStake ); UserStake memory userStake = UserStake({ amountStaked: amountOfTokensToStake, amountOfTicketsGetting: numberOfTickets, unlockingTime: minTimeToStake.add(block.timestamp), isWithdrawn: false }); addressToTokenIdToStakes[msg.sender][tokenId].push(userStake); // Increase number of tickets reserved tokenIdToNumberOfTicketsReserved[tokenId] = numberOfTicketsReserved.add(numberOfTickets); emit TokensStaked( msg.sender, amountOfTokensToStake, tokenId, numberOfTickets, userStake.unlockingTime ); } /** * @notice Function to claim NFTs and withdraw tokens staked for that NFTs * @param tokenId is representing token class for which user has performed stake */ function claimNFTs( uint tokenId, uint startIndex, uint endIndex ) public { UserStake [] storage userStakesForNft = addressToTokenIdToStakes[msg.sender][tokenId]; uint256 totalStakeToWithdraw; uint256 ticketsToWithdraw; uint256 i = startIndex; while (i < userStakesForNft.length && i < endIndex) { UserStake storage stake = userStakesForNft[i]; if(stake.isWithdrawn || stake.unlockingTime > block.timestamp) { i++; continue; } totalStakeToWithdraw = totalStakeToWithdraw.add(stake.amountStaked); ticketsToWithdraw = ticketsToWithdraw.add(stake.amountOfTicketsGetting); stake.isWithdrawn = true; i++; } if(totalStakeToWithdraw > 0 && ticketsToWithdraw > 0) { // Transfer staking tokens stakingToken.transfer(msg.sender, totalStakeToWithdraw); // Transfer NFTs hordTicketFactory.safeTransferFrom( address(this), msg.sender, tokenId, ticketsToWithdraw, "0x0" ); // Emit event emit NFTsClaimed( msg.sender, totalStakeToWithdraw, ticketsToWithdraw, tokenId ); } } /** * @notice Get number of specific tokens claimed * @param tokenId is the subject of search */ function getAmountOfTokensClaimed(uint tokenId) external view returns (uint256) { uint mintedSupply = hordTicketFactory.getTokenSupply(tokenId); return mintedSupply.sub(hordTicketFactory.balanceOf(address(this), tokenId)); } /** * @notice Get amount of tickets reserved for selected tokenId * @param tokenId is the subject of search */ function getAmountOfTicketsReserved( uint tokenId ) external view returns (uint256) { return tokenIdToNumberOfTicketsReserved[tokenId]; } /** * @notice Get account stakes for specified token Id * @param account is user address * @param tokenId is the id of the token in favor of which stake is made. */ function getUserStakesForTokenId( address account, uint tokenId ) external view returns ( uint256[] memory, uint256[] memory, uint256[] memory, bool[] memory ) { UserStake [] memory userStakes = addressToTokenIdToStakes[account][tokenId]; uint numberOfStakes = userStakes.length; uint256[] memory amountsStaked = new uint256[](numberOfStakes); uint256[] memory ticketsBought = new uint256[](numberOfStakes); uint256[] memory unlockingTimes = new uint256[](numberOfStakes); bool[] memory isWithdrawn = new bool[](numberOfStakes); for(uint i = 0; i < numberOfStakes; i++) { // Fulfill arrays with stake information amountsStaked[i] = userStakes[i].amountStaked; ticketsBought[i] = userStakes[i].amountOfTicketsGetting; unlockingTimes[i] = userStakes[i].unlockingTime; isWithdrawn[i] = userStakes[i].isWithdrawn; } return (amountsStaked, ticketsBought, unlockingTimes, isWithdrawn); } /** * @notice Get currently how many tokens is account actively staking * @param account is address for which stakes are being checked * @param tokenId is the subject of search for the passed account */ function getCurrentAmountStakedForTokenId( address account, uint tokenId ) external view returns (uint256) { UserStake [] memory userStakes = addressToTokenIdToStakes[account][tokenId]; uint numberOfStakes = userStakes.length; uint amountCurrentlyStaking = 0; for(uint i = 0; i < numberOfStakes; i++) { if(userStakes[i].isWithdrawn == false) { amountCurrentlyStaking = amountCurrentlyStaking.add(userStakes[i].amountStaked); } } return amountCurrentlyStaking; } /** * @notice Function to get all token ids minted for specific champion * @param championId is the db id of the champion */ function getChampionTokenIds( uint championId ) external view returns (uint[] memory) { return championIdToMintedTokensIds[championId]; } /** * @notice Function to get number of stakes for user and token * @param user is the address of selected user * @param tokenId is the ID of the token */ function getNumberOfStakesForUserAndToken( address user, uint tokenId ) external view returns (uint256) { return addressToTokenIdToStakes[user][tokenId].length; } }
IMaintainersRegistry contract. Nikola Madjarevic Date created: 8.5.21. Github: madjarevicn/
interface IMaintainersRegistry { function isMaintainer(address _address) external view returns (bool); } }
14,848,764
/* * This file was generated by MyWish Platform (https://mywish.io/) * The complete code could be found at https://github.com/MyWishPlatform/ * Copyright (C) 2020 MyWish * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.24; /** * @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); } /** * @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 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 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); } } /** * @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; } } /** * @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); } } /** * @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. * @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; } } /** * @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; } } contract FreezableToken is StandardToken { // freezing chains mapping (bytes32 => uint64) internal chains; // freezing amounts for each chain mapping (bytes32 => uint) internal freezings; // total freezing balance per address mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); /** * @dev Gets the balance of the specified address include freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } /** * @dev Gets the balance of the specified address without freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } /** * @dev gets freezing count * @param _addr Address of freeze tokens owner. */ function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } /** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */ function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } /** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in future. */ function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } /** * @dev release first available freezing tokens. */ function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } /** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */ function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { // WISH masc to increase entropy result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } /** * @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 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(); } } contract FreezableMintableToken is FreezableToken, MintableToken { /** * @dev Mint the specified amount of token to the specified address and freeze it until the specified date. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to mint and freeze. * @param _until Release date, must be in future. * @return A boolean that indicates if the operation was successful. */ function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "GOE"; string public constant TOKEN_SYMBOL = "GOE"; bool public constant PAUSED = true; address public constant TARGET_USER = 0x7edfb498a99CC2475db7A426Dff640Fa605daaBA; uint public constant START_TIME = 1600616760; bool public constant CONTINUE_MINTING = true; } /** * @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 { } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } } contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale { function hasStarted() public view returns (bool) { return now >= openingTime; } function startTime() public view returns (uint256) { return openingTime; } function endTime() public view returns (uint256) { return closingTime; } function hasClosed() public view returns (bool) { return super.hasClosed() || capReached(); } function hasEnded() public view returns (bool) { return hasClosed(); } function finalization() internal { super.finalization(); if (PAUSED) { MainToken(token).unpause(); } if (!CONTINUE_MINTING) { require(MintableToken(token).finishMinting()); } Ownable(token).transferOwnership(TARGET_USER); } /** * @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).div(1 ether); } } contract TemplateCrowdsale is Consts, MainCrowdsale { event Initialized(); event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime); bool public initialized = false; constructor(MintableToken _token) public Crowdsale(10 * TOKEN_DECIMAL_MULTIPLIER, 0x7edfb498a99CC2475db7A426Dff640Fa605daaBA, _token) TimedCrowdsale(START_TIME > now ? START_TIME : now, 1609515960) CappedCrowdsale(100000000000000000000000000000) { } function init() public onlyOwner { require(!initialized); initialized = true; if (PAUSED) { MainToken(token).pause(); } transferOwnership(TARGET_USER); emit Initialized(); } /** * @dev override hasClosed to add minimal value logic * @return true if remained to achieve less than minimal */ function hasClosed() public view returns (bool) { bool remainValue = cap.sub(weiRaised) < 50000000000000000; return super.hasClosed() || remainValue; } function setStartTime(uint _startTime) public onlyOwner { // only if CS was not started require(now < openingTime); // only move time to future require(_startTime > openingTime); require(_startTime < closingTime); emit TimesChanged(_startTime, closingTime, openingTime, closingTime); openingTime = _startTime; } function setEndTime(uint _endTime) public onlyOwner { // only if CS was not ended require(now < closingTime); // only if new end time in future require(now < _endTime); require(_endTime > openingTime); emit TimesChanged(openingTime, _endTime, openingTime, closingTime); closingTime = _endTime; } function setTimes(uint _startTime, uint _endTime) public onlyOwner { require(_endTime > _startTime); uint oldStartTime = openingTime; uint oldEndTime = closingTime; bool changed = false; if (_startTime != oldStartTime) { require(_startTime > now); // only if CS was not started require(now < oldStartTime); // only move time to future require(_startTime > oldStartTime); openingTime = _startTime; changed = true; } if (_endTime != oldEndTime) { // only if CS was not ended require(now < oldEndTime); // end time in future require(now < _endTime); closingTime = _endTime; changed = true; } if (changed) { emit TimesChanged(openingTime, _endTime, openingTime, closingTime); } } /** * @dev override purchase validation to add extra value logic. * @return true if sended more than minimal value */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(msg.value >= 50000000000000000); require(msg.value <= 100000000000000000000000000000); super._preValidatePurchase(_beneficiary, _weiAmount); } }
override purchase validation to add extra value logic. return true if sended more than minimal value/
function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(msg.value >= 50000000000000000); require(msg.value <= 100000000000000000000000000000); super._preValidatePurchase(_beneficiary, _weiAmount); }
5,921,233
./partial_match/1/0xb46ec1DB4b766D32fBaF7c30aba1428bd470553E/sources/ARENA.sol
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniV2Routr), tokenAmount); address(this), tokenAmount, lpTokenReceiver, block.timestamp ); }
4,144,517
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; 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: Apache-2.0 pragma solidity 0.7.6; interface IERC1155 { /****************************************| | Events | |_______________________________________*/ /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount ); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts ); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /****************************************| | Functions | |_______________________________________*/ /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data ) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @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; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IERC1155Metadata { event URI(string _uri, uint256 indexed _id); /****************************************| | Functions | |_______________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) external view returns (string memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data ) external returns (bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @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 _amounts, bytes calldata _data ) external returns (bytes4); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import '../../utils/SafeMath.sol'; import '../../interfaces/IERC1155TokenReceiver.sol'; import '../../interfaces/IERC1155.sol'; import '../../utils/Address.sol'; import '../../utils/ERC165.sol'; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC1155, ERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping(address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping(address => mapping(address => bool)) internal operators; /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) public virtual override { require( (msg.sender == _from) || isApprovedForAll(_from, msg.sender), 'ERC1155#safeTransferFrom: INVALID_OPERATOR' ); require(_to != address(0), 'ERC1155#safeTransferFrom: INVALID_RECIPIENT'); // require(_amount <= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public virtual override { // Requirements require( (msg.sender == _from) || isApprovedForAll(_from, msg.sender), 'ERC1155#safeBatchTransferFrom: INVALID_OPERATOR' ); require( _to != address(0), 'ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT' ); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount ) internal { _beforeTokenTransfer(msg.sender, _from, _to, _id, _amount, ''); // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received( address _from, address _to, uint256 _id, uint256 _amount, uint256 _gasLimit, bytes memory _data ) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received{ gas: _gasLimit }(msg.sender, _from, _id, _amount, _data); require( retval == ERC1155_RECEIVED_VALUE, 'ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE' ); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts ) internal { require( _ids.length == _amounts.length, 'ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH' ); _beforeBatchTokenTransfer(msg.sender, _from, _to, _ids, _amounts, ''); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data ) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{ gas: _gasLimit }(msg.sender, _from, _ids, _amounts, _data); require( retval == ERC1155_BATCH_RECEIVED_VALUE, 'ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE' ); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @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) public virtual override { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public view virtual override returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view override returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view override returns (uint256[] memory) { require( _owners.length == _ids.length, 'ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH' ); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | HOOKS | |__________________________________*/ /** * @notice overrideable hook for single transfers. */ function _beforeTokenTransfer( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) internal virtual {} /** * @notice overrideable hook for batch transfers. */ function _beforeBatchTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual {} /***********************************| | ERC165 Functions | |__________________________________*/ /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public pure virtual override returns (bool) { if (_interfaceID == type(IERC1155).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '../../interfaces/IERC1155TokenReceiver.sol'; import '../../utils/ERC165.sol'; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC165, IERC1155TokenReceiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } function supportsInterface(bytes4 _interfaceID) public pure virtual override returns (bool) { if (_interfaceID == type(IERC1155TokenReceiver).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import '../../interfaces/IERC1155Metadata.sol'; import '../../utils/ERC165.sol'; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata is IERC1155Metadata, ERC165 { // URI's default URI prefix string private _baseMetadataURI; // contract metadata URL string private _contractMetadataURI; // Hex numbers for creating hexadecimal tokenId bytes16 private constant HEX_MAP = '0123456789ABCDEF'; // bytes4(keccak256('contractURI()')) == 0xe8a3d485 bytes4 private constant _INTERFACE_ID_CONTRACT_URI = 0xe8a3d485; /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * @return URI string */ function uri(uint256 _id) public view virtual override returns (string memory) { return _uri(_baseMetadataURI, _id, 0); } /** * @notice Opensea calls this fuction to get information about how to display storefront. * * @return full URI to the location of the contract metadata. */ function contractURI() public view returns (string memory) { return _contractMetadataURI; } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_uri(_baseMetadataURI, _tokenIDs[i], 0), _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory newBaseMetadataURI) internal { _baseMetadataURI = newBaseMetadataURI; } /** * @notice Will update the contract metadata URI * @param newContractMetadataURI New contract metadata URI */ function _setContractMetadataURI(string memory newContractMetadataURI) internal { _contractMetadataURI = newContractMetadataURI; } /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` or CONTRACT_URI */ function supportsInterface(bytes4 _interfaceID) public pure virtual override returns (bool) { if ( _interfaceID == type(IERC1155Metadata).interfaceId || _interfaceID == _INTERFACE_ID_CONTRACT_URI ) { return true; } return super.supportsInterface(_interfaceID); } /***********************************| | Utility private Functions | |__________________________________*/ /** * @notice returns uri * @param tokenId Unsigned integer to convert to string */ function _uri( string memory base, uint256 tokenId, uint256 minLength ) internal view returns (string memory) { if (bytes(base).length == 0) base = _baseMetadataURI; // Calculate URI uint256 temp = tokenId; uint256 length = tokenId == 0 ? 2 : 0; while (temp != 0) { length += 2; temp >>= 8; } if (length > minLength) minLength = length; bytes memory buffer = new bytes(minLength); for (uint256 i = minLength; i > minLength - length; --i) { buffer[i - 1] = HEX_MAP[tokenId & 0xf]; tokenId >>= 4; } minLength -= length; while (minLength > 0) buffer[--minLength] = '0'; return string(abi.encodePacked(base, buffer, '.json')); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import './ERC1155.sol'; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { using SafeMath for uint256; /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint( address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { _beforeTokenTransfer(msg.sender, address(0x0), _to, _id, _amount, _data); // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { require( _ids.length == _amounts.length, 'ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH' ); _beforeBatchTokenTransfer( msg.sender, address(0x0), _to, _ids, _amounts, _data ); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived( address(0x0), _to, _ids, _amounts, gasleft(), _data ); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn( address _from, uint256 _id, uint256 _amount ) internal { _beforeTokenTransfer(msg.sender, _from, address(0x0), _id, _amount, ''); //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn( address _from, uint256[] memory _ids, uint256[] memory _amounts ) internal { // Number of mints to execute uint256 nBurn = _ids.length; require( nBurn == _amounts.length, 'ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH' ); _beforeBatchTokenTransfer( msg.sender, _from, address(0x0), _ids, _amounts, '' ); // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: MIT AND Apache-2.0 pragma solidity 0.7.6; /** * Utility library of inline functions on addresses */ library Address { // Default hash for EOA accounts returned by extcodehash bytes32 internal constant ACCOUNT_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract. * @param _address address of the account to check * @return Whether the target address is a contract */ function isContract(address _address) internal view returns (bool) { bytes32 codehash; // Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address or if it has a non-zero code hash or account hash // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(_address) } return (codehash != 0x0 && codehash != ACCOUNT_HASH); } /** * @dev Performs a Solidity function call using a low level `call`. * * 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. */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: No contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: No contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /* * @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: Apache-2.0 pragma solidity 0.7.6; abstract contract ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface(bytes4 _interfaceID) public pure virtual returns (bool) { return _interfaceID == this.supportsInterface.selector; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @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: Apache-2.0 pragma solidity 0.7.6; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath#mul: OVERFLOW'); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'SafeMath#div: DIVISION_BY_ZERO'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'SafeMath#sub: UNDERFLOW'); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath#add: OVERFLOW'); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'SafeMath#mod: DIVISION_BY_ZERO'); return a % b; } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; import '../../0xerc1155/interfaces/IERC20.sol'; import '../../0xerc1155/tokens/ERC1155/ERC1155Holder.sol'; import '../token/interfaces/IWOWSCryptofolio.sol'; import '../token/interfaces/IWOWSERC1155.sol'; import '../utils/AddressBook.sol'; import '../utils/interfaces/IAddressRegistry.sol'; import '../utils/TokenIds.sol'; import './interfaces/ICFolioItemCallback.sol'; import './WOWSMinterPauser.sol'; abstract contract OpenSeaProxyRegistry { mapping(address => address) public proxies; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-1155[ERC1155] * Multi Token Standard, including the Metadata URI extension. * * This contract is an extension of the minter preset. It accepts the address * of the contract minting the token via the ERC-1155 data parameter. When * the token is transferred or burned, the minter is notified. * * Token ID allocation: * * - 32Bit Stock Cards * - 32Bit Custom Cards * - Remaining CFolio NFTs */ contract TradeFloor is WOWSMinterPauser, ERC1155Holder { using TokenIds for uint256; ////////////////////////////////////////////////////////////////////////////// // Roles ////////////////////////////////////////////////////////////////////////////// // Only OPERATORS can approve when trading is restricted bytes32 public constant OPERATOR_ROLE = 'OPERATOR_ROLE'; ////////////////////////////////////////////////////////////////////////////// // Constants ////////////////////////////////////////////////////////////////////////////// // solhint-disable-next-line const-name-snakecase string public constant name = 'Wolves of Wall Street - C-Folio NFTs'; // solhint-disable-next-line const-name-snakecase string public constant symbol = 'WOWSCFNFT'; ////////////////////////////////////////////////////////////////////////////// // Modifier ////////////////////////////////////////////////////////////////////////////// modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Only admin'); _; } modifier notNull(address adr) { require(adr != address(0), 'Null address'); _; } ////////////////////////////////////////////////////////////////////////////// // State ////////////////////////////////////////////////////////////////////////////// /** * @dev Per token information, used to cap NFT's and to allow querying a list * of NFT's owned by an address */ struct ListKey { uint256 index; } // Per token information struct TokenInfo { bool minted; // Make sure we only mint 1 ListKey listKey; // Next tokenId in the owner linkedList } // slither-disable-next-line uninitialized-state mapping(uint256 => TokenInfo) private _tokenInfos; // Mapping owner -> first owned token // // Note that we work 1 based here because of initialization // e.g. firstId == 1 links to tokenId 0; struct Owned { uint256 count; ListKey listKey; // First tokenId in linked list } // slither-disable-next-line uninitialized-state mapping(address => Owned) private _owned; // Our SFT contract, needed to check for locked transfers IWOWSERC1155 private immutable _sftHolder; // Migration!! This is the old sft contract IWOWSERC1155 private immutable _sftHolderOld; // Restrict approvals to OPERATOR_ROLE members bool private _tradingRestricted = false; ////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////// /** * @dev Emitted when the state of restriction has updated * * @param tradingRestricted True if trading has been restricted, false otherwise */ event RestrictionUpdated(bool tradingRestricted); ////////////////////////////////////////////////////////////////////////////// // OpenSea compatibility ////////////////////////////////////////////////////////////////////////////// // OpenSea per-account proxy registry. Used to whitelist Approvals and save // GAS. OpenSeaProxyRegistry private immutable _openSeaProxyRegistry; address private immutable _deployer; // OpenSea events event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); ////////////////////////////////////////////////////////////////////////////// // Rarible compatibility ////////////////////////////////////////////////////////////////////////////// /* * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * * => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584 */ bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584; uint256 private _fee; address private _feeRecipient; // Rarible events // solhint-disable-next-line event-name-camelcase event CreateERC1155_v1(address indexed creator, string name, string symbol); event SecondarySaleFees( uint256 tokenId, address payable[] recipients, uint256[] bps ); ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Construct the contract * * @param addressRegistry Registry containing our system addresses * * Note: Pause operation in this context. Only calls from Proxy allowed. */ constructor( IAddressRegistry addressRegistry, OpenSeaProxyRegistry openSeaProxyRegistry, IWOWSERC1155 sftHolderOld ) { // Initialize {AccessControl} _setupRole( DEFAULT_ADMIN_ROLE, _getAddressRegistryAddress(addressRegistry, AddressBook.ADMIN_ACCOUNT) ); // Immutable, visible for all contexts _sftHolder = IWOWSERC1155( _getAddressRegistryAddress(addressRegistry, AddressBook.SFT_HOLDER_PROXY) ); _sftHolderOld = sftHolderOld; // Immutable, visible for all contexts _openSeaProxyRegistry = openSeaProxyRegistry; // Immutable, visible for all contexts _deployer = _getAddressRegistryAddress( addressRegistry, AddressBook.DEPLOYER ); // Pause this instance _pause(true); } /** * @dev One time contract initializer * * @param tokenUriPrefix The ERC-1155 metadata URI Prefix * @param contractUri The contract metadata URI */ function initialize( IAddressRegistry addressRegistry, string memory tokenUriPrefix, string memory contractUri ) public { // Validate state require(_feeRecipient == address(0), 'already initialized'); // Initialize {AccessControl} address admin = _getAddressRegistryAddress( addressRegistry, AddressBook.ADMIN_ACCOUNT ); _setupRole(DEFAULT_ADMIN_ROLE, admin); // Initialize {ERC1155Metadata} _setBaseMetadataURI(tokenUriPrefix); _setContractMetadataURI(contractUri); _feeRecipient = _getAddressRegistryAddress( addressRegistry, AddressBook.REWARD_HANDLER ); _fee = 1000; // 10% // This event initializes Rarible storefront emit CreateERC1155_v1(_deployer, name, symbol); // OpenSea enable storefront editing emit OwnershipTransferred(address(0), _deployer); } ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Return list of tokenIds owned by `account` */ function getTokenIds(address account) external view returns (uint256[] memory) { Owned storage list = _owned[account]; uint256[] memory result = new uint256[](list.count); ListKey storage key = list.listKey; for (uint256 i = 0; i < list.count; ++i) { result[i] = key.index; key = _tokenInfos[key.index].listKey; } return result; } ////////////////////////////////////////////////////////////////////////////// // Implementation of {IERC1155} via {WOWSMinterPauser} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, uint256 amount, bytes calldata data ) public override notNull(from) notNull(to) { // Call parent super.safeTransferFrom(from, to, tokenId, amount, data); uint256[] memory tokenIds = new uint256[](1); uint256[] memory amounts = new uint256[](1); tokenIds[0] = tokenId; amounts[0] = amount; _onTransfer(from, to, tokenIds, amounts); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) public override notNull(from) notNull(to) { // Validate parameters require(tokenIds.length == amounts.length, "Lengths don't match"); // Call parent super.safeBatchTransferFrom(from, to, tokenIds, amounts, data); _onTransfer(from, to, tokenIds, amounts); } /** * @dev See {IERC1155-setApprovalForAll}. * * Override setApprovalForAll to be able to restrict to known operators. */ function setApprovalForAll(address operator, bool approved) public virtual override { // Validate access require( !_tradingRestricted || hasRole(OPERATOR_ROLE, operator), 'forbidden' ); // Call ancestor super.setApprovalForAll(operator, approved); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { if (!_tradingRestricted && address(_openSeaProxyRegistry) != address(0)) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry( _openSeaProxyRegistry ); if (proxyRegistry.proxies(account) == operator) { return true; } } // Call ancestor return super.isApprovedForAll(account, operator); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {IERC1155MetadataURI} via {WOWSMinterPauser} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IERC1155MetadataURI-uri}. * * Revert for unminted SFT NFTs. */ function uri(uint256 tokenId) public view override returns (string memory) { // Validate state require(_tokenInfos[tokenId].minted, 'Not minted'); // Load state return _uri('', tokenId, 0); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {WOWSMinterPauser} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC1155MintBurn-_burn}. */ function burn( address account, uint256 tokenId, uint256 amount ) public override notNull(account) { // Call ancestor super.burn(account, tokenId, amount); // Perform internal handling uint256[] memory tokenIds = new uint256[](1); uint256[] memory amounts = new uint256[](1); tokenIds[0] = tokenId; amounts[0] = amount; _onTransfer(account, address(0), tokenIds, amounts); } /** * @dev See {ERC1155MintBurn-_batchBurn}. */ function burnBatch( address account, uint256[] calldata tokenIds, uint256[] calldata amounts ) public virtual override notNull(account) { // Validate parameters require(tokenIds.length == amounts.length, "Lengths don't match"); // Call ancestor super.burnBatch(account, tokenIds, amounts); // Perform internal handling _onTransfer(account, address(0), tokenIds, amounts); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {IERC1155TokenReceiver} via {ERC1155Holder} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IERC1155TokenReceiver-onERC1155Received} */ function onERC1155Received( address operator, address from, uint256 tokenId, uint256 amount, bytes calldata data ) public override returns (bytes4) { // Handle tokens uint256[] memory tokenIds = new uint256[](1); tokenIds[0] = tokenId; uint256[] memory amounts = new uint256[](1); amounts[0] = amount; _onTokensReceived(from, tokenIds, amounts, data); // Call ancestor return super.onERC1155Received(operator, from, tokenId, amount, data); } /** * @dev See {IERC1155TokenReceiver-onERC1155BatchReceived} */ function onERC1155BatchReceived( address operator, address from, uint256[] memory tokenIds, uint256[] memory amounts, bytes calldata data ) public override returns (bytes4) { // Handle tokens _onTokensReceived(from, tokenIds, amounts, data); // Call ancestor return super.onERC1155BatchReceived(operator, from, tokenIds, amounts, data); } ////////////////////////////////////////////////////////////////////////////// // Administrative functions ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC1155Metadata-setBaseMetadataURI}. */ function setBaseMetadataURI(string memory baseMetadataURI) external onlyAdmin { // Set state _setBaseMetadataURI(baseMetadataURI); } /** * @dev Set contract metadata URI */ function setContractMetadataURI(string memory newContractUri) public onlyAdmin { _setContractMetadataURI(newContractUri); } /** * @dev Register interfaces */ function supportsInterface(bytes4 _interfaceID) public pure virtual override(WOWSMinterPauser, ERC1155Holder) returns (bool) { // Register rarible fee interface if (_interfaceID == _INTERFACE_ID_FEES) { return true; } return super.supportsInterface(_interfaceID); } /** * @dev Withdraw tokenAddress ERC20token to destination * * A future improvement would be to swap the token into WOWS. * * @param tokenAddress the address of the token to transfer. Cannot be * rewardToken. */ function collectGarbage(address tokenAddress) external onlyAdmin { // Transfer token to msg.sender uint256 amountToken = IERC20(tokenAddress).balanceOf(address(this)); if (amountToken > 0) IERC20(tokenAddress).transfer(_msgSender(), amountToken); } /** * @dev Restrict trading to OPERATOR_ROLE (see setApprovalForAll) */ function restrictTrading(bool restrict) external onlyAdmin { // Update state _tradingRestricted = restrict; // Dispatch event emit RestrictionUpdated(restrict); } /** * @dev Self destruct implementation contract */ function destructContract(address payable newContract) external onlyAdmin { // slither-disable-next-line suicidal selfdestruct(newContract); } ////////////////////////////////////////////////////////////////////////////// // OpenSea compatibility ////////////////////////////////////////////////////////////////////////////// function isOwner() external view returns (bool) { return _msgSender() == owner(); } function owner() public view returns (address) { return _deployer; } ////////////////////////////////////////////////////////////////////////////// // Rarible fees and events ////////////////////////////////////////////////////////////////////////////// function setFee(uint256 fee) external onlyAdmin { // Update state _fee = fee; } function setFeeRecipient(address feeRecipient) external onlyAdmin { // Update state _feeRecipient = feeRecipient; } function getFeeRecipients(uint256) public view returns (address payable[] memory) { // Return value address payable[] memory recipients = new address payable[](1); // Load state recipients[0] = payable(_feeRecipient); return recipients; } function getFeeBps(uint256) public view returns (uint256[] memory) { // Return value uint256[] memory bps = new uint256[](1); // Load state bps[0] = _fee; return bps; } function logURI(uint256 tokenId) external { emit URI(uri(tokenId), tokenId); } ////////////////////////////////////////////////////////////////////////////// // Internal details ////////////////////////////////////////////////////////////////////////////// function _onTransfer( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts ) private { // Count SFT tokenIds uint256 length = tokenIds.length; uint256 validLength = 0; // Relink owner for (uint256 i = 0; i < length; ++i) { if (amounts[i] == 1) { _relinkOwner(from, to, tokenIds[i], uint256(-1)); ++validLength; } // CryptoFolios send 0 amount!! else require(amounts[i] == 0, 'TF: Invalid amount'); } // On Burn we need to transfer SFT ownership back if (validLength > 0 && to == address(0)) { uint256[] memory sftTokenIds = new uint256[](validLength); uint256[] memory sftAmounts = new uint256[](validLength); validLength = 0; for (uint256 i = 0; i < length; ++i) { if (amounts[i] == 1) { uint256 tokenId = tokenIds[i]; sftTokenIds[validLength] = tokenId.toSftTokenId(); sftAmounts[validLength++] = 1; } } IWOWSERC1155 sftHolder = _sftHolder; // Migration!!! Remove if all TF's are on new contract if ( address(_sftHolderOld) != address(0) && _sftHolderOld.balanceOf(address(this), sftTokenIds[0]) == 1 ) sftHolder = _sftHolderOld; sftHolder.safeBatchTransferFrom( address(this), _msgSender(), sftTokenIds, sftAmounts, '' ); } } /** * @dev SFT token arrived, provide an NFT */ function _onTokensReceived( address from, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) private { // We only support tokens from our SFT Holder contract require(_msgSender() == address(_sftHolder), 'TF: Invalid sender'); // Validate parameters require(tokenIds.length == amounts.length, 'TF: Lengths mismatch'); // To save gas we allow minting directly into a given recipient address sftRecipient; if (data.length == 20) { sftRecipient = _getAddress(data); require(sftRecipient != address(0), 'TF: invalid recipient'); } else sftRecipient = from; // Update state uint256[] memory mintedTokenIds = new uint256[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; ++i) { require(amounts[i] == 1, 'Amount != 1 not allowed'); uint256 mintedTokenId = _hashedTokenId(tokenIds[i]); mintedTokenIds[i] = mintedTokenId; // OpenSea only listens to TransferSingle event on mint _mintAndEmit(sftRecipient, mintedTokenId); } _onTransfer(address(0), sftRecipient, mintedTokenIds, amounts); } /** * @dev Ownership change -> update linked list owner -> tokenId * * If tokenIdNew is != uint256(-1) this function executes an * ownership transfer of "from" from tokenId to tokenIdNew * In this case "to" must be set to 0. */ function _relinkOwner( address from, address to, uint256 tokenId, uint256 tokenIdNew ) internal { // Load state TokenInfo storage tokenInfo = _tokenInfos[tokenId]; // Remove tokenId from List if (from != address(0)) { // Load state Owned storage fromList = _owned[from]; // Validate state require(fromList.count > 0, 'Count mismatch'); ListKey storage key = fromList.listKey; uint256 count = fromList.count; // Search the token which links to tokenId for (; count > 0 && key.index != tokenId; --count) key = _tokenInfos[key.index].listKey; require(key.index == tokenId, 'Key mismatch'); if (tokenIdNew == uint256(-1)) { // Unlink prev -> tokenId key.index = tokenInfo.listKey.index; // Decrement count fromList.count--; } else { // replace tokenId -> tokenIdNew key.index = tokenIdNew; TokenInfo storage tokenInfoNew = _tokenInfos[tokenIdNew]; require(!tokenInfoNew.minted, 'Must not be minted'); tokenInfoNew.listKey.index = tokenInfo.listKey.index; tokenInfoNew.minted = true; } // Unlink tokenId -> next tokenInfo.listKey.index = 0; require(tokenInfo.minted, 'Must be minted'); tokenInfo.minted = false; } // Update state if (to != address(0)) { Owned storage toList = _owned[to]; tokenInfo.listKey.index = toList.listKey.index; require(!tokenInfo.minted, 'Must not be minted'); tokenInfo.minted = true; toList.listKey.index = tokenId; toList.count++; } } /** * @dev Get the address from the user data parameter * * @param data Per ERC-1155, the data parameter is additional data with no * specified format, and is sent unaltered in the call to * {IERC1155Receiver-onERC1155Received} on the receiver of the minted token. */ function _getAddress(bytes memory data) public pure returns (address addr) { // solhint-disable-next-line no-inline-assembly assembly { addr := mload(add(data, 20)) } } /** * @dev Save contract size by wrappng external call into an internal */ function _getAddressRegistryAddress(IAddressRegistry reg, bytes32 data) private view returns (address) { return reg.getRegistryEntry(data); } /** * @dev Save contract size by wrappng external call into an internal */ function _addressToTokenId(address tokenAddress) private view returns (uint256) { return _sftHolder.addressToTokenId(tokenAddress); } /** * @dev internal mint + event emiting */ function _mintAndEmit(address recipient, uint256 tokenId) private { _mint(recipient, tokenId, 1, ''); // Rarible needs to be informed about fees emit SecondarySaleFees(tokenId, getFeeRecipients(0), getFeeBps(0)); } /** * @dev Calculate a 128-bit hash for making tokenIds unique to underlying asset * * @param sftTokenId The tokenId from SFT contract from that we use the first 128 bit * TokenIds in SFT contract are limited to max 128 Bit in WowsSftMinter contract. */ function _hashedTokenId(uint256 sftTokenId) private view returns (uint256) { bytes memory hashData; uint256[] memory tokenIds; uint256 tokenIdsLength; if (sftTokenId.isBaseCard()) { // It's a base card, calculate hash using all cfolioItems address cfolio = _sftHolder.tokenIdToAddress(sftTokenId); require(cfolio != address(0), 'TF: src token invalid'); tokenIds = _sftHolder.getTokenIds(cfolio); tokenIdsLength = tokenIds.length; hashData = abi.encodePacked(address(this), sftTokenId); } else { // It's a cfolioItem itself, only calculate underlying value tokenIds = new uint256[](1); tokenIds[0] = sftTokenId; tokenIdsLength = 1; } // Run through all cfolioItems and let their single CFolioItemHandler // append hashable data for (uint256 i = 0; i < tokenIdsLength; ++i) { address cfolio = _sftHolder.tokenIdToAddress(tokenIds[i].toSftTokenId()); require(cfolio != address(0), 'TF: item token invalid'); address handler = IWOWSCryptofolio(cfolio).handler(); require(handler != address(0), 'TF: item handler invalid'); hashData = ICFolioItemCallback(handler).appendHash(cfolio, hashData); } uint256 hashNum = uint256(keccak256(hashData)); return (hashNum ^ (hashNum << 128)).maskHash() | sftTokenId; } } /* * Copyright (C) 2020-2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 AND MIT * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; import '../../0xerc1155/access/AccessControl.sol'; import '../../0xerc1155/tokens/ERC1155/ERC1155Metadata.sol'; import '../../0xerc1155/tokens/ERC1155/ERC1155MintBurn.sol'; /** * @dev Partial implementation of https://eips.ethereum.org/EIPS/eip-1155[ERC1155] * Multi Token Standard */ contract WOWSMinterPauser is Context, AccessControl, ERC1155MintBurn, ERC1155Metadata { ////////////////////////////////////////////////////////////////////////////// // Roles ////////////////////////////////////////////////////////////////////////////// // Role to mint new tokens bytes32 public constant MINTER_ROLE = 'MINTER_ROLE'; ////////////////////////////////////////////////////////////////////////////// // State ////////////////////////////////////////////////////////////////////////////// // Pause bool private _pauseActive; ////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////// // Event triggered when _pause state changed event Pause(bool active); ////////////////////////////////////////////////////////////////////////////// // Constructor ////////////////////////////////////////////////////////////////////////////// constructor() {} ////////////////////////////////////////////////////////////////////////////// // Pausing interface ////////////////////////////////////////////////////////////////////////////// /** * @dev Pauses all token transfers. * * Requirements: * * - The caller must have the `DEFAULT_ADMIN_ROLE`. */ function pause(bool active) public { // Validate access require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'Only admin'); if (_pauseActive != active) { // Update state _pauseActive = active; emit Pause(active); } } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _pauseActive; } function _pause(bool active) internal { _pauseActive = active; } ////////////////////////////////////////////////////////////////////////////// // Minting interface ////////////////////////////////////////////////////////////////////////////// /** * @dev Creates `amount` new tokens for `to`, of token type `tokenId`. * * See {ERC1155-_mint}. * * Requirements: * * - The caller must have the `MINTER_ROLE`. */ function mint( address to, uint256 tokenId, uint256 amount, bytes memory data ) public virtual { // Validate access require(hasRole(MINTER_ROLE, _msgSender()), 'Only minter'); // Validate parameters require(to != address(0), "Can't mint to zero address"); // Update state _mint(to, tokenId, amount, data); } /** * @dev Batched variant of {mint}. */ function mintBatch( address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) public virtual { // Validate access require(hasRole(MINTER_ROLE, _msgSender()), 'Only minter'); // Validate parameters require(to != address(0), "Can't mint to zero address"); require(tokenIds.length == amounts.length, "Lengths don't match"); // Update state _batchMint(to, tokenIds, amounts, data); } ////////////////////////////////////////////////////////////////////////////// // Burning interface ////////////////////////////////////////////////////////////////////////////// function burn( address account, uint256 id, uint256 value ) public virtual { // Validate access require( account == _msgSender() || isApprovedForAll(account, _msgSender()), 'Caller is not owner nor approved' ); // Update state _burn(account, id, value); } function burnBatch( address account, uint256[] calldata ids, uint256[] calldata values ) public virtual { // Validate access require( account == _msgSender() || isApprovedForAll(account, _msgSender()), 'Caller is not owner nor approved' ); // Update state _batchBurn(account, ids, values); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ERC1155} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC1155-_beforeTokenTransfer}. * * This function is necessary due to diamond inheritance. */ function _beforeTokenTransfer( address operator, address from, address to, uint256 tokenId, uint256 amount, bytes memory data ) internal virtual override { // Validate state require(!_pauseActive, 'Transfer operation paused!'); // Call ancestor super._beforeTokenTransfer(operator, from, to, tokenId, amount, data); } /** * @dev See {ERC1155-_beforeBatchTokenTransfer}. * * This function is necessary due to diamond inheritance. */ function _beforeBatchTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual override { // Valiate state require(!_pauseActive, 'Transfer operation paused!'); // Call ancestor super._beforeBatchTokenTransfer( operator, from, to, tokenIds, amounts, data ); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {ERC165} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {ERC165-supportsInterface} */ function supportsInterface(bytes4 _interfaceID) public pure virtual override(ERC1155, ERC1155Metadata) returns (bool) { return super.supportsInterface(_interfaceID); } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @dev Interface to receive callbacks when minted tokens are burnt */ interface ICFolioItemCallback { /** * @dev Called when a TradeFloor CFolioItem is transfered * * In case of mint `from` is address(0). * In case of burn `to` is address(0). * * cfolioHandlers are passed to let each cfolioHandler filter for its own * token. This eliminates the need for creating separate lists. * * @param from The account sending the token * @param to The account receiving the token * @param tokenIds The ERC-1155 token IDs * @param cfolioHandlers cFolioItem handlers */ function onCFolioItemsTransferedFrom( address from, address to, uint256[] calldata tokenIds, address[] calldata cfolioHandlers ) external; /** * @dev Append data we use later for hashing * * @param cfolioItem The token ID of the c-folio item * @param current The current data being hashes * * @return The current data, with internal data appended */ function appendHash(address cfolioItem, bytes calldata current) external view returns (bytes memory); } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Cryptofolio interface */ interface IWOWSCryptofolio { ////////////////////////////////////////////////////////////////////////////// // Getter ////////////////////////////////////////////////////////////////////////////// /** * @dev Return the handler (CFIH) of the underlying NFT */ function handler() external view returns (address); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the handler of the underlying NFT * * This function is called during I-NFT setup * * @param newHandler The new handler of the underlying NFT, */ function setHandler(address newHandler) external; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Sft holder contract */ interface IWOWSERC1155 { ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Get the token ID of a given address * * A cross check is required because token ID 0 is valid. * * @param tokenAddress The address to convert to a token ID * * @return The token ID on success, or uint256(-1) if `tokenAddress` does not * belong to a token ID */ function addressToTokenId(address tokenAddress) external view returns (uint256); /** * @dev Get the address for a given token ID * * @param tokenId The token ID to convert * * @return The address, or address(0) in case the token ID does not belong * to an NFT */ function tokenIdToAddress(uint256 tokenId) external view returns (address); /** * @dev Return the level and the mint timestamp of tokenId * * @param tokenId The tokenId to query * * @return mintTimestamp The timestamp token was minted * @return level The level token belongs to */ function getTokenData(uint256 tokenId) external view returns (uint64 mintTimestamp, uint8 level); /** * @dev Return all tokenIds owned by account */ function getTokenIds(address account) external view returns (uint256[] memory); /** * @dev Returns the cFolioItemType of a given cFolioItem tokenId */ function getCFolioItemType(uint256 tokenId) external view returns (uint256); /** * @notice Get the balance of an account's Tokens * @param owner The address of the token holder * @param tokenId ID of the Token * @return The _owner's balance of the token type requested */ function balanceOf(address owner, uint256 tokenId) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param owners The addresses of the token holders * @param tokenIds ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch( address[] calldata owners, uint256[] calldata tokenIds ) external view returns (uint256[] memory); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @notice Mints tokenIds into 'to' account * @dev Emits SftTokenTransfer Event * * Throws if sender has no MINTER_ROLE * 'data' holds the CFolioItemHandler if CFI's are minted */ function mintBatch( address to, uint256[] calldata tokenIds, bytes calldata data ) external; /** * @notice Burns tokenIds owned by 'account' * @dev Emits SftTokenTransfer Event * * Burns all owned CFolioItems * Throws if CFolioItems have assets */ function burnBatch(address account, uint256[] calldata tokenIds) external; /** * @notice Transfers amount of an id from the from address to the 'to' address specified * @dev Emits SftTokenTransfer Event * Throws if 'to' is the zero address * Throws if 'from' is not the current owner * If 'to' is a smart contract, ERC1155TokenReceiver interface will checked * @param from Source address * @param to Target address * @param tokenId ID of the token type * @param amount Transfered amount * @param data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address from, address to, uint256 tokenId, uint256 amount, bytes calldata data ) external; /** * @dev Batch version of {safeTransferFrom} */ function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds, uint256[] calldata amounts, bytes calldata data ) external; /** * @dev Each custom card has its own level. Level will be used when * calculating rewards and raiding power. * * @param tokenId The ID of the token whose level is being set * @param cardLevel The new level of the specified token */ function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external; /** * @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used * sftHolder tokenId expected (without hash) */ function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external; /** * @dev Sets external NFT for display tokenId * By default NFT is rendered using our internal metadata * * Throws if not called from MINTER role */ function setExternalNft( uint256 tokenId, address externalCollection, uint256 externalTokenId ) external; /** * @dev Deletes external NFT settings * * Throws if not called from MINTER role */ function deleteExternalNft(uint256 tokenId) external; } /* * Copyright (C) 2020-2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; library AddressBook { bytes32 public constant DEPLOYER = 'DEPLOYER'; bytes32 public constant TEAM_WALLET = 'TEAM_WALLET'; bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET'; bytes32 public constant ADMIN_ACCOUNT = 'ADMIN_ACCOUNT'; bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02'; bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM'; bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN'; bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR'; bytes32 public constant WOWS_BOOSTER_PROXY = 'WOWS_BOOSTER_PROXY'; bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER'; bytes32 public constant SFT_MINTER_PROXY = 'SFT_MINTER_PROXY'; bytes32 public constant SFT_HOLDER_PROXY = 'SFT_HOLDER_PROXY'; bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY'; bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY'; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See LICENSE.txt for more information. */ pragma solidity >=0.7.0 <0.8.0; library TokenIds { // 128 bit underlying hash uint256 public constant HASH_MASK = (1 << 128) - 1; function isBaseCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) < (1 << 64); } function isStockCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) < (1 << 32); } function isCustomCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) >= (1 << 32) && (tokenId & HASH_MASK) < (1 << 64); } function isCFolioCard(uint256 tokenId) internal pure returns (bool) { return (tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128); } function toSftTokenId(uint256 tokenId) internal pure returns (uint256) { return tokenId & HASH_MASK; } function maskHash(uint256 tokenId) internal pure returns (uint256) { return tokenId & ~HASH_MASK; } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; interface IAddressRegistry { /** * @dev Set an abitrary key / address pair into the registry */ function setRegistryEntry(bytes32 _key, address _location) external; /** * @dev Get a registry enty with by key, returns 0 address if not existing */ function getRegistryEntry(bytes32 _key) external view returns (address); }
Get the balance of an account's Tokens _owner The address of the token holder _id ID of the Token return The _owner's balance of the Token type requested/
function balanceOf(address _owner, uint256 _id) public view override returns (uint256) { return balances[_owner][_id]; }
389,828
./full_match/5/0xEf8F1fe8918eB5BB70853F2dF2cAC85626d6FB56/sources/project_/contracts/base/MetawinNFTMinter.sol
Get current price./
function price_current() external view virtual returns (uint256) { return _currentDutchAuctionPrice(); }
7,035,513
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface ICrvPriceOracle { function usdToCrv(uint256 amount) external view returns (uint256); function crvToUsd(uint256 amount) external view returns (uint256); } // SPDX-License-Identifier: MIT 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: MIT pragma solidity 0.6.10; import {SafeMath} from "SafeMath.sol"; import {ICrvPriceOracle} from "ICrvPriceOracle.sol"; import "AggregatorV3Interface.sol"; contract CrvPriceOracle is ICrvPriceOracle { AggregatorV3Interface internal crvPriceFeed; AggregatorV3Interface internal ethPriceFeed; using SafeMath for uint256; /** * Network: Mainnet * Aggregator: CRV/ETH * Address: 0x8a12Be339B0cD1829b91Adc01977caa5E9ac121e * Network: Mainnet * Aggregator: ETH/USD * Address: 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419 * Mainnet deployed: https://etherscan.io/address/0x23DE9562bf8020f5B92a2A04C59b39deABbB2315#readContract */ constructor() public { crvPriceFeed = AggregatorV3Interface(0x8a12Be339B0cD1829b91Adc01977caa5E9ac121e); ethPriceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * @dev return the lastest price for CRV/USD with 18 decimals places * @return CRV/USD price */ function getLatestPrice() public view returns (uint256) { (, int256 crvEthPrice, , , ) = crvPriceFeed.latestRoundData(); (, int256 ethPrice, , , ) = ethPriceFeed.latestRoundData(); uint256 crvPrice = safeUint(crvEthPrice).mul(safeUint(ethPrice)).div(1e8); return crvPrice; } /** * @dev converts from USD with 18 decimals to CRV with 18 decimals * @param amount Amount in USD * @return CRV value of USD input */ function usdToCrv(uint256 amount) external override view returns (uint256) { return amount.mul(1e18).div(getLatestPrice()); } /** * @dev converts from CRV with 18 decimals to USD with 18 decimals * @param amount Amount in CRV * @return USD value of CRV input */ function crvToUsd(uint256 amount) external override view returns (uint256) { return amount.mul(getLatestPrice()).div(1e18); } /** * @dev convert int256 to uint256 * @param value to convert to uint * @return the converted uint256 value */ function safeUint(int256 value) internal pure returns (uint256) { require(value >= 0, "CrvPriceChainLinkOracle: uint underflow"); return uint256(value); } }
converts from USD with 18 decimals to CRV with 18 decimals amount Amount in USD return CRV value of USD input/
function usdToCrv(uint256 amount) external override view returns (uint256) { return amount.mul(1e18).div(getLatestPrice()); }
6,938,397
pragma solidity ^0.4.24; import "../access/roles/MinterRole.sol"; import "../math/SafeMath.sol"; import "../access/roles/MintLimiterRole.sol"; /** * @title Mintable * * @dev Base contract which allows children to implement limit-based minting of tokens. * This contract inherits the MinterRole contract to use RBAC for administering accounts that can mint tokens. * This contract inherits the MintLimiterRole contract to use RBAC for administering accounts that limit the minters. */ contract Mintable is MinterRole, MintLimiterRole { using SafeMath for uint256; /** The amount of tokens each minter is allowed to mint. */ mapping(address => uint256) private _minterLimits; /** Mapping of unique mint identifiers to whether or not they've been used before. */ mapping(int256 => bool) private mintIds; /** Event emitted whenever a minter limit is updated. */ event MinterLimitUpdated(address indexed minter, uint256 limit); /** Event emitted whenever tokens are minted. */ event Mint(address indexed minter, address indexed to, uint256 value, int256 mintId); /** * @dev Gets the amount of tokens the given `minter` is limited to minting. * * @param minter The minter account whose limit is being queried * @return The amount of tokens allowed to be minted */ function mintLimitOf(address minter) external view returns (uint256) { return _minterLimits[minter]; } /** * @dev Extension of the MinterRole removeMinter function to additionally set minter limit to zero. * Callable by an account with the minterAdmin role. * * @param account The account address having access removed from the minter role */ function removeMinter(address account) external onlyMinterAdmin { _setLimit(account, 0); super._removeMinter(account); } /** * @dev Set the amount of tokens the given `minter` is allowed to mint. * Callable by an account with the mintLimiter role. * * @notice This function should only be called when setting the minter's limit to zero. * * @param minter The minter account whose limit is being set * @param value The amount to set the minter's limit to */ function setMintLimit(address minter, uint256 value) external onlyMintLimiter { require(super._isMinter(minter)); _setLimit(minter, value); } /** * @dev Increase the amount of tokens the given `minter` is allowed to mint. * Callable by an account with the mintLimiter role. * * @param minter The minter account whose limit is being increased * @param value The amount to increase the minter's limit by */ function increaseMintLimit(address minter, uint256 value) external onlyMintLimiter { require(super._isMinter(minter)); _setLimit(minter, _minterLimits[minter].add(value)); } /** * @dev Decrease the amount of tokens the given `_minter` is allowed to mint. * Callable by an account with the mintLimiter role. * * @param minter The minter account whose limit is being decreased * @param value The amount to decrease the minter's limit by */ function decreaseMintLimit(address minter, uint256 value) external onlyMintLimiter { require(super._isMinter(minter)); _setLimit(minter, _minterLimits[minter].sub(value)); } /** * @dev Internal function that sets the limit of a minter in the private mapping of `_minterLimits`. * Emits a MinterLimitUpdated event. * * @param minter The minter account whose limit is being updated * @param limit The amount of tokens to set the minter's limit to */ function _setLimit(address minter, uint256 limit) internal { _minterLimits[minter] = limit; emit MinterLimitUpdated(minter, limit); } /** * @dev Internal function that should be called whenever new tokens are being minted as it encapsulates limit logic. * Emits a Mint event. * * @param minter The account that is minting the tokens * @param to The account the tokens are being minted to * @param value The amount of tokens being minted * @param mintId A unique identifier for the mint transaction */ function _mint(address minter, address to, uint256 value, int256 mintId) internal { // Assert that the to address is not null account and that the value is greater than zero require(to != address(0)); require(value > 0); // Assert that the mintId has not been used before require(!mintIds[mintId]); // Decrease the minter's mint limit by the minted value _minterLimits[minter] = _minterLimits[minter].sub(value); // Add the mintId to the mapping of used mintIds mintIds[mintId] = true; // Emit the mint event emit Mint(minter, to, value, mintId); } }
The amount of tokens each minter is allowed to mint. / Mapping of unique mint identifiers to whether or not they've been used before. / Event emitted whenever a minter limit is updated. / Event emitted whenever tokens are minted. / Gets the amount of tokens the given `minter` is limited to minting. minter The minter account whose limit is being queried return The amount of tokens allowed to be minted/
function mintLimitOf(address minter) external view returns (uint256) { return _minterLimits[minter]; }
5,388,354
pragma solidity ^0.4.22; /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title MultiOwnable * @dev The MultiOwnable contract has an owner address[], and provides basic authorization control */ contract MultiOwnable is Ownable { struct Types { mapping (address => bool) access; } mapping (uint => Types) private multiOwnersTypes; event AddOwner(uint _type, address addr); event AddOwner(uint[] types, address addr); event RemoveOwner(uint _type, address addr); modifier onlyMultiOwnersType(uint _type) { require(multiOwnersTypes[_type].access[msg.sender] || msg.sender == owner, "403"); _; } function onlyMultiOwnerType(uint _type, address _sender) public view returns(bool) { if (multiOwnersTypes[_type].access[_sender] || _sender == owner) { return true; } return false; } function addMultiOwnerType(uint _type, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[_type].access[_owner] = true; emit AddOwner(_type, _owner); return true; } function addMultiOwnerTypes(uint[] types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); require(types.length > 0); for (uint i = 0; i < types.length; i++) { multiOwnersTypes[types[i]].access[_owner] = true; } emit AddOwner(types, _owner); return true; } function removeMultiOwnerType(uint types, address _owner) public onlyOwner returns(bool) { require(_owner != address(0)); multiOwnersTypes[types].access[_owner] = false; emit RemoveOwner(types, _owner); return true; } } /** * @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; } } contract IBonus { function getCurrentDayBonus(uint startSaleDate, bool saleState) public view returns(uint); function _currentDay(uint startSaleDate, bool saleState) public view returns(uint); function getBonusData() public view returns(string); function getPreSaleBonusPercent() public view returns(uint); function getMinReachUsdPayInCents() public view returns(uint); } contract ICurrency { function getUsdAbsRaisedInCents() external view returns(uint); function getCoinRaisedBonusInWei() external view returns(uint); function getCoinRaisedInWei() public view returns(uint); function getUsdFromETH(uint ethWei) public view returns(uint); function getTokenFromETH(uint ethWei) public view returns(uint); function getCurrencyRate(string _ticker) public view returns(uint); function addPay(string _ticker, uint value, uint usdAmount, uint coinRaised, uint coinRaisedBonus) public returns(bool); function checkTickerExists(string ticker) public view returns(bool); function getUsdFromCurrency(string ticker, uint value) public view returns(uint); function getUsdFromCurrency(string ticker, uint value, uint usd) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value) public view returns(uint); function getUsdFromCurrency(bytes32 ticker, uint value, uint usd) public view returns(uint); function getTokenWeiFromUSD(uint usdCents) public view returns(uint); function editPay(bytes32 ticker, uint currencyValue, uint currencyUsdRaised, uint _usdAbsRaisedInCents, uint _coinRaisedInWei, uint _coinRaisedBonusInWei) public returns(bool); function getCurrencyList(string ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getCurrencyList(bytes32 ticker) public view returns(bool active, uint usd, uint devision, uint raised, uint usdRaised, uint usdRaisedExchangeRate, uint counter, uint lastUpdate); function getTotalUsdRaisedInCents() public view returns(uint); function getAllCurrencyTicker() public view returns(string); function getCoinUSDRate() public view returns(uint); function addPreSaleBonus(uint bonusToken) public returns(bool); function editPreSaleBonus(uint beforeBonus, uint afterBonus) public returns(bool); } contract IStorage { function processPreSaleBonus(uint minTotalUsdAmountInCents, uint bonusPercent, uint _start, uint _limit) external returns(uint); function checkNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents) external view returns(bool); function getCountNeedProcessPreSaleBonus(uint minTotalUsdAmountInCents, uint start, uint limit) external view returns(uint); function reCountUserPreSaleBonus(uint uId, uint minTotalUsdAmountInCents, uint bonusPercent, uint maxPayTime) external returns(uint, uint); function getContributorIndexes(uint index) external view returns(uint); function checkNeedSendSHPC(bool proc) external view returns(bool); function getCountNeedSendSHPC(uint start, uint limit) external view returns(uint); function checkETHRefund(bool proc) external view returns(bool); function getCountETHRefund(uint start, uint limit) external view returns(uint); function addPayment(address _addr, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function addPayment(uint uId, string pType, uint _value, uint usdAmount, uint currencyUSD, uint tokenWithoutBonus, uint tokenBonus, uint bonusPercent, uint payId) public returns(bool); function checkUserIdExists(uint uId) public view returns(bool); function getContributorAddressById(uint uId) public view returns(address); function editPaymentByUserId(uint uId, uint payId, uint _payValue, uint _usdAmount, uint _currencyUSD, uint _totalToken, uint _tokenWithoutBonus, uint _tokenBonus, uint _bonusPercent) public returns(bool); function getUserPaymentById(uint uId, uint payId) public view returns(uint time, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus, uint tokenWithoutBonus, uint usdAbsRaisedInCents, bool refund); function checkWalletExists(address addr) public view returns(bool result); function checkReceivedCoins(address addr) public view returns(bool); function getContributorId(address addr) public view returns(uint); function getTotalCoin(address addr) public view returns(uint); function setReceivedCoin(uint uId) public returns(bool); function checkPreSaleReceivedBonus(address addr) public view returns(bool); function checkRefund(address addr) public view returns(bool); function setRefund(uint uId) public returns(bool); function getEthPaymentContributor(address addr) public view returns(uint); function refundPaymentByUserId(uint uId, uint payId) public returns(bool); function changeSupportChangeMainWallet(bool support) public returns(bool); } /** * @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); } /** * @title ShipCoin Crowdsale */ contract ShipCoinCrowdsale is MultiOwnable { using SafeMath for uint256; ERC20Basic public coinContract; IStorage public storageContract; ICurrency public currencyContract; IBonus public bonusContract; enum SaleState {NEW, PRESALE, CALCPSBONUS, SALE, END, REFUND} uint256 private constant ONE_DAY = 86400; SaleState public state; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } // minimum goal USD uint public softCapUSD = 500000000; // 5,000,000$ in cents // maximum goal USD uint public hardCapUSD = 6200000000; // 62,000,000$ in cents // maximum available SHPC with a bonus uint public maxDistributeCoin = 600000000 * 1 ether; //600,000,000 shpc (incl. bonus) // minimal accept payment uint public minimalContributionUSD = 100000; // 1000$ in cents // start and end timestamps where investments are allowed in PreSale uint public startPreSaleDate; uint public endPreSaleDate; uint public unfreezeRefundPreSale; uint public unfreezeRefundAll; // start and end timestamps where investments are allowed in sale uint public startSaleDate; uint public endSaleDate; bool public softCapAchieved = false; address public multiSig1; address public multiSig2; bool public multiSigReceivedSoftCap = false; /* Events */ event ChangeState(uint blockNumber, SaleState state); event ChangeMinContribUSD(uint oldAmount, uint newAmount); event ChangeStorageContract(address oldAddress, address newAddress); event ChangeCurrencyContract(address oldAddress, address newAddress); event ChangeCoinContract(address oldAddress, address newAddress); event ChangeBonusContract(address oldAddress, address newAddress); event AddPay(address contributor); event EditPay(address contributor); event SoftCapAchieved(uint amount); event ManualChangeStartPreSaleDate(uint oldDate, uint newDate); event ManualChangeEndPreSaleDate(uint oldDate, uint newDate); event ManualChangeStartSaleDate(uint oldDate, uint newDate); event ManualEndSaleDate(uint oldDate, uint newDate); event SendSHPCtoContributor(address contributor); event SoftCapChanged(); event Refund(address contributor); event RefundPay(address contributor); struct PaymentInfo { bytes32 pType; uint currencyUSD; uint bonusPercent; uint payValue; uint totalToken; uint tokenBonus; uint usdAbsRaisedInCents; bool refund; } struct CurrencyInfo { uint value; uint usdRaised; uint usdAbsRaisedInCents; uint coinRaisedInWei; uint coinRaisedBonusInWei; } struct EditPaymentInfo { uint usdAmount; uint currencyUSD; uint bonusPercent; uint totalToken; uint tokenWithoutBonus; uint tokenBonus; CurrencyInfo currency; } function () external whenNotPaused payable { buyTokens(msg.sender); } /** * @dev Run after deploy. Initialize initial variables * @param _coinAddress address coinContract * @param _storageContract address storageContract * @param _currencyContract address currencyContract * @param _bonusContract address bonusContract * @param _multiSig1 address multiSig where eth will be transferred * @param _startPreSaleDate timestamp * @param _endPreSaleDate timestamp * @param _startSaleDate timestamp * @param _endSaleDate timestamp */ function init( address _coinAddress, address _storageContract, address _currencyContract, address _bonusContract, address _multiSig1, uint _startPreSaleDate, uint _endPreSaleDate, uint _startSaleDate, uint _endSaleDate ) public onlyOwner { require(_coinAddress != address(0)); require(_storageContract != address(0)); require(_currencyContract != address(0)); require(_multiSig1 != address(0)); require(_bonusContract != address(0)); require(_startPreSaleDate > 0 && _startSaleDate > 0); require(_startSaleDate > _endPreSaleDate); require(_endSaleDate > _startSaleDate); require(startSaleDate == 0); coinContract = ERC20Basic(_coinAddress); storageContract = IStorage(_storageContract); currencyContract = ICurrency(_currencyContract); bonusContract = IBonus(_bonusContract); multiSig1 = _multiSig1; multiSig2 = 0x231121dFCB61C929BCdc0D1E6fC760c84e9A02ad; startPreSaleDate = _startPreSaleDate; endPreSaleDate = _endPreSaleDate; startSaleDate = _startSaleDate; endSaleDate = _endSaleDate; unfreezeRefundPreSale = _endSaleDate; unfreezeRefundAll = _endSaleDate.add(ONE_DAY); state = SaleState.NEW; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { paused = true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { paused = false; } /** * @dev Change the minimum amount in dollars indicated in cents to accept payment. * @param minContribUsd in cents */ function setMinimalContributionUSD(uint minContribUsd) public onlyOwner { require(minContribUsd > 100); // > 1$ uint oldMinAmount = minimalContributionUSD; minimalContributionUSD = minContribUsd; emit ChangeMinContribUSD(oldMinAmount, minimalContributionUSD); } /** * @dev Set the time when contributors can receive tokens * @param _time timestamp */ function setUnfreezeRefund(uint _time) public onlyOwner { require(_time > startSaleDate); unfreezeRefundPreSale = _time; unfreezeRefundAll = _time.add(ONE_DAY); } /** * @dev Change address ShipCoinStorage contracts. * @param _storageContract address ShipCoinStorage contracts */ function setStorageContract(address _storageContract) public onlyOwner { require(_storageContract != address(0)); address oldStorageContract = storageContract; storageContract = IStorage(_storageContract); emit ChangeStorageContract(oldStorageContract, storageContract); } /** * @dev Change address ShipCoin contracts. * @param _coinContract address ShipCoin contracts */ function setCoinContract(address _coinContract) public onlyOwner { require(_coinContract != address(0)); address oldCoinContract = coinContract; coinContract = ERC20Basic(_coinContract); emit ChangeCoinContract(oldCoinContract, coinContract); } /** * @dev Change address ShipCoinCurrency contracts. * @param _currencyContract address ShipCoinCurrency contracts */ function setCurrencyContract(address _currencyContract) public onlyOwner { require(_currencyContract != address(0)); address oldCurContract = currencyContract; currencyContract = ICurrency(_currencyContract); emit ChangeCurrencyContract(oldCurContract, currencyContract); } /** * @dev Change address ShipCoinBonusSystem contracts. * @param _bonusContract address ShipCoinBonusSystem contracts */ function setBonusContract(address _bonusContract) public onlyOwner { require(_bonusContract != address(0)); address oldContract = _bonusContract; bonusContract = IBonus(_bonusContract); emit ChangeBonusContract(oldContract, bonusContract); } /** * @dev Change address multiSig1. * @param _address address multiSig1 */ function setMultisig(address _address) public onlyOwner { require(_address != address(0)); multiSig1 = _address; } /** * @dev Set softCapUSD * @param _softCapUsdInCents uint softCapUSD > 100000 */ function setSoftCap(uint _softCapUsdInCents) public onlyOwner { require(_softCapUsdInCents > 100000); softCapUSD = _softCapUsdInCents; emit SoftCapChanged(); } /** * @dev Change maximum number of tokens sold * @param _maxCoin maxDistributeCoin */ function changeMaxDistributeCoin(uint _maxCoin) public onlyOwner { require(_maxCoin > 0 && _maxCoin >= currencyContract.getCoinRaisedInWei()); maxDistributeCoin = _maxCoin; } /** * @dev Change status. Start presale. */ function startPreSale() public onlyMultiOwnersType(1) { require(block.timestamp <= endPreSaleDate); require(state == SaleState.NEW); state = SaleState.PRESALE; emit ChangeState(block.number, state); } /** * @dev Change status. Start calculate presale bonus. */ function startCalculatePreSaleBonus() public onlyMultiOwnersType(5) { require(state == SaleState.PRESALE); state = SaleState.CALCPSBONUS; emit ChangeState(block.number, state); } /** * @dev Change status. Start sale. */ function startSale() public onlyMultiOwnersType(2) { require(block.timestamp <= endSaleDate); require(state == SaleState.CALCPSBONUS); //require(!storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); state = SaleState.SALE; emit ChangeState(block.number, state); } /** * @dev Change status. Set end if sale it was successful. */ function saleSetEnded() public onlyMultiOwnersType(3) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= startSaleDate); require(checkSoftCapAchieved()); state = SaleState.END; storageContract.changeSupportChangeMainWallet(false); emit ChangeState(block.number, state); } /** * @dev Change status. Set refund when sale did not reach softcap. */ function saleSetRefund() public onlyMultiOwnersType(4) { require((state == SaleState.SALE) || (state == SaleState.PRESALE)); require(block.timestamp >= endSaleDate); require(!checkSoftCapAchieved()); state = SaleState.REFUND; emit ChangeState(block.number, state); } /** * @dev Payable function. Processes contribution in ETH. */ function buyTokens(address _beneficiary) public whenNotPaused payable { require((state == SaleState.PRESALE && block.timestamp >= startPreSaleDate && block.timestamp <= endPreSaleDate) || (state == SaleState.SALE && block.timestamp >= startSaleDate && block.timestamp <= endSaleDate)); require(_beneficiary != address(0)); require(msg.value > 0); uint usdAmount = currencyContract.getUsdFromETH(msg.value); assert(usdAmount >= minimalContributionUSD); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert((totalToken > 0 && totalToken <= calculateMaxCoinIssued())); uint usdRate = currencyContract.getCurrencyRate("ETH"); assert(storageContract.addPayment(_beneficiary, "ETH", msg.value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, 0)); assert(currencyContract.addPay("ETH", msg.value, usdAmount, totalToken, tokenBonus)); emit AddPay(_beneficiary); } /** * @dev Manually add alternative contribution payment. * @param ticker string * @param value uint * @param uId uint contributor identificator * @param _pId uint payment identificator * @param _currencyUSD uint current ticker rate (optional field) */ function addPay(string ticker, uint value, uint uId, uint _pId, uint _currencyUSD) public onlyMultiOwnersType(6) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(_pId > 0); string memory _ticker = ticker; uint _value = value; assert(currencyContract.checkTickerExists(_ticker)); uint usdAmount = currencyContract.getUsdFromCurrency(_ticker, _value, _currencyUSD); assert(usdAmount > 0); uint bonusPercent = 0; if (state == SaleState.SALE) { bonusPercent = bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); assert(tokenWithoutBonus > 0); uint usdRate = _currencyUSD > 0 ? _currencyUSD : currencyContract.getCurrencyRate(_ticker); uint pId = _pId; assert(storageContract.addPayment(uId, _ticker, _value, usdAmount, usdRate, tokenWithoutBonus, tokenBonus, bonusPercent, pId)); assert(currencyContract.addPay(_ticker, _value, usdAmount, totalToken, tokenBonus)); emit AddPay(storageContract.getContributorAddressById(uId)); } /** * @dev Edit contribution payment. * @param uId uint contributor identificator * @param payId uint payment identificator * @param value uint * @param _currencyUSD uint current ticker rate (optional field) * @param _bonusPercent uint current ticker rate (optional field) */ function editPay(uint uId, uint payId, uint value, uint _currencyUSD, uint _bonusPercent) public onlyMultiOwnersType(7) { require(value > 0); require(storageContract.checkUserIdExists(uId)); require(payId > 0); require((_bonusPercent == 0 || _bonusPercent <= getPreSaleBonusPercent())); PaymentInfo memory payment = getPaymentInfo(uId, payId); EditPaymentInfo memory paymentInfo = calcEditPaymentInfo(payment, value, _currencyUSD, _bonusPercent); assert(paymentInfo.tokenWithoutBonus > 0); assert(paymentInfo.currency.value > 0); assert(paymentInfo.currency.usdRaised > 0); assert(paymentInfo.currency.usdAbsRaisedInCents > 0); assert(paymentInfo.currency.coinRaisedInWei > 0); assert(currencyContract.editPay(payment.pType, paymentInfo.currency.value, paymentInfo.currency.usdRaised, paymentInfo.currency.usdAbsRaisedInCents, paymentInfo.currency.coinRaisedInWei, paymentInfo.currency.coinRaisedBonusInWei)); assert(storageContract.editPaymentByUserId(uId, payId, value, paymentInfo.usdAmount, paymentInfo.currencyUSD, paymentInfo.totalToken, paymentInfo.tokenWithoutBonus, paymentInfo.tokenBonus, paymentInfo.bonusPercent)); assert(reCountUserPreSaleBonus(uId)); emit EditPay(storageContract.getContributorAddressById(uId)); } /** * @dev Refund contribution payment. * @param uId uint * @param payId uint */ function refundPay(uint uId, uint payId) public onlyMultiOwnersType(18) { require(storageContract.checkUserIdExists(uId)); require(payId > 0); (CurrencyInfo memory currencyInfo, bytes32 pType) = calcCurrency(getPaymentInfo(uId, payId), 0, 0, 0, 0); assert(storageContract.refundPaymentByUserId(uId, payId)); assert(currencyContract.editPay(pType, currencyInfo.value, currencyInfo.usdRaised, currencyInfo.usdAbsRaisedInCents, currencyInfo.coinRaisedInWei, currencyInfo.coinRaisedBonusInWei)); assert(reCountUserPreSaleBonus(uId)); emit RefundPay(storageContract.getContributorAddressById(uId)); } /** * @dev Check if softCap is reached */ function checkSoftCapAchieved() public view returns(bool) { return softCapAchieved || getTotalUsdRaisedInCents() >= softCapUSD; } /** * @dev Set softCapAchieved=true if softCap is reached */ function activeSoftCapAchieved() public onlyMultiOwnersType(8) { require(checkSoftCapAchieved()); require(getCoinBalance() >= maxDistributeCoin); softCapAchieved = true; emit SoftCapAchieved(getTotalUsdRaisedInCents()); } /** * @dev Send ETH from contract balance to multiSig. */ function getEther() public onlyMultiOwnersType(9) { require(getETHBalance() > 0); require(softCapAchieved && (!multiSigReceivedSoftCap || (state == SaleState.END))); uint sendEther = (address(this).balance / 2); assert(sendEther > 0); address(multiSig1).transfer(sendEther); address(multiSig2).transfer(sendEther); multiSigReceivedSoftCap = true; } /** * @dev Return maximum amount buy token. */ function calculateMaxCoinIssued() public view returns (uint) { return maxDistributeCoin - currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised SHPC in wei. */ function getCoinRaisedInWei() public view returns (uint) { return currencyContract.getCoinRaisedInWei(); } /** * @dev Return raised usd in cents. */ function getTotalUsdRaisedInCents() public view returns (uint) { return currencyContract.getTotalUsdRaisedInCents(); } /** * @dev Return all currency rate in json. */ function getAllCurrencyTicker() public view returns (string) { return currencyContract.getAllCurrencyTicker(); } /** * @dev Return SHPC price in cents. */ function getCoinUSDRate() public view returns (uint) { return currencyContract.getCoinUSDRate(); } /** * @dev Retrun SHPC balance in contract. */ function getCoinBalance() public view returns (uint) { return coinContract.balanceOf(address(this)); } /** * @dev Return balance ETH from contract. */ function getETHBalance() public view returns (uint) { return address(this).balance; } /** * @dev Processing of the data of the contributors. Bonus assignment for presale. * @param start uint > 0 * @param limit uint > 0 */ function processSetPreSaleBonus(uint start, uint limit) public onlyMultiOwnersType(10) { require(state == SaleState.CALCPSBONUS); require(start >= 0 && limit > 0); //require(storageContract.checkNeedProcessPreSaleBonus(getMinReachUsdPayInCents())); uint bonusToken = storageContract.processPreSaleBonus(getMinReachUsdPayInCents(), getPreSaleBonusPercent(), start, limit); if (bonusToken > 0) { assert(currencyContract.addPreSaleBonus(bonusToken)); } } /** * @dev Processing of the data of the contributor by uId. Bonus assignment for presale. * @param uId uint */ function reCountUserPreSaleBonus(uint uId) public onlyMultiOwnersType(11) returns(bool) { if (uint(state) > 1) { // > PRESALE uint maxPayTime = 0; if (state != SaleState.CALCPSBONUS) { maxPayTime = startSaleDate; } (uint befTokenBonus, uint aftTokenBonus) = storageContract.reCountUserPreSaleBonus(uId, getMinReachUsdPayInCents(), getPreSaleBonusPercent(), maxPayTime); assert(currencyContract.editPreSaleBonus(befTokenBonus, aftTokenBonus)); } return true; } /** * @dev Contributor get SHPC. */ function getCoins() public { return _getCoins(msg.sender); } /** * @dev Send contributors SHPC. * @param start uint * @param limit uint */ function sendSHPCtoContributors(uint start, uint limit) public onlyMultiOwnersType(12) { require(state == SaleState.END); require(start >= 0 && limit > 0); require(getCoinBalance() > 0); //require(storageContract.checkNeedSendSHPC(state == SaleState.END)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint coins = storageContract.getTotalCoin(addr); if (!storageContract.checkReceivedCoins(addr) && storageContract.checkWalletExists(addr) && coins > 0 && ((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll))) { if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } } } } /** * @dev Set startPreSaleDate * @param date timestamp */ function setStartPreSaleDate(uint date) public onlyMultiOwnersType(13) { uint oldDate = startPreSaleDate; startPreSaleDate = date; emit ManualChangeStartPreSaleDate(oldDate, date); } /** * @dev Set startPreSaleDate * @param date timestamp */ function setEndPreSaleDate(uint date) public onlyMultiOwnersType(14) { uint oldDate = endPreSaleDate; endPreSaleDate = date; emit ManualChangeEndPreSaleDate(oldDate, date); } /** * @dev Set startSaleDate * @param date timestamp */ function setStartSaleDate(uint date) public onlyMultiOwnersType(15) { uint oldDate = startSaleDate; startSaleDate = date; emit ManualChangeStartSaleDate(oldDate, date); } /** * @dev Set endSaleDate * @param date timestamp */ function setEndSaleDate(uint date) public onlyMultiOwnersType(16) { uint oldDate = endSaleDate; endSaleDate = date; emit ManualEndSaleDate(oldDate, date); } /** * @dev Return SHPC from contract. When sale ended end contributor got SHPC. */ function getSHPCBack() public onlyMultiOwnersType(17) { require(state == SaleState.END); require(getCoinBalance() > 0); //require(!storageContract.checkNeedSendSHPC(state == SaleState.END)); coinContract.transfer(msg.sender, getCoinBalance()); } /** * @dev Refund ETH contributor. */ function refundETH() public { return _refundETH(msg.sender); } /** * @dev Refund ETH contributors. * @param start uint * @param limit uint */ function refundETHContributors(uint start, uint limit) public onlyMultiOwnersType(19) { require(state == SaleState.REFUND); require(start >= 0 && limit > 0); require(getETHBalance() > 0); //require(storageContract.checkETHRefund(state == SaleState.REFUND)); for (uint i = start; i < limit; i++) { uint uId = storageContract.getContributorIndexes(i); if (uId > 0) { address addr = storageContract.getContributorAddressById(uId); uint ethAmount = storageContract.getEthPaymentContributor(addr); if (!storageContract.checkRefund(addr) && storageContract.checkWalletExists(addr) && ethAmount > 0) { storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } } } } /** * @dev Return pre-sale bonus getPreSaleBonusPercent. */ function getPreSaleBonusPercent() public view returns(uint) { return bonusContract.getPreSaleBonusPercent(); } /** * @dev Return pre-sale minReachUsdPayInCents. */ function getMinReachUsdPayInCents() public view returns(uint) { return bonusContract.getMinReachUsdPayInCents(); } /** * @dev Return current sale day. */ function _currentDay() public view returns(uint) { return bonusContract._currentDay(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return current sale day bonus percent. */ function getCurrentDayBonus() public view returns(uint) { return bonusContract.getCurrentDayBonus(startSaleDate, (state == SaleState.SALE)); } /** * @dev Return contributor payment info. * @param uId uint * @param pId uint */ function getPaymentInfo(uint uId, uint pId) private view returns(PaymentInfo) { (, bytes32 pType, uint currencyUSD, uint bonusPercent, uint payValue, uint totalToken, uint tokenBonus,, uint usdAbsRaisedInCents, bool refund) = storageContract.getUserPaymentById(uId, pId); return PaymentInfo(pType, currencyUSD, bonusPercent, payValue, totalToken, tokenBonus, usdAbsRaisedInCents, refund); } /** * @dev Return recalculate payment data from old payment user. */ function calcEditPaymentInfo(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(EditPaymentInfo) { (uint usdAmount, uint currencyUSD, uint bonusPercent) = getUsdAmountFromPayment(payment, value, _currencyUSD, _bonusPercent); (uint totalToken, uint tokenWithoutBonus, uint tokenBonus) = calcToken(usdAmount, bonusPercent); (CurrencyInfo memory currency,) = calcCurrency(payment, value, usdAmount, totalToken, tokenBonus); return EditPaymentInfo(usdAmount, currencyUSD, bonusPercent, totalToken, tokenWithoutBonus, tokenBonus, currency); } /** * @dev Return usd from payment amount. */ function getUsdAmountFromPayment(PaymentInfo payment, uint value, uint _currencyUSD, uint _bonusPercent) private view returns(uint, uint, uint) { _currencyUSD = _currencyUSD > 0 ? _currencyUSD : payment.currencyUSD; _bonusPercent = _bonusPercent > 0 ? _bonusPercent : payment.bonusPercent; uint usdAmount = currencyContract.getUsdFromCurrency(payment.pType, value, _currencyUSD); return (usdAmount, _currencyUSD, _bonusPercent); } /** * @dev Return payment SHPC data from usd amount and bonusPercent */ function calcToken(uint usdAmount, uint _bonusPercent) private view returns(uint, uint, uint) { uint tokenWithoutBonus = currencyContract.getTokenWeiFromUSD(usdAmount); uint tokenBonus = _bonusPercent > 0 ? tokenWithoutBonus.mul(_bonusPercent).div(100) : 0; uint totalToken = tokenBonus > 0 ? tokenWithoutBonus.add(tokenBonus) : tokenWithoutBonus; return (totalToken, tokenWithoutBonus, tokenBonus); } /** * @dev Calculate currency data when edit user payment data */ function calcCurrency(PaymentInfo payment, uint value, uint usdAmount, uint totalToken, uint tokenBonus) private view returns(CurrencyInfo, bytes32) { (,,, uint currencyValue, uint currencyUsdRaised,,,) = currencyContract.getCurrencyList(payment.pType); uint usdAbsRaisedInCents = currencyContract.getUsdAbsRaisedInCents(); uint coinRaisedInWei = currencyContract.getCoinRaisedInWei(); uint coinRaisedBonusInWei = currencyContract.getCoinRaisedBonusInWei(); currencyValue -= payment.payValue; currencyUsdRaised -= payment.usdAbsRaisedInCents; usdAbsRaisedInCents -= payment.usdAbsRaisedInCents; coinRaisedInWei -= payment.totalToken; coinRaisedBonusInWei -= payment.tokenBonus; currencyValue += value; currencyUsdRaised += usdAmount; usdAbsRaisedInCents += usdAmount; coinRaisedInWei += totalToken; coinRaisedBonusInWei += tokenBonus; return (CurrencyInfo(currencyValue, currencyUsdRaised, usdAbsRaisedInCents, coinRaisedInWei, coinRaisedBonusInWei), payment.pType); } /** * @dev Getting the SHPC from the contributor */ function _getCoins(address addr) private { require(state == SaleState.END); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkReceivedCoins(addr)); require((storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundPreSale) || (!storageContract.checkPreSaleReceivedBonus(addr) && block.timestamp >= unfreezeRefundAll)); uint uId = storageContract.getContributorId(addr); uint coins = storageContract.getTotalCoin(addr); assert(uId > 0 && coins > 0); if (coinContract.transfer(addr, coins)) { storageContract.setReceivedCoin(uId); emit SendSHPCtoContributor(addr); } } /** * @dev Refund ETH contributor when sale not reach softcap. */ function _refundETH(address addr) private { require(state == SaleState.REFUND); require(storageContract.checkWalletExists(addr)); require(!storageContract.checkRefund(addr)); uint uId = storageContract.getContributorId(addr); uint ethAmount = storageContract.getEthPaymentContributor(addr); assert(uId > 0 && ethAmount > 0 && getETHBalance() >= ethAmount); storageContract.setRefund(uId); addr.transfer(ethAmount); emit Refund(addr); } }
called by the owner to unpause, returns to normal state/
function unpause() public onlyOwner { paused = false; }
15,856,443
/* Copyright 2017 Dharma 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.4.18; import "./DebtRegistry.sol"; import "NonFungibleToken/contracts/MintableNonFungibleToken.sol"; import "zeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /** * The DebtToken contract governs all business logic for making a debt agreement * transferable as an ERC721 non-fungible token. Additionally, the contract * allows authorized contracts to trigger the minting of a debt agreement token * and, in turn, the insertion of a debt issuance into the DebtRegsitry. * * Author: Nadav Hollander -- Github: nadavhollander */ contract DebtToken is MintableNonFungibleToken, Pausable { using PermissionsLib for PermissionsLib.Permissions; string public name = "DebtToken"; string public symbol = "DDT"; DebtRegistry public registry; PermissionsLib.Permissions internal tokenCreationPermissions; PermissionsLib.Permissions internal tokenBrokeragePermissions; /** * Constructor that sets the address of the debt registry. */ function DebtToken(address _registry) public { registry = DebtRegistry(_registry); } /** * Mints a unique debt token and inserts the associated issuance into * the debt registry, if the calling address is authorized to do so. */ function create( address _version, address _beneficiary, address _debtor, address _underwriter, uint _underwriterRiskRating, address _termsContract, bytes32 _termsContractParameters, uint _salt ) public whenNotPaused returns (uint _tokenId) { require(tokenCreationPermissions.isAuthorized(msg.sender)); bytes32 entryHash = registry.insert( _version, _beneficiary, _debtor, _underwriter, _underwriterRiskRating, _termsContract, _termsContractParameters, _salt ); mint(_beneficiary, uint(entryHash)); return uint(entryHash); } /** * Adds an address to the list of agents authorized to mint debt tokens. */ function addAuthorizedMintAgent(address _agent) public onlyOwner { tokenCreationPermissions.authorize(_agent); } /** * Removes an address from the list of agents authorized to mint debt tokens */ function revokeMintAgentAuthorization(address _agent) public onlyOwner { tokenCreationPermissions.revokeAuthorization(_agent); } /** * Returns the list of agents authorized to mint debt tokens */ function getAuthorizedMintAgents() public view returns (address[] _agents) { return tokenCreationPermissions.getAuthorizedAgents(); } /** * We override the core transfer method of the parent non-fungible token * contract to allow its functionality to be frozen in the case of an emergency */ function _clearApprovalAndTransfer( address _from, address _to, uint _tokenId ) internal whenNotPaused { super._clearApprovalAndTransfer(_from, _to, _tokenId); } /** * We override the core approvals method of the parent non-fungible token * contract to allow its functionality to be frozen in the case of an emergency */ function _approve(address _to, uint _tokenId) internal whenNotPaused { super._approve(_to, _tokenId); } /** * We oveerride the core ownership transfer method of the parent non-fungible token * contract so that it mutates the debt registry every time a token is transferred */ function _setTokenOwner(uint _tokenId, address _to) internal { if (registry.getBeneficiary(bytes32(_tokenId)) != _to) { registry.modifyBeneficiary(bytes32(_tokenId), _to); } super._setTokenOwner(_tokenId, _to); } }
We override the core transfer method of the parent non-fungible token contract to allow its functionality to be frozen in the case of an emergency/
function _clearApprovalAndTransfer( address _from, address _to, uint _tokenId ) internal whenNotPaused { super._clearApprovalAndTransfer(_from, _to, _tokenId); }
14,124,700
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./XanaArtTradable.sol"; contract XanaArtFactory is Ownable { /// @dev Events of the contract event ContractCreated(address creator, address nft); event ContractDisabled(address caller, address nft); /// @notice Xana marketplace contract address; address public marketplace; /// @notice Xana bundle marketplace contract address; address public bundleMarketplace; /// @notice NFT mint fee uint256 public mintFee; /// @notice Platform fee for deploying new NFT contract uint256 public platformFee; /// @notice Platform fee recipient address payable public feeRecipient; /// @notice NFT Address => Bool mapping(address => bool) public exists; bytes4 private constant INTERFACE_ID_ERC1155 = 0xd9b67a26; /// @notice Contract constructor constructor( address _marketplace, address _bundleMarketplace, uint256 _mintFee, address payable _feeRecipient, uint256 _platformFee ) public { marketplace = _marketplace; bundleMarketplace = _bundleMarketplace; mintFee = _mintFee; feeRecipient = _feeRecipient; platformFee = _platformFee; } /** @notice Update marketplace contract @dev Only admin @param _marketplace address the marketplace contract address to set */ function updateMarketplace(address _marketplace) external onlyOwner { marketplace = _marketplace; } /** @notice Update bundle marketplace contract @dev Only admin @param _bundleMarketplace address the bundle marketplace contract address to set */ function updateBundleMarketplace(address _bundleMarketplace) external onlyOwner { bundleMarketplace = _bundleMarketplace; } /** @notice Update mint fee @dev Only admin @param _mintFee uint256 the platform fee to set */ function updateMintFee(uint256 _mintFee) external onlyOwner { mintFee = _mintFee; } /** @notice Update platform fee @dev Only admin @param _platformFee uint256 the platform fee to set */ function updatePlatformFee(uint256 _platformFee) external onlyOwner { platformFee = _platformFee; } /** @notice Method for updating platform fee address @dev Only admin @param _feeRecipient payable address the address to sends the funds to */ function updateFeeRecipient(address payable _feeRecipient) external onlyOwner { feeRecipient = _feeRecipient; } /// @notice Method for deploy new XanaArtTradable contract /// @param _name Name of NFT contract /// @param _symbol Symbol of NFT contract function createNFTContract(string memory _name, string memory _symbol) external payable returns (address) { require(msg.value >= platformFee, "Insufficient funds."); (bool success,) = feeRecipient.call{value: msg.value}(""); require(success, "Transfer failed"); XanaArtTradable nft = new XanaArtTradable( _name, _symbol, mintFee, feeRecipient, marketplace, bundleMarketplace ); exists[address(nft)] = true; nft.transferOwnership(_msgSender()); emit ContractCreated(_msgSender(), address(nft)); return address(nft); } /// @notice Method for registering existing XanaArtTradable contract /// @param tokenContractAddress Address of NFT contract function registerTokenContract(address tokenContractAddress) external onlyOwner { require(!exists[tokenContractAddress], "Art contract already registered"); require(IERC165(tokenContractAddress).supportsInterface(INTERFACE_ID_ERC1155), "Not an ERC1155 contract"); exists[tokenContractAddress] = true; emit ContractCreated(_msgSender(), tokenContractAddress); } /// @notice Method for disabling existing XanaArtTradable contract /// @param tokenContractAddress Address of NFT contract function disableTokenContract(address tokenContractAddress) external onlyOwner { require(exists[tokenContractAddress], "Art contract is not registered"); exists[tokenContractAddress] = false; emit ContractDisabled(_msgSender(), tokenContractAddress); } } // 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.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./library/ERC1155.sol"; import "./library/ERC1155MintBurn.sol"; import "./library/ERC1155Metadata.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title XanaArtTradable * XanaArtTradable - ERC1155 contract that whitelists an operator address, * has mint functionality, and supports useful standards from OpenZeppelin, like _exists(), name(), symbol(), and totalSupply() */ contract XanaArtTradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable { uint256 private _currentTokenID = 0; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; // Contract name string public name; // Contract symbol string public symbol; // Platform fee uint256 public platformFee; // Platform fee receipient address payable public feeReceipient; // Xana Marketplace contract address marketplace; // Xana Bundle Marketplace contract address bundleMarketplace; constructor( string memory _name, string memory _symbol, uint256 _platformFee, address payable _feeReceipient, address _marketplace, address _bundleMarketplace ) public { name = _name; symbol = _symbol; platformFee = _platformFee; feeReceipient = _feeReceipient; marketplace = _marketplace; bundleMarketplace = _bundleMarketplace; } function uri(uint256 _id) public view override returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return _tokenURIs[_id]; } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Creates a new token type and assigns _supply to an address * @param _to owner address of the new token * @param _supply Optional amount to supply the first owner * @param _uri Optional URI for this token type */ function mint( address _to, uint256 _supply, string calldata _uri ) external payable { require(msg.value >= platformFee, "Insufficient funds to mint."); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; _setTokenURI(_id, _uri); if (bytes(_uri).length > 0) { emit URI(_uri, _id); } _mint(_to, _id, _supply, bytes("")); tokenSupply[_id] = _supply; // Send ETH fee to fee recipient (bool success, ) = feeReceipient.call{value: msg.value}(""); require(success, "Transfer failed"); } function getCurrentTokenID() public view returns (uint256) { return _currentTokenID; } /** * Override isApprovedForAll to whitelist Xana contracts to enable gas-less listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist Xana marketplace, bundle marketplace contracts for easy trading. if (marketplace == _operator || bundleMarketplace == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) public view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param _id uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _id, string memory _uri) internal { require(_exists(_id), "_setTokenURI: Token should exist"); _tokenURIs[_id] = _uri; } } // 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: UNLICENSE pragma solidity 0.6.12; import './IERC165.sol'; import './IERC1155TokenReceiver.sol'; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping (address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping (address => mapping(address => bool)) internal operators; // Events event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _uri, uint256 indexed _id); /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @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 { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator Bool of approved for all */ function isApprovedForAll(address _owner, address _operator) public view virtual returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * @dev INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /** * @dev INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) external view override returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } // SPDX-License-Identifier: UNLICENSE pragma solidity 0.6.12; import './ERC1155.sol'; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nBurn = _ids.length; // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: UNLICENSE pragma solidity 0.6.12; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view virtual returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } } // SPDX-License-Identifier: UNLICENSE pragma solidity 0.6.12; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // SPDX-License-Identifier: UNLICENSE pragma solidity 0.6.12; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @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 _amounts, bytes calldata _data) external returns(bytes4); /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // 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.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; } }
Method for deploy new XanaArtTradable contract _name Name of NFT contract _symbol Symbol of NFT contract
function createNFTContract(string memory _name, string memory _symbol) external payable returns (address) { require(msg.value >= platformFee, "Insufficient funds."); require(success, "Transfer failed"); XanaArtTradable nft = new XanaArtTradable( _name, _symbol, mintFee, feeRecipient, marketplace, bundleMarketplace ); exists[address(nft)] = true; nft.transferOwnership(_msgSender()); emit ContractCreated(_msgSender(), address(nft)); return address(nft); }
11,842,261
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); } interface ITokensTypeStorage { function isRegistred(address _address) external view returns(bool); function getType(address _address) external view returns(bytes32); function isPermittedAddress(address _address) external view returns(bool); function owner() external view returns(address); function addNewTokenType(address _token, string calldata _type) external; function setTokenTypeAsOwner(address _token, string calldata _type) external; } interface UniswapFactoryInterface { // Create Exchange function createExchange(address token) external returns (address exchange); // Get Exchange and Token Info function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); // Never use function initializeFactory(address template) external; } interface UniswapExchangeInterface { // Address of ERC20 token sold on this exchange function tokenAddress() external view returns (address token); // Address of Uniswap Factory function factoryAddress() external view returns (address factory); // Provide Liquidity function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); // Get Prices function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold); // Trade ETH to ERC20 function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold); // Trade ERC20 to ETH function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold); // Trade ERC20 to ERC20 function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold); function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold); // Trade ERC20 to Custom Pool function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold); function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold); // ERC20 comaptibility for liquidity tokens function name() external view returns(bytes32); function symbol() external view returns(bytes32); function decimals() external view returns(uint256); 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); function allowance(address _owner, address _spender) external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function totalSupply() external view returns (uint256); // Never use function setup(address token_addr) external; } interface IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) external view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) external view returns (uint256); function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) external view returns (uint256); function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256); function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256); } interface IGetBancorAddressFromRegistry { function getBancorContractAddresByName(string calldata _name) external view returns (address result); } interface IGetRatioForBancorAssets { function getRatio(address _from, address _to, uint256 _amount) external view returns(uint256 result); } interface BancorConverterInterface { function connectorTokens(uint index) external view returns(IERC20); function fund(uint256 _amount) external; function liquidate(uint256 _amount) external; function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256); } /* * This contract allow buy/sell pool for Bancor and Uniswap assets * and provide ratio and addition info for pool assets */ /** * @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; } } interface SmartTokenInterface is IERC20 { function disableTransfers(bool _disable) external; function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; function owner() external view returns (address); } contract PoolPortal { using SafeMath for uint256; IGetRatioForBancorAssets public bancorRatio; IGetBancorAddressFromRegistry public bancorRegistry; UniswapFactoryInterface public uniswapFactory; address public BancorEtherToken; // CoTrader platform recognize ETH by this address IERC20 constant private ETH_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Enum // NOTE: You can add a new type at the end, but do not change this order enum PortalType { Bancor, Uniswap } // events event BuyPool(address poolToken, uint256 amount, address trader); event SellPool(address poolToken, uint256 amount, address trader); // Contract for handle tokens types ITokensTypeStorage public tokensTypes; /** * @dev contructor * * @param _bancorRegistryWrapper address of GetBancorAddressFromRegistry * @param _bancorRatio address of GetRatioForBancorAssets * @param _bancorEtherToken address of Bancor ETH wrapper * @param _uniswapFactory address of Uniswap factory contract * @param _tokensTypes address of the ITokensTypeStorage */ constructor( address _bancorRegistryWrapper, address _bancorRatio, address _bancorEtherToken, address _uniswapFactory, address _tokensTypes ) public { bancorRegistry = IGetBancorAddressFromRegistry(_bancorRegistryWrapper); bancorRatio = IGetRatioForBancorAssets(_bancorRatio); BancorEtherToken = _bancorEtherToken; uniswapFactory = UniswapFactoryInterface(_uniswapFactory); tokensTypes = ITokensTypeStorage(_tokensTypes); } /** * @dev buy Bancor or Uniswap pool * * @param _amount amount of pool token * @param _type pool type * @param _poolToken pool token address */ function buyPool ( uint256 _amount, uint _type, IERC20 _poolToken ) external payable { if(_type == uint(PortalType.Bancor)){ buyBancorPool(_poolToken, _amount); } else if (_type == uint(PortalType.Uniswap)){ require(_amount == msg.value, "Not enough ETH"); buyUniswapPool(address(_poolToken), _amount); } else{ // unknown portal type revert(); } emit BuyPool(address(_poolToken), _amount, msg.sender); } /** * @dev helper for buy pool in Bancor network * * @param _poolToken address of bancor converter * @param _amount amount of bancor relay */ function buyBancorPool(IERC20 _poolToken, uint256 _amount) private { // get Bancor converter address converterAddress = getBacorConverterAddressByRelay(address(_poolToken)); // calculate connectors amount for buy certain pool amount (uint256 bancorAmount, uint256 connectorAmount) = getBancorConnectorsAmountByRelayAmount(_amount, _poolToken); // get converter as contract BancorConverterInterface converter = BancorConverterInterface(converterAddress); // approve bancor and coonector amount to converter // get connectors (IERC20 bancorConnector, IERC20 ercConnector) = getBancorConnectorsByRelay(address(_poolToken)); // reset approve (some ERC20 not allow do new approve if already approved) bancorConnector.approve(converterAddress, 0); ercConnector.approve(converterAddress, 0); // transfer from fund and approve to converter _transferFromSenderAndApproveTo(bancorConnector, bancorAmount, converterAddress); _transferFromSenderAndApproveTo(ercConnector, connectorAmount, converterAddress); // buy relay from converter converter.fund(_amount); require(_amount > 0, "BNT pool recieved amount can not be zerro"); // transfer relay back to smart fund _poolToken.transfer(msg.sender, _amount); // transfer connectors back if a small amount remains uint256 bancorRemains = bancorConnector.balanceOf(address(this)); if(bancorRemains > 0) bancorConnector.transfer(msg.sender, bancorRemains); uint256 ercRemains = ercConnector.balanceOf(address(this)); if(ercRemains > 0) ercConnector.transfer(msg.sender, ercRemains); setTokenType(address(_poolToken), "BANCOR_ASSET"); } /** * @dev helper for buy pool in Uniswap network * * @param _poolToken address of Uniswap exchange * @param _ethAmount ETH amount (in wei) */ function buyUniswapPool(address _poolToken, uint256 _ethAmount) private returns(uint256 poolAmount) { // get token address address tokenAddress = uniswapFactory.getToken(_poolToken); // check if such a pool exist if(tokenAddress != address(0x0000000000000000000000000000000000000000)){ // get tokens amd approve to exchange uint256 erc20Amount = getUniswapTokenAmountByETH(tokenAddress, _ethAmount); _transferFromSenderAndApproveTo(IERC20(tokenAddress), erc20Amount, _poolToken); // get exchange contract UniswapExchangeInterface exchange = UniswapExchangeInterface(_poolToken); // set deadline uint256 deadline = now + 15 minutes; // buy pool poolAmount = exchange.addLiquidity.value(_ethAmount)( 1, erc20Amount, deadline); // reset approve (some ERC20 not allow do new approve if already approved) IERC20(tokenAddress).approve(_poolToken, 0); require(poolAmount > 0, "UNI pool recieved amount can not be zerro"); // transfer pool token back to smart fund IERC20(_poolToken).transfer(msg.sender, poolAmount); // transfer ERC20 remains uint256 remainsERC = IERC20(tokenAddress).balanceOf(address(this)); if(remainsERC > 0) IERC20(tokenAddress).transfer(msg.sender, remainsERC); setTokenType(_poolToken, "UNISWAP_POOL"); }else{ // throw if such pool not Exist in Uniswap network revert(); } } /** * @dev return token amount by ETH input ratio * * @param _token address of ERC20 token * @param _amount ETH amount (in wei) */ function getUniswapTokenAmountByETH(address _token, uint256 _amount) public view returns(uint256) { UniswapExchangeInterface exchange = UniswapExchangeInterface( uniswapFactory.getExchange(_token)); return exchange.getTokenToEthOutputPrice(_amount); } /** * @dev sell Bancor or Uniswap pool * * @param _amount amount of pool token * @param _type pool type * @param _poolToken pool token address */ function sellPool ( uint256 _amount, uint _type, IERC20 _poolToken ) external payable { if(_type == uint(PortalType.Bancor)){ sellPoolViaBancor(_poolToken, _amount); } else if (_type == uint(PortalType.Uniswap)){ sellPoolViaUniswap(_poolToken, _amount); } else{ // unknown portal type revert(); } emit SellPool(address(_poolToken), _amount, msg.sender); } /** * @dev helper for sell pool in Bancor network * * @param _poolToken address of bancor relay * @param _amount amount of bancor relay */ function sellPoolViaBancor(IERC20 _poolToken, uint256 _amount) private { // transfer pool from fund _poolToken.transferFrom(msg.sender, address(this), _amount); // get Bancor Converter address address converterAddress = getBacorConverterAddressByRelay(address(_poolToken)); // liquidate relay BancorConverterInterface(converterAddress).liquidate(_amount); // get connectors (IERC20 bancorConnector, IERC20 ercConnector) = getBancorConnectorsByRelay(address(_poolToken)); // transfer connectors back to fund bancorConnector.transfer(msg.sender, bancorConnector.balanceOf(address(this))); ercConnector.transfer(msg.sender, ercConnector.balanceOf(address(this))); } /** * @dev helper for sell pool in Uniswap network * * @param _poolToken address of uniswap exchane * @param _amount amount of uniswap pool */ function sellPoolViaUniswap(IERC20 _poolToken, uint256 _amount) private { address tokenAddress = uniswapFactory.getToken(address(_poolToken)); // check if such a pool exist if(tokenAddress != address(0x0000000000000000000000000000000000000000)){ UniswapExchangeInterface exchange = UniswapExchangeInterface(address(_poolToken)); // approve pool token _transferFromSenderAndApproveTo(IERC20(_poolToken), _amount, address(_poolToken)); // get min returns (uint256 minEthAmount, uint256 minErcAmount) = getUniswapConnectorsAmountByPoolAmount( _amount, address(_poolToken)); // set deadline uint256 deadline = now + 15 minutes; // liquidate (uint256 eth_amount, uint256 token_amount) = exchange.removeLiquidity( _amount, minEthAmount, minErcAmount, deadline); // transfer assets back to smart fund msg.sender.transfer(eth_amount); IERC20(tokenAddress).transfer(msg.sender, token_amount); }else{ revert(); } } /** * @dev helper for get bancor converter by bancor relay addrses * * @param _relay address of bancor relay */ function getBacorConverterAddressByRelay(address _relay) public view returns(address converter) { converter = SmartTokenInterface(_relay).owner(); } /** * @dev helper for get Bancor ERC20 connectors addresses * * @param _relay address of bancor relay */ function getBancorConnectorsByRelay(address _relay) public view returns( IERC20 BNTConnector, IERC20 ERCConnector ) { address converterAddress = getBacorConverterAddressByRelay(_relay); BancorConverterInterface converter = BancorConverterInterface(converterAddress); BNTConnector = converter.connectorTokens(0); ERCConnector = converter.connectorTokens(1); } /** * @dev return ERC20 address from Uniswap exchange address * * @param _exchange address of uniswap exchane */ function getTokenByUniswapExchange(address _exchange) external view returns(address) { return uniswapFactory.getToken(_exchange); } /** * @dev helper for get amounts for both Uniswap connectors for input amount of pool * * @param _amount relay amount * @param _exchange address of uniswap exchane */ function getUniswapConnectorsAmountByPoolAmount( uint256 _amount, address _exchange ) public view returns(uint256 ethAmount, uint256 ercAmount) { IERC20 token = IERC20(uniswapFactory.getToken(_exchange)); // total_liquidity exchange.totalSupply uint256 totalLiquidity = UniswapExchangeInterface(_exchange).totalSupply(); // ethAmount = amount * exchane.eth.balance / total_liquidity ethAmount = _amount.mul(_exchange.balance).div(totalLiquidity); // ercAmount = amount * token.balanceOf(exchane) / total_liquidity ercAmount = _amount.mul(token.balanceOf(_exchange)).div(totalLiquidity); } /** * @dev helper for get amount for both Bancor connectors for input amount of pool * * @param _amount relay amount * @param _relay address of bancor relay */ function getBancorConnectorsAmountByRelayAmount ( uint256 _amount, IERC20 _relay ) public view returns(uint256 bancorAmount, uint256 connectorAmount) { // get converter contract BancorConverterInterface converter = BancorConverterInterface( SmartTokenInterface(address(_relay)).owner()); // calculate BNT and second connector amount // get connectors IERC20 bancorConnector = converter.connectorTokens(0); IERC20 ercConnector = converter.connectorTokens(1); // get connectors balance uint256 bntBalance = converter.getConnectorBalance(bancorConnector); uint256 ercBalance = converter.getConnectorBalance(ercConnector); // get bancor formula contract IBancorFormula bancorFormula = IBancorFormula( bancorRegistry.getBancorContractAddresByName("BancorFormula")); // calculate input bancorAmount = bancorFormula.calculateFundCost( _relay.totalSupply(), bntBalance, 1000000, _amount); connectorAmount = bancorFormula.calculateFundCost( _relay.totalSupply(), ercBalance, 1000000, _amount); } /** * @dev helper for get ratio between assets in bancor newtork * * @param _from token or relay address * @param _to token or relay address * @param _amount amount from */ function getBancorRatio(address _from, address _to, uint256 _amount) external view returns(uint256) { // Change ETH to Bancor ETH wrapper address fromAddress = IERC20(_from) == ETH_TOKEN_ADDRESS ? BancorEtherToken : _from; address toAddress = IERC20(_to) == ETH_TOKEN_ADDRESS ? BancorEtherToken : _to; // return Bancor ratio return bancorRatio.getRatio(fromAddress, toAddress, _amount); } /** * @dev Transfers tokens to this contract and approves them to another address * * @param _source Token to transfer and approve * @param _sourceAmount The amount to transfer and approve (in _source token) * @param _to Address to approve to */ function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private { require(_source.transferFrom(msg.sender, address(this), _sourceAmount)); _source.approve(_to, _sourceAmount); } // Pool portal can mark each pool token as UNISWAP or BANCOR function setTokenType(address _token, string memory _type) private { // no need add type, if token alredy registred if(tokensTypes.isRegistred(_token)) return; tokensTypes.addNewTokenType(_token, _type); } // fallback payable function to receive ether from other contract addresses fallback() external payable {} }
sell Bancor or Uniswap pool _amount amount of pool token _type pool type _poolToken pool token address/ unknown portal type
function sellPool ( uint256 _amount, uint _type, IERC20 _poolToken ) external payable { if(_type == uint(PortalType.Bancor)){ sellPoolViaBancor(_poolToken, _amount); } else if (_type == uint(PortalType.Uniswap)){ sellPoolViaUniswap(_poolToken, _amount); } else{ revert(); } emit SellPool(address(_poolToken), _amount, msg.sender); }
14,713,698
pragma solidity ^0.6.0; import "./Database.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract DatabaseFactory is Ownable { /** @dev SafeMath library */ using SafeMath for uint256; /** @dev eMTV token address */ address public EMTV_TOKEN_ADDRESS = 0x07a7ED332c595B53a317AfCEE50733Af571475e7; /** @dev Action prices */ uint256 public UpdatePrice = 1 ether; uint256 public DropTablePrice = 1 ether; uint256 public InsertIntoPrice = 1 ether; uint256 public DeleteFromPrice = 1 ether; uint256 public CreateTablePrice = 1 ether; uint256 public CreateDatabasePrice = 1 ether; /** * @dev Created databases */ mapping(address => address[]) public databaseAddresses; mapping(address => bytes32[]) public databaseNames; /** * @dev Used to check for duplicated databases' names */ mapping(address => mapping(bytes32 => bool)) private databaseUsedNames; /** * @dev Returns the databases owned by the requested address * @return _addresses The database addresses list * @return _names The database names list */ function databases(address _owner) external returns (address[] memory _addresses, bytes32[] memory _names) { return (databaseAddresses[_owner], databaseNames[_owner]); } /** * @dev Creates a new database instance * @return _database The newly created contract */ function create(bytes32 _name) external returns (address _database) { return _create(_name, msg.sender); } /** * @dev Creates a new database instance using tokens from another account * @return _database The newly created contract */ function createFrom(bytes32 _name, address _from) external returns (address _database) { return _create(_name, _from); } /** * @dev Withdraws all eMTVs to an address */ function withdraw(address _to) external onlyOwner { ERC20 token = ERC20(EMTV_TOKEN_ADDRESS); token.transfer(_to, token.balanceOf(address(this))); } /** * @dev Updates the price to update a row */ function updateUpdatePrice(uint256 _newPrice) external onlyOwner { UpdatePrice = _newPrice; emit UpdatePriceUpdated(_newPrice); } /** * @dev Updates the price to drop a table */ function updateDropTablePrice(uint256 _newPrice) external onlyOwner { DropTablePrice = _newPrice; emit DropTablePriceUpdated(_newPrice); } /** * @dev Updates the price to insert a row */ function updateInsertIntoPrice(uint256 _newPrice) external onlyOwner { InsertIntoPrice = _newPrice; emit InsertIntoPriceUpdated(_newPrice); } /** * @dev Updates the price to delete a row */ function updateDeleteFromPrice(uint256 _newPrice) external onlyOwner { DeleteFromPrice = _newPrice; emit DeleteFromPriceUpdated(_newPrice); } /** * @dev Updates the price to delete a row */ function updateCreateTablePrice(uint256 _newPrice) external onlyOwner { CreateTablePrice = _newPrice; emit CreateTablePriceUpdated(_newPrice); } /** * @dev Updates the price to create a new Database */ function updateCreateDatabasePrice(uint256 _newPrice) external onlyOwner { CreateDatabasePrice = _newPrice; emit CreateDatabasePriceUpdated(_newPrice); } /** * @dev Update the token address. This is here only for debugging porpuses! */ function updateTokenAddress(address _newAddress) external onlyOwner { EMTV_TOKEN_ADDRESS = _newAddress; emit TokenAddressUpdated(_newAddress); } /** * @dev Checks if an address can make a purchase */ function canPurchase(address _from, uint256 _price) public view returns (bool _canPurchase) { ERC20 token = ERC20(EMTV_TOKEN_ADDRESS); uint256 balance = token.balanceOf(_from); return balance.sub(_price) >= 0; } function _create(bytes32 _name, address _from) internal returns (address _database) { require(_name.length > 0, "A database must have a name"); require(_from != address(0x0), "Invalid owner address"); require(databaseUsedNames[_from][_name] == false, "Duplicate database name"); ERC20 token = ERC20(EMTV_TOKEN_ADDRESS); uint256 balance = token.balanceOf(_from); require(balance.sub(CreateDatabasePrice) >= 0, "Not enough tokens to create a new database"); bool result = token.transferFrom(_from, address(this), CreateDatabasePrice); require(result, "Transfer returned false"); Database db = new Database(address(this), _from); address dbAddress = address(db); databaseUsedNames[_from][_name] = true; databaseNames[_from].push(_name); databaseAddresses[_from].push(dbAddress); emit DatabaseCreated(_name, _from, address(db)); return address(db); } event DatabaseCreated(bytes32 _name, address _by, address _contract); event TokenAddressUpdated(address _newAddress); event UpdatePriceUpdated(uint256 _newPrice); event DropTablePriceUpdated(uint256 _newPrice); event InsertIntoPriceUpdated(uint256 _newPrice); event DeleteFromPriceUpdated(uint256 _newPrice); event CreateTablePriceUpdated(uint256 _newPrice); event CreateDatabasePriceUpdated(uint256 _newPrice); }
Checks if an address can make a purchase/
function canPurchase(address _from, uint256 _price) public view returns (bool _canPurchase) { ERC20 token = ERC20(EMTV_TOKEN_ADDRESS); uint256 balance = token.balanceOf(_from); return balance.sub(_price) >= 0; }
6,352,863
// SPDX-License-Identifier: AGPLv3 pragma solidity ^0.7.0; /** * @title Int96SafeMath * @dev Int96 math operations with safety checks that revert on error. */ library Int96SafeMath { int96 constant private _INT96_MIN = -2**95; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int96 a, int96 b, string memory errorMessage) internal pure returns (int96) { // 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 == _INT96_MIN), errorMessage); int96 c = a * b; require(c / a == b, errorMessage); 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(int96 a, int96 b, string memory errorMessage) internal pure returns (int96) { require(b != 0, errorMessage); require(!(b == -1 && a == _INT96_MIN), errorMessage); int96 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(int96 a, int96 b, string memory errorMessage) internal pure returns (int96) { int96 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), errorMessage); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int96 a, int96 b, string memory errorMessage) internal pure returns (int96) { int96 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), errorMessage); return c; } }
Returns the multiplication of two signed integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522
function mul(int96 a, int96 b, string memory errorMessage) internal pure returns (int96) { if (a == 0) { return 0; } require(!(a == -1 && b == _INT96_MIN), errorMessage); int96 c = a * b; require(c / a == b, errorMessage); return c; }
13,001,440
// SPDX-License-Identifier: None pragma solidity >=0.7.5; import "./Adminable.sol"; /// @title Module Registry Contract /// @author DEXAG, Inc. /// @notice This contract provides the logic for querying, maintaining, and updating Slingshot modules. /// @dev When a new module is deployed, it must be registered. If the logic for a particular /// DEX/AMM changes, a new module must be deployed and registered. contract ModuleRegistry is Adminable { /// @notice This is an index which indicates the validity of a module mapping(address => bool) public modulesIndex; /// @notice Slingshot.sol address address public slingshot; event ModuleRegistered(address moduleAddress); event ModuleUnregistered(address moduleAddress); event NewSlingshot(address oldAddress, address newAddress); /// @notice Use this function for post upgrade setup /// @param _admin Address to control admin functions function postUpgrade(address _admin) external onlyAdminIfInitialized { // skip when initialized if (!isInitialized()) initialize(_admin); // all other post upgrade setup below } /// @notice Initialization function for proxy setup /// @param _admin Address to control admin functions function initialize(address _admin) internal initializer { initializeAdmin(_admin); } /// @notice Checks if given address is a module /// @param _moduleAddress Address of the module in question /// @return true if address is module function isModule(address _moduleAddress) external view returns (bool) { return modulesIndex[_moduleAddress]; } /// @param _moduleAddress Address of the module to register function registerSwapModule(address _moduleAddress) external onlyAdmin { modulesIndex[_moduleAddress] = true; emit ModuleRegistered(_moduleAddress); } /// @param _moduleAddress Address of the module to unregister function unregisterSwapModule(address _moduleAddress) external onlyAdmin { delete modulesIndex[_moduleAddress]; emit ModuleRegistered(_moduleAddress); } /// @param _slingshot Slingshot.sol address implementation function setSlingshot(address _slingshot) external onlyAdmin { address oldAddress = slingshot; slingshot = _slingshot; emit NewSlingshot(oldAddress, _slingshot); } }
Checks if given address is a module _moduleAddress Address of the module in question return true if address is module
function isModule(address _moduleAddress) external view returns (bool) { return modulesIndex[_moduleAddress]; }
12,990,969
./partial_match/1/0xC74ECe7F996e9315386dD31B7291D55e83c1F98B/sources/OxOPool.sol
Gets the unpacked, packed ring data packedData The packed ring data
function getRingPackedData(uint packedData) public view returns (uint256, uint256, uint256){ uint256 p = packedData >> _BITWIDTH_BLOCK_NUM; return ( p >> _BITWIDTH_PARTICIPANTS, p & _BITMASK_PARTICIPANTS, packedData & _BITMASK_BLOCK_NUM ); }
2,885,182
./full_match/3/0x37ff2Dab3fc4323b304fD894D1e8df57E2CaD152/sources/browser/ERC721Beers.sol
NEW FUNCTION - SHOULD ONLY BE CALLABLE BY THE NFT CONTRACT ADMIn this function does not require a signature of the originAddress but of the owner originAddress the address the NFT will be extracted from destinationAddress the address of the ticketeer that will receive the NFT nftIndex the index of the NFT that will be returned to the tickeer Clear approvals from the previous owner emit Transfer(from, to, nftIndex);
function _collect(address originAddress, address destinationAddress, uint256 nftIndex) internal virtual { _beforeTokenTransfer(originAddress, destinationAddress, nftIndex); _approve(address(0), nftIndex); _holderTokens[originAddress].remove(nftIndex); _holderTokens[destinationAddress].add(nftIndex); _tokenOwners.set(nftIndex, destinationAddress); emit Collect(originAddress, destinationAddress, nftIndex); }
14,133,213
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IStakingPools interface IStakingPools { function claim(uint256 _poolId) external; function deposit(uint256 _poolId, uint256 _depositAmount) external; function exit(uint256 _poolId) external; function getPoolRewardWeight(uint256 _poolId) external view returns (uint256); function getPoolToken(uint256 _poolId) external view returns (address); function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256); function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256); function withdraw(uint256 _poolId, uint256 _withdrawAmount) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @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); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function apiVersion() external pure returns (string memory); function withdraw(uint256 shares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay = 0; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: AlchemixStakingStrategy.sol contract AlchemixStakingStrategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 _poolId = 1; //Initiate staking gov interface IStakingPools public pool = IStakingPools(0xAB8e74017a8Cc7c15FFcCd726603790d26d7DeCa); constructor(address _vault) public BaseStrategy(_vault) { //Approve staking contract to spend ALCX tokens want.safeApprove(address(pool), type(uint256).max); } function name() external view override returns (string memory) { return "StrategyAlchemixStaking"; } // returns balance of ALCX function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } //Returns staked ALCX value function balanceOfStake() public view returns (uint256) { return pool.getStakeTotalDeposited(address(this), _poolId); } function pendingReward() public view virtual returns (uint256) { return pool.getStakeTotalUnclaimed(address(this), _poolId); } function estimatedTotalAssets() public view override returns (uint256) { //Add the vault tokens + staked tokens from 1inch governance contract return balanceOfWant().add(balanceOfStake()).add(pendingReward()); } function _deposit(uint256 _depositAmount) internal { pool.deposit(_poolId, _depositAmount); } function _withdraw(uint256 _withdrawAmount) internal { pool.withdraw(_poolId, _withdrawAmount); } function getReward() internal virtual { pool.claim(_poolId); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // We might need to return want to the vault if (_debtOutstanding > 0) { uint256 _amountFreed = 0; (_amountFreed, _loss) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_amountFreed, _debtOutstanding); } uint256 balanceOfWantBefore = balanceOfWant(); getReward(); _profit = balanceOfWant().sub(balanceOfWantBefore); } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 _wantAvailable = balanceOfWant(); if (_debtOutstanding >= _wantAvailable) { return; } uint256 toInvest = _wantAvailable.sub(_debtOutstanding); if (toInvest > 0) { _deposit(toInvest); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // NOTE: Maintain invariant `want.balanceOf(this) >= _liquidatedAmount` // NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded` uint256 balanceWant = balanceOfWant(); uint256 balanceStaked = balanceOfStake(); if (_amountNeeded > balanceWant) { // unstake needed amount _withdraw((Math.min(balanceStaked, _amountNeeded - balanceWant))); } // Since we might free more than needed, let's send back the min _liquidatedAmount = Math.min(balanceOfWant(), _amountNeeded); } function prepareMigration(address _newStrategy) internal virtual override { //This claims rewards and withdraws deposited ALCX pool.exit(_poolId); } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) function protectedTokens() internal view override returns (address[] memory) {} }
Returns staked ALCX value
function balanceOfStake() public view returns (uint256) { return pool.getStakeTotalDeposited(address(this), _poolId); }
390,448
pragma solidity ^0.4.13; interface IAffiliateList { /** * @dev Sets the given address as an affiliate. * If the address is not currently an affiliate, startTimestamp is required * and endTimestamp is optional. * If the address is already registered as an affiliate, both values are optional. * @param startTimestamp Timestamp when the address became/becomes an affiliate. * @param endTimestamp Timestamp when the address will no longer be an affiliate. */ function set(address addr, uint startTimestamp, uint endTimestamp) external; /** * @dev Retrieves the start and end timestamps for the given address. * It is sufficient to check the start value to determine if the address * is an affiliate (start will be greater than zero). */ function get(address addr) external view returns (uint start, uint end); /** * @dev Returns true if the address is, was, or will be an affiliate at the given time. */ function inListAsOf(address addr, uint time) external view returns (bool); } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract IInvestorList { string public constant ROLE_REGD = "regd"; string public constant ROLE_REGCF = "regcf"; string public constant ROLE_REGS = "regs"; string public constant ROLE_UNKNOWN = "unknown"; function inList(address addr) public view returns (bool); function addAddress(address addr, string role) public; function getRole(address addr) public view returns (string); function hasRole(address addr, string role) public view returns (bool); } contract Ownable { address public owner; address public 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 Starts the 2-step process of changing ownership. The new owner * must then call `acceptOwnership()`. */ function changeOwner(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev Completes the process of transferring ownership to a new owner. */ function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; newOwner = 0; } } } contract AffiliateList is Ownable, IAffiliateList { event AffiliateAdded(address addr, uint startTimestamp, uint endTimestamp); event AffiliateUpdated(address addr, uint startTimestamp, uint endTimestamp); mapping (address => uint) public affiliateStart; mapping (address => uint) public affiliateEnd; function set(address addr, uint startTimestamp, uint endTimestamp) public onlyOwner { require(addr != address(0)); uint existingStart = affiliateStart[addr]; if(existingStart == 0) { // this is a new address require(startTimestamp != 0); affiliateStart[addr] = startTimestamp; if(endTimestamp != 0) { require(endTimestamp > startTimestamp); affiliateEnd[addr] = endTimestamp; } emit AffiliateAdded(addr, startTimestamp, endTimestamp); } else { // this address was previously registered if(startTimestamp == 0) { // don't update the start timestamp if(endTimestamp == 0) { affiliateStart[addr] = 0; affiliateEnd[addr] = 0; } else { require(endTimestamp > existingStart); } } else { // update the start timestamp affiliateStart[addr] = startTimestamp; if(endTimestamp != 0) { require(endTimestamp > startTimestamp); } } affiliateEnd[addr] = endTimestamp; emit AffiliateUpdated(addr, startTimestamp, endTimestamp); } } function get(address addr) public view returns (uint start, uint end) { return (affiliateStart[addr], affiliateEnd[addr]); } function inListAsOf(address addr, uint time) public view returns (bool) { uint start; uint end; (start, end) = get(addr); if(start == 0) { return false; } if(time < start) { return false; } if(end != 0 && time >= end) { return false; } return true; } } contract InvestorList is Ownable, IInvestorList { event AddressAdded(address addr, string role); event AddressRemoved(address addr, string role); mapping (address => string) internal investorList; /** * @dev Throws if called by any account that's not investorListed. * @param role string */ modifier validRole(string role) { require( keccak256(bytes(role)) == keccak256(bytes(ROLE_REGD)) || keccak256(bytes(role)) == keccak256(bytes(ROLE_REGCF)) || keccak256(bytes(role)) == keccak256(bytes(ROLE_REGS)) || keccak256(bytes(role)) == keccak256(bytes(ROLE_UNKNOWN)) ); _; } /** * @dev Getter to determine if address is in investorList. * @param addr address * @return true if the address was added to the investorList, false if the address was already in the investorList */ function inList(address addr) public view returns (bool) { if (bytes(investorList[addr]).length != 0) { return true; } else { return false; } } /** * @dev Getter for address role if address is in list. * @param addr address * @return string for address role */ function getRole(address addr) public view returns (string) { require(inList(addr)); return investorList[addr]; } /** * @dev Returns a boolean indicating if the given address is in the list * with the given role. * @param addr address to check * @param role role to check * @ return boolean for whether the address is in the list with the role */ function hasRole(address addr, string role) public view returns (bool) { return keccak256(bytes(role)) == keccak256(bytes(investorList[addr])); } /** * @dev Add single address to the investorList. * @param addr address * @param role string */ function addAddress(address addr, string role) onlyOwner validRole(role) public { investorList[addr] = role; emit AddressAdded(addr, role); } /** * @dev Add multiple addresses to the investorList. * @param addrs addresses * @param role string */ function addAddresses(address[] addrs, string role) onlyOwner validRole(role) public { for (uint256 i = 0; i < addrs.length; i++) { addAddress(addrs[i], role); } } /** * @dev Remove single address from the investorList. * @param addr address */ function removeAddress(address addr) onlyOwner public { // removeRole(addr, ROLE_WHITELISTED); require(inList(addr)); string memory role = investorList[addr]; investorList[addr] = ""; emit AddressRemoved(addr, role); } /** * @dev Remove multiple addresses from the investorList. * @param addrs addresses */ function removeAddresses(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { if (inList(addrs[i])) { removeAddress(addrs[i]); } } } } 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; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ISecurityController { function balanceOf(address _a) public view returns (uint); function totalSupply() public view returns (uint); function isTransferAuthorized(address _from, address _to) public view returns (bool); function setTransferAuthorized(address from, address to, uint expiry) public; function transfer(address _from, address _to, uint _value) public returns (bool success); function transferFrom(address _spender, address _from, address _to, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint); function approve(address _owner, address _spender, uint _value) public returns (bool success); function increaseApproval(address _owner, address _spender, uint _addedValue) public returns (bool success); function decreaseApproval(address _owner, address _spender, uint _subtractedValue) public returns (bool success); function burn(address _owner, uint _amount) public; function ledgerTransfer(address from, address to, uint val) public; function setLedger(address _ledger) public; function setSale(address _sale) public; function setToken(address _token) public; function setAffiliateList(address _affiliateList) public; } contract SecurityController is ISecurityController, Ownable { ISecurityLedger public ledger; ISecurityToken public token; ISecuritySale public sale; IInvestorList public investorList; ITransferAuthorizations public transferAuthorizations; IAffiliateList public affiliateList; uint public lockoutPeriod = 10 * 60 * 60; // length in seconds of the lockout period // restrict who can grant transfer authorizations mapping(address => bool) public transferAuthPermission; constructor() public { } function setTransferAuthorized(address from, address to, uint expiry) public { // Must be called from address in the transferAuthPermission mapping require(transferAuthPermission[msg.sender]); // don't allow 'from' to be zero require(from != 0); // verify expiry is in future, but not more than 30 days if(expiry > 0) { require(expiry > block.timestamp); require(expiry <= (block.timestamp + 30 days)); } transferAuthorizations.set(from, to, expiry); } // functions below this line are onlyOwner function setLockoutPeriod(uint _lockoutPeriod) public onlyOwner { lockoutPeriod = _lockoutPeriod; } function setToken(address _token) public onlyOwner { token = ISecurityToken(_token); } function setLedger(address _ledger) public onlyOwner { ledger = ISecurityLedger(_ledger); } function setSale(address _sale) public onlyOwner { sale = ISecuritySale(_sale); } function setInvestorList(address _investorList) public onlyOwner { investorList = IInvestorList(_investorList); } function setTransferAuthorizations(address _transferAuthorizations) public onlyOwner { transferAuthorizations = ITransferAuthorizations(_transferAuthorizations); } function setAffiliateList(address _affiliateList) public onlyOwner { affiliateList = IAffiliateList(_affiliateList); } function setDependencies(address _token, address _ledger, address _sale, address _investorList, address _transferAuthorizations, address _affiliateList) public onlyOwner { token = ISecurityToken(_token); ledger = ISecurityLedger(_ledger); sale = ISecuritySale(_sale); investorList = IInvestorList(_investorList); transferAuthorizations = ITransferAuthorizations(_transferAuthorizations); affiliateList = IAffiliateList(_affiliateList); } function setTransferAuthPermission(address agent, bool hasPermission) public onlyOwner { require(agent != address(0)); transferAuthPermission[agent] = hasPermission; } modifier onlyToken() { require(msg.sender == address(token)); _; } modifier onlyLedger() { require(msg.sender == address(ledger)); _; } // public functions function totalSupply() public view returns (uint) { return ledger.totalSupply(); } function balanceOf(address _a) public view returns (uint) { return ledger.balanceOf(_a); } function allowance(address _owner, address _spender) public view returns (uint) { return ledger.allowance(_owner, _spender); } function isTransferAuthorized(address _from, address _to) public view returns (bool) { // A `from` address could have both an allowance for the `to` address // and a global allowance (to the zero address). We pick the maximum // of the two. uint expiry = transferAuthorizations.get(_from, _to); uint globalExpiry = transferAuthorizations.get(_from, 0); if(globalExpiry > expiry) { expiry = globalExpiry; } return expiry > block.timestamp; } /** * @dev Determines whether the given transfer is possible. Returns multiple * boolean flags specifying how the transfer must occur. * This is kept public to provide for testing and subclasses overriding behavior. * @param _from Address the tokens are being transferred from * @param _to Address the tokens are being transferred to * @param _value Number of tokens that would be transferred * @param lockoutTime A point in time, specified in epoch time, that specifies * the lockout period (typically 1 year before now). * @return canTransfer Whether the transfer can occur at all. * @return useLockoutTime Whether the lockoutTime should be used to determine which tokens to transfer. * @return newTokensAreRestricted Whether the transferred tokens should be marked as restricted. * @return preservePurchaseDate Whether the purchase date on the tokens should be preserved, or reset to 'now'. */ function checkTransfer(address _from, address _to, uint _value, uint lockoutTime) public returns (bool canTransfer, bool useLockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) { // DEFAULT BEHAVIOR: // // If there exists a Transfer Agent authorization, allow transfer regardless // // All transfers from an affiliate must be authorized by Transfer Agent // - tokens become restricted // // From Reg S to Reg S: allowable, regardless of holding period // // otherwise must meet holding period // presently this isn't used, so always setting to false to avoid warning preservePurchaseDate = false; bool transferIsAuthorized = isTransferAuthorized(_from, _to); bool fromIsAffiliate = affiliateList.inListAsOf(_from, block.timestamp); bool toIsAffiliate = affiliateList.inListAsOf(_to, block.timestamp); if(transferIsAuthorized) { canTransfer = true; if(fromIsAffiliate || toIsAffiliate) { newTokensAreRestricted = true; } // useLockoutTime will remain false // preservePurchaseDate will remain false } else if(!fromIsAffiliate) { // see if both are Reg S if(investorList.hasRole(_from, investorList.ROLE_REGS()) && investorList.hasRole(_to, investorList.ROLE_REGS())) { canTransfer = true; // newTokensAreRestricted will remain false // useLockoutTime will remain false // preservePurchaseDate will remain false } else { if(ledger.transferDryRun(_from, _to, _value, lockoutTime) == _value) { canTransfer = true; useLockoutTime = true; // newTokensAreRestricted will remain false // preservePurchaseDate will remain false } } } } // functions below this line are onlyLedger // let the ledger send transfer events (the most obvious case // is when we mint directly to the ledger and need the Transfer() // events to appear in the token) function ledgerTransfer(address from, address to, uint val) public onlyLedger { token.controllerTransfer(from, to, val); } // functions below this line are onlyToken function transfer(address _from, address _to, uint _value) public onlyToken returns (bool success) { uint lockoutTime = block.timestamp - lockoutPeriod; bool canTransfer; bool useLockoutTime; bool newTokensAreRestricted; bool preservePurchaseDate; (canTransfer, useLockoutTime, newTokensAreRestricted, preservePurchaseDate) = checkTransfer(_from, _to, _value, lockoutTime); if(!canTransfer) { return false; } uint overrideLockoutTime = lockoutTime; if(!useLockoutTime) { overrideLockoutTime = 0; } return ledger.transfer(_from, _to, _value, overrideLockoutTime, newTokensAreRestricted, preservePurchaseDate); } function transferFrom(address _spender, address _from, address _to, uint _value) public onlyToken returns (bool success) { uint lockoutTime = block.timestamp - lockoutPeriod; bool canTransfer; bool useLockoutTime; bool newTokensAreRestricted; bool preservePurchaseDate; (canTransfer, useLockoutTime, newTokensAreRestricted, preservePurchaseDate) = checkTransfer(_from, _to, _value, lockoutTime); if(!canTransfer) { return false; } uint overrideLockoutTime = lockoutTime; if(!useLockoutTime) { overrideLockoutTime = 0; } return ledger.transferFrom(_spender, _from, _to, _value, overrideLockoutTime, newTokensAreRestricted, preservePurchaseDate); } function approve(address _owner, address _spender, uint _value) public onlyToken returns (bool success) { return ledger.approve(_owner, _spender, _value); } function increaseApproval (address _owner, address _spender, uint _addedValue) public onlyToken returns (bool success) { return ledger.increaseApproval(_owner, _spender, _addedValue); } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) public onlyToken returns (bool success) { return ledger.decreaseApproval(_owner, _spender, _subtractedValue); } function burn(address _owner, uint _amount) public onlyToken { ledger.burn(_owner, _amount); } } interface ISecurityLedger { function balanceOf(address _a) external view returns (uint); function totalSupply() external view returns (uint); function transferDryRun(address _from, address _to, uint amount, uint lockoutTime) external returns (uint transferrableCount); function transfer(address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) external returns (bool success); function transferFrom(address _spender, address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint); function approve(address _owner, address _spender, uint _value) external returns (bool success); function increaseApproval(address _owner, address _spender, uint _addedValue) external returns (bool success); function decreaseApproval(address _owner, address _spender, uint _subtractedValue) external returns (bool success); function burn(address _owner, uint _amount) external; function setController(address _controller) external; } contract SecurityLedger is Ownable { using SafeMath for uint256; struct TokenLot { uint amount; uint purchaseDate; bool restricted; } mapping(address => TokenLot[]) public tokenLotsOf; SecurityController public controller; mapping(address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint public totalSupply; uint public mintingNonce; bool public mintingStopped; constructor() public { } // functions below this line are onlyOwner function setController(address _controller) public onlyOwner { controller = SecurityController(_controller); } function stopMinting() public onlyOwner { mintingStopped = true; } //TODO: not sure if this function should stay long term function mint(address addr, uint value, uint timestamp) public onlyOwner { require(!mintingStopped); uint time = timestamp; if(time == 0) { time = block.timestamp; } balanceOf[addr] = balanceOf[addr].add(value); tokenLotsOf[addr].push(TokenLot(value, time, true)); controller.ledgerTransfer(0, addr, value); totalSupply = totalSupply.add(value); } function multiMint(uint nonce, uint256[] bits, uint timestamp) external onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce = mintingNonce.add(1); uint256 lomask = (1 << 96) - 1; uint created = 0; uint time = timestamp; if(time == 0) { time = block.timestamp; } for (uint i = 0; i < bits.length; i++) { address addr = address(bits[i]>>96); uint value = bits[i] & lomask; balanceOf[addr] = balanceOf[addr].add(value); tokenLotsOf[addr].push(TokenLot(value, time, true)); controller.ledgerTransfer(0, addr, value); created = created.add(value); } totalSupply = totalSupply.add(created); } // send received tokens to anyone function sendReceivedTokens(address token, address sender, uint amount) public onlyOwner { ERC20Basic t = ERC20Basic(token); require(t.transfer(sender, amount)); } // functions below this line are onlyController modifier onlyController() { require(msg.sender == address(controller)); _; } /** * @dev Walks through the list of TokenLots for the given address, attempting to find * `amount` tokens that can be transferred. It uses the given `lockoutTime` if * the supplied value is not zero. If `removeTokens` is true the tokens are * actually removed from the address, otherwise this function acts as a dry run. * The value returned is the actual number of transferrable tokens found, up to * the maximum value of `amount`. */ function walkTokenLots(address from, address to, uint amount, uint lockoutTime, bool removeTokens, bool newTokensAreRestricted, bool preservePurchaseDate) internal returns (uint numTransferrableTokens) { TokenLot[] storage fromTokenLots = tokenLotsOf[from]; for(uint i=0; i<fromTokenLots.length; i++) { TokenLot storage lot = fromTokenLots[i]; uint lotAmount = lot.amount; // skip if there are no available tokens if(lotAmount == 0) { continue; } if(lockoutTime > 0) { // skip if it is more recent than the lockout period AND it's restricted if(lot.restricted && lot.purchaseDate > lockoutTime) { continue; } } uint remaining = amount.sub(numTransferrableTokens); if(lotAmount >= remaining) { numTransferrableTokens = numTransferrableTokens.add(remaining); if(removeTokens) { lot.amount = lotAmount.sub(remaining); if(to != address(0)) { if(preservePurchaseDate) { tokenLotsOf[to].push(TokenLot(remaining, lot.purchaseDate, newTokensAreRestricted)); } else { tokenLotsOf[to].push(TokenLot(remaining, block.timestamp, newTokensAreRestricted)); } } } break; } // If we're here, then amount in this lot is not yet enough. // Take all of it. numTransferrableTokens = numTransferrableTokens.add(lotAmount); if(removeTokens) { lot.amount = 0; if(to != address(0)) { if(preservePurchaseDate) { tokenLotsOf[to].push(TokenLot(lotAmount, lot.purchaseDate, newTokensAreRestricted)); } else { tokenLotsOf[to].push(TokenLot(lotAmount, block.timestamp, newTokensAreRestricted)); } } } } } function transferDryRun(address from, address to, uint amount, uint lockoutTime) public onlyController returns (uint) { return walkTokenLots(from, to, amount, lockoutTime, false, false, false); } function transfer(address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) public onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; // ensure number of tokens removed from TokenLots is as expected uint tokensTransferred = walkTokenLots(_from, _to, _value, lockoutTime, true, newTokensAreRestricted, preservePurchaseDate); require(tokensTransferred == _value); // adjust balances balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); return true; } function transferFrom(address _spender, address _from, address _to, uint _value, uint lockoutTime, bool newTokensAreRestricted, bool preservePurchaseDate) public onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; // ensure there is enough allowance uint allowed = allowance[_from][_spender]; if (allowed < _value) return false; // ensure number of tokens removed from TokenLots is as expected uint tokensTransferred = walkTokenLots(_from, _to, _value, lockoutTime, true, newTokensAreRestricted, preservePurchaseDate); require(tokensTransferred == _value); // adjust balances balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][_spender] = allowed.sub(_value); return true; } function approve(address _owner, address _spender, uint _value) public onlyController returns (bool success) { // require user to set to zero before resetting to nonzero if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; } allowance[_owner][_spender] = _value; return true; } function increaseApproval (address _owner, address _spender, uint _addedValue) public onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; allowance[_owner][_spender] = oldValue.add(_addedValue); return true; } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) public onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; if (_subtractedValue > oldValue) { allowance[_owner][_spender] = 0; } else { allowance[_owner][_spender] = oldValue.sub(_subtractedValue); } return true; } function burn(address _owner, uint _amount) public onlyController { require(balanceOf[_owner] >= _amount); balanceOf[_owner] = balanceOf[_owner].sub(_amount); // remove tokens from TokenLots // (i.e. transfer them to 0) walkTokenLots(_owner, address(0), _amount, 0, true, false, false); totalSupply = totalSupply.sub(_amount); } } interface ISecuritySale { function setLive(bool newLiveness) external; function setInvestorList(address _investorList) external; } contract SecuritySale is Ownable { bool public live; // sale is live right now IInvestorList public investorList; // approved contributors event SaleLive(bool liveness); event EtherIn(address from, uint amount); event StartSale(); event EndSale(); constructor() public { live = false; } function setInvestorList(address _investorList) public onlyOwner { investorList = IInvestorList(_investorList); } function () public payable { require(live); require(investorList.inList(msg.sender)); emit EtherIn(msg.sender, msg.value); } // set liveness function setLive(bool newLiveness) public onlyOwner { if(live && !newLiveness) { live = false; emit EndSale(); } else if(!live && newLiveness) { live = true; emit StartSale(); } } // withdraw all of the Ether to owner function withdraw() public onlyOwner { msg.sender.transfer(address(this).balance); } // withdraw some of the Ether to owner function withdrawSome(uint value) public onlyOwner { require(value <= address(this).balance); msg.sender.transfer(value); } // withdraw tokens to owner function withdrawTokens(address token) public onlyOwner { ERC20Basic t = ERC20Basic(token); require(t.transfer(msg.sender, t.balanceOf(this))); } // send received tokens to anyone function sendReceivedTokens(address token, address sender, uint amount) public onlyOwner { ERC20Basic t = ERC20Basic(token); require(t.transfer(sender, amount)); } } interface ISecurityToken { function balanceOf(address addr) external view returns(uint); function transfer(address to, uint amount) external returns(bool); function controllerTransfer(address _from, address _to, uint _value) external; } contract SecurityToken is Ownable{ using SafeMath for uint256; ISecurityController public controller; // these public fields are set once in constructor string public name; string public symbol; uint8 public decimals; event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } // functions below this line are onlyOwner function setName(string _name) public onlyOwner { name = _name; } function setSymbol(string _symbol) public onlyOwner { symbol = _symbol; } function setController(address _c) public onlyOwner { controller = ISecurityController(_c); } // send received tokens to anyone function sendReceivedTokens(address token, address sender, uint amount) public onlyOwner { ERC20Basic t = ERC20Basic(token); require(t.transfer(sender, amount)); } // functions below this line are public function balanceOf(address a) public view returns (uint) { return controller.balanceOf(a); } function totalSupply() public view returns (uint) { return controller.totalSupply(); } function allowance(address _owner, address _spender) public view returns (uint) { return controller.allowance(_owner, _spender); } function burn(uint _amount) public { controller.burn(msg.sender, _amount); emit Transfer(msg.sender, 0x0, _amount); } // functions below this line are onlyPayloadSize // TODO: investigate this security optimization more modifier onlyPayloadSize(uint numwords) { assert(msg.data.length >= numwords.mul(32).add(4)); _; } function isTransferAuthorized(address _from, address _to) public onlyPayloadSize(2) view returns (bool) { return controller.isTransferAuthorized(_from, _to); } function transfer(address _to, uint _value) public onlyPayloadSize(2) returns (bool success) { if (controller.transfer(msg.sender, _to, _value)) { emit Transfer(msg.sender, _to, _value); return true; } return false; } function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3) returns (bool success) { if (controller.transferFrom(msg.sender, _from, _to, _value)) { emit Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) onlyPayloadSize(2) public returns (bool success) { if (controller.approve(msg.sender, _spender, _value)) { emit Approval(msg.sender, _spender, _value); return true; } return false; } function increaseApproval (address _spender, uint _addedValue) public onlyPayloadSize(2) returns (bool success) { if (controller.increaseApproval(msg.sender, _spender, _addedValue)) { uint newval = controller.allowance(msg.sender, _spender); emit Approval(msg.sender, _spender, newval); return true; } return false; } function decreaseApproval (address _spender, uint _subtractedValue) public onlyPayloadSize(2) returns (bool success) { if (controller.decreaseApproval(msg.sender, _spender, _subtractedValue)) { uint newval = controller.allowance(msg.sender, _spender); emit Approval(msg.sender, _spender, newval); return true; } return false; } // functions below this line are onlyController modifier onlyController() { assert(msg.sender == address(controller)); _; } function controllerTransfer(address _from, address _to, uint _value) public onlyController { emit Transfer(_from, _to, _value); } function controllerApprove(address _owner, address _spender, uint _value) public onlyController { emit Approval(_owner, _spender, _value); } } interface ITransferAuthorizations { function setController(address _controller) external; function get(address from, address to) external view returns (uint); function set(address from, address to, uint expiry) external; } contract TransferAuthorizations is Ownable, ITransferAuthorizations { /** * @dev The first key is the `from` address. The second key is the `to` address. * The uint value of the mapping is the epoch time (seconds since 1/1/1970) * of the expiration of the approved transfer. */ mapping(address => mapping(address => uint)) public authorizations; /** * @dev This controller is the only contract allowed to call the `set` function. */ address public controller; event TransferAuthorizationSet(address from, address to, uint expiry); function setController(address _controller) public onlyOwner { controller = _controller; } modifier onlyController() { assert(msg.sender == controller); _; } /** * @dev Sets the authorization for a transfer to occur between the 'from' and * 'to' addresses, to expire at the 'expiry' time. * @param from The address from which funds would be transferred. * @param to The address to which funds would be transferred. This can be * the zero address to allow transfers to any address. * @param expiry The epoch time (seconds since 1/1/1970) at which point this * authorization will no longer be valid. */ function set(address from, address to, uint expiry) public onlyController { require(from != 0); authorizations[from][to] = expiry; emit TransferAuthorizationSet(from, to, expiry); } /** * @dev Returns the expiration time for the transfer authorization between the * given addresses. Returns 0 if not allowed. * @param from The address from which funds would be transferred. * @param to The address to which funds would be transferred. This can be * the zero address to allow transfers to any address. */ function get(address from, address to) public view returns (uint) { return authorizations[from][to]; } }
Walks through the list of TokenLots for the given address, attempting to find `amount` tokens that can be transferred. It uses the given `lockoutTime` if the supplied value is not zero. If `removeTokens` is true the tokens are actually removed from the address, otherwise this function acts as a dry run. The value returned is the actual number of transferrable tokens found, up to the maximum value of `amount`./ skip if there are no available tokens skip if it is more recent than the lockout period AND it's restricted
function walkTokenLots(address from, address to, uint amount, uint lockoutTime, bool removeTokens, bool newTokensAreRestricted, bool preservePurchaseDate) internal returns (uint numTransferrableTokens) { TokenLot[] storage fromTokenLots = tokenLotsOf[from]; for(uint i=0; i<fromTokenLots.length; i++) { TokenLot storage lot = fromTokenLots[i]; uint lotAmount = lot.amount; if(lotAmount == 0) { continue; } if(lockoutTime > 0) { if(lot.restricted && lot.purchaseDate > lockoutTime) { continue; } } uint remaining = amount.sub(numTransferrableTokens); if(lotAmount >= remaining) { numTransferrableTokens = numTransferrableTokens.add(remaining); if(removeTokens) { lot.amount = lotAmount.sub(remaining); if(to != address(0)) { if(preservePurchaseDate) { tokenLotsOf[to].push(TokenLot(remaining, lot.purchaseDate, newTokensAreRestricted)); } else { tokenLotsOf[to].push(TokenLot(remaining, block.timestamp, newTokensAreRestricted)); } } } break; } if(removeTokens) { lot.amount = 0; if(to != address(0)) { if(preservePurchaseDate) { tokenLotsOf[to].push(TokenLot(lotAmount, lot.purchaseDate, newTokensAreRestricted)); } else { tokenLotsOf[to].push(TokenLot(lotAmount, block.timestamp, newTokensAreRestricted)); } } } } }
213,065
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; /** * @title Benchmarks */ contract Benchmarks { bytes32 singleProp; mapping(bytes32 => bytes32) public benchmarkingMap; bytes32[] public mapKeys; mapping(bytes32 => uint256[]) public bigArray; uint256 public counter; /** * Triggers the execution of a single SSTORE opcode * @dev Stores to provided variable into storage. Example variable: 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97 * @param _singleProp value to store */ function twoSSTOREs(bytes32 _singleProp) public { singleProp = _singleProp; counter++; } /** * Triggers the execution of the MLOAD opcode. Loads the stored variable from storage * @dev Return value * @return value of 'singleProp' */ function singleMLOAD() public view returns (bytes32) { return singleProp; } /** * Stores N number of pseudo randomly generated bytes32 variables to a mapping. Triggers 2*N number of SSTORE (create) */ function sstoreCreate(uint256 n) public { for (uint256 i = 0; i < n; i++) { bytes32 pseudoRandom = keccak256(abi.encodePacked(bytes32(i), block.number)); benchmarkingMap[pseudoRandom] = pseudoRandom; mapKeys.push(pseudoRandom); } counter++; } /** * Updates N number of bytes32 variables. Triggers N number of SSTORE (update) * IMPORTANT! N must be lower than the number of sstoreCreates's performed in the contract so far! */ function sstoreUpdate(uint256 n) public { require(n <= mapKeys.length, "not enough keys have been generated"); for (uint256 i = 0; i < n; i++) { bytes32 pseudoRandom = keccak256(abi.encodePacked(bytes32(i), block.number)); benchmarkingMap[mapKeys[i]] = pseudoRandom; } counter++; } /** * Stores arbitrary array of bytes32 at a pseudo random key. * This means that the SSTORE executed is Create (not Update) */ function bigSSTORE(uint256[] memory data) public { bytes32 pseudoRandomKey = keccak256(abi.encodePacked(block.number)); bigArray[pseudoRandomKey] = data; counter++; } function loadTx(uint256 n) public { singleProp = keccak256(abi.encodePacked(bytes32(n), block.timestamp)); for (uint256 i = 0; i < n; i++) { bytes32 loadProp = singleProp; } counter++; } }
Triggers the execution of a single SSTORE opcode Stores to provided variable into storage. Example variable: 0xf2eeb729e636a8cb783be044acf6b7b1e2c5863735b60d6daae84c366ee87d97 _singleProp value to store/
function twoSSTOREs(bytes32 _singleProp) public { singleProp = _singleProp; counter++; }
12,985,472
pragma solidity 0.5.16; import "./openzeppelin/Address.sol"; import "./openzeppelin/SafeMath.sol"; import "./interfaces/ILiquidityPoolV1Converter.sol"; import "./interfaces/ILiquidityPoolV2Converter.sol"; import "./interfaces/ISmartToken.sol"; import "./interfaces/IERC20Token.sol"; import "./interfaces/IWrbtcERC20.sol"; import "./interfaces/ISovrynSwapNetwork.sol"; import "./interfaces/ISovrynSwapFormula.sol"; import "./interfaces/IContractRegistry.sol"; import "./ContractRegistryClient.sol"; import "./mockups/LiquidityMining.sol"; import "./interfaces/ILoanToken.sol"; contract RBTCWrapperProxy is ContractRegistryClient { using Address for address; using SafeMath for uint256; address public wrbtcTokenAddress; address public sovrynSwapNetworkAddress; LiquidityMining public liquidityMiningContract; /** * @dev triggered after liquidity is added * * @param _provider liquidity provider * @param _reserveAmount provided reserve token amount * @param _poolTokenAmount minted pool token amount */ event LiquidityAdded( address indexed _provider, uint256 _reserveAmount, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is added to LiquidityPoolConverter V1 * * @param _provider liquidity provider * @param _reserveTokens provided reserve token * @param _reserveAmounts provided reserve token amount * @param _poolTokenAmount minted pool token amount */ event LiquidityAddedToV1( address indexed _provider, IERC20Token[] _reserveTokens, uint256[] _reserveAmounts, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is removed * * @param _provider liquidity provider * @param _reserveAmount added reserve token amount * @param _poolTokenAmount burned pool token amount */ event LiquidityRemoved( address indexed _provider, uint256 _reserveAmount, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is removed from LiquidityPoolConverter V1 * * @param _provider liquidity provider * @param _reserveTokens added reserve tokens * @param _reserveAmounts added reserve token amounts */ event LiquidityRemovedFromV1( address indexed _provider, IERC20Token[] _reserveTokens, uint256[] _reserveAmounts, uint256 _poolTokenAmount ); /** * @dev triggered after liquidity is removed * * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _sourceTokenAmount amount to convert from, in the source token * @param _targetTokenAmount amount of tokens received from the conversion, in the target token * @param _path conversion path between two tokens in the network */ event TokenConverted( address indexed _beneficiary, uint256 indexed _sourceTokenAmount, uint256 indexed _targetTokenAmount, IERC20Token[] _path ); /** * @dev triggered after loan tokens are minted * @param user the user address * @param poolTokenAmount the minted amount of pool tokens * @param assetAmount the deposited amount of underlying asset tokens */ event LoanTokensMinted( address indexed user, uint256 poolTokenAmount, uint256 assetAmount ); /** * @dev triggered after loan tokens are minted * @param user the user address * @param poolTokenAmount the burnt amount of pool tokens * @param assetAmount the withdrawn amount of underlying asset tokens */ event LoanTokensBurnt( address indexed user, uint256 poolTokenAmount, uint256 assetAmount ); /** * @dev To check if ddress is contract address */ modifier checkAddress(address address_) { require(address_.isContract(), "The address is not a contract"); _; } constructor( address _wrbtcTokenAddress, address _sovrynSwapNetworkAddress, IContractRegistry _registry, address liquidityMiningAddress ) public ContractRegistryClient(_registry) checkAddress(_wrbtcTokenAddress) checkAddress(_sovrynSwapNetworkAddress) { wrbtcTokenAddress = _wrbtcTokenAddress; sovrynSwapNetworkAddress = _sovrynSwapNetworkAddress; liquidityMiningContract = LiquidityMining(liquidityMiningAddress); } function() external payable { require(wrbtcTokenAddress == msg.sender, "Only can receive rBTC from WRBTC contract"); } /** * @dev * The process: * 1.Accepts RBTC * 2.Sends RBTC to WRBTC contract in order to wrap RBTC to WRBTC * 3.Calls 'addLiquidity' on LiquidityPoolConverter contract * 4.Transfers pool tokens to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _reserveAddress address of the reserve to add to the pool * @param _amount amount of liquidity to add * @param _minReturn minimum return-amount of reserve tokens * * @return amount of pool tokens minted */ function addLiquidityToV2( address _liquidityPoolConverterAddress, address _reserveAddress, uint256 _amount, uint256 _minReturn ) public payable checkAddress(_liquidityPoolConverterAddress) returns(uint256) { ILiquidityPoolV2Converter _liquidityPoolConverter = ILiquidityPoolV2Converter(_liquidityPoolConverterAddress); IERC20Token reserveToken = IERC20Token(_reserveAddress); ISmartToken _poolToken = _liquidityPoolConverter.poolToken(reserveToken); //wrap rbtc if required if(_reserveAddress == wrbtcTokenAddress){ require(_amount == msg.value, "The provided amount should be identical to msg.value"); IWrbtcERC20(wrbtcTokenAddress).deposit.value(_amount)(); } else{ reserveToken.transferFrom(msg.sender, address(this), _amount); } require(reserveToken.approve(_liquidityPoolConverterAddress, _amount), "token approval failed"); uint256 poolTokenAmount = _liquidityPoolConverter.addLiquidity(reserveToken, _amount, _minReturn); //deposit the pool tokens in the liquidity mining contract on the sender's behalf _poolToken.approve(address(liquidityMiningContract), poolTokenAmount); liquidityMiningContract.deposit(address(_poolToken), poolTokenAmount, msg.sender); emit LiquidityAdded(msg.sender, _amount, poolTokenAmount); return poolTokenAmount; } /** * @dev * The process: * 1.Accepts RBTC * 2.Sends RBTC to WRBTC contract in order to wrap RBTC to WRBTC * 3.Accepts reserve token and approve LiquidityPoolConverter to transfer * 4.Calls 'addLiquidity' on LiquidityPoolConverter contract * 5.Transfers pool tokens to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _reserveTokens address of each reserve token. The first element should be the address of WRBTC * @param _reserveAmounts amount of each reserve token. The first element should be the amount of RBTC * @param _minReturn minimum return-amount of reserve tokens * * @return amount of pool tokens minted */ function addLiquidityToV1( address _liquidityPoolConverterAddress, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn ) public payable checkAddress(_liquidityPoolConverterAddress) returns(uint256) { require(address(_reserveTokens[0]) == wrbtcTokenAddress, "The first reserve token must be WRBTC"); require(_reserveAmounts[0] == msg.value, "The provided amount of RBTC should be identical to msg.value"); bool success; uint256 amount; ILiquidityPoolV1Converter _liquidityPoolConverter = ILiquidityPoolV1Converter(_liquidityPoolConverterAddress); ISmartToken _poolToken = ISmartToken(address(_liquidityPoolConverter.token())); uint32 reserveRatio_ = _liquidityPoolConverter.reserveRatio(); uint256 totalSupplyBefore = _poolToken.totalSupply(); uint256[] memory rsvBalances = new uint256[](_reserveTokens.length); IWrbtcERC20(wrbtcTokenAddress).deposit.value(_reserveAmounts[0])(); success = IWrbtcERC20(wrbtcTokenAddress).approve(_liquidityPoolConverterAddress, _reserveAmounts[0]); require(success, "Failed to approve converter to transfer WRBTC"); for (uint256 i = 1; i < _reserveTokens.length; i++) { success = IERC20Token(_reserveTokens[i]).transferFrom(msg.sender, address(this), _reserveAmounts[i]); require(success, "Failed to transfer reserve token from user"); success = IERC20Token(_reserveTokens[i]).approve(_liquidityPoolConverterAddress, _reserveAmounts[i]); require(success, "Failed to approve converter to transfer reserve token"); (rsvBalances[i], , , , ) = _liquidityPoolConverter.reserves(address(_reserveTokens[i])); } (rsvBalances[0], , , , ) = _liquidityPoolConverter.reserves(wrbtcTokenAddress); uint256 poolTokenAmountBefore = _poolToken.balanceOf(address(this)); _liquidityPoolConverter.addLiquidity(_reserveTokens, _reserveAmounts, _minReturn); uint256 poolTokenAmount = _poolToken.balanceOf(address(this)).sub(poolTokenAmountBefore); //deposit the pool tokens in the liquidity mining contract on the sender's behalf _poolToken.approve(address(liquidityMiningContract), poolTokenAmount); liquidityMiningContract.deposit(address(_poolToken), poolTokenAmount, msg.sender); for (uint256 i = 1; i < _reserveTokens.length; i++) { amount = _reserveAmounts[i].sub(ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)).fundCost(totalSupplyBefore, rsvBalances[i], reserveRatio_, poolTokenAmount)); if (amount > 0) { success = _reserveTokens[i].transfer(msg.sender, amount); require(success, "Failed to transfer extra reserve token back to user"); } } amount = _reserveAmounts[0].sub(ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)).fundCost(totalSupplyBefore, rsvBalances[0], reserveRatio_, poolTokenAmount)); if (amount > 0) { IWrbtcERC20(wrbtcTokenAddress).withdraw(amount); (success,) = msg.sender.call.value(amount)(""); require(success, "Failed to send extra RBTC back to user"); } emit LiquidityAddedToV1(msg.sender, _reserveTokens, _reserveAmounts, poolTokenAmount); return poolTokenAmount; } /** * @notice * Before calling this function to remove liquidity, users need approve this contract to be able to spend or transfer their pool tokens * * @dev * The process: * 1.Transfers pool tokens to this contract * 2.Calls 'removeLiquidity' on LiquidityPoolConverter contract * 3.Calls 'withdraw' on WRBTC contract in order to unwrap WRBTC to RBTC * 4.Sneds RBTC to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _reserveAddress address of the reserve to add to the pool * @param _amount amount of pool tokens to burn * @param _minReturn minimum return-amount of reserve tokens * * @return amount of liquidity removed also WRBTC unwrapped to RBTC */ function removeLiquidityFromV2( address _liquidityPoolConverterAddress, address _reserveAddress, uint256 _amount, uint256 _minReturn ) public checkAddress(_liquidityPoolConverterAddress) returns(uint256) { ILiquidityPoolV2Converter _liquidityPoolConverter = ILiquidityPoolV2Converter(_liquidityPoolConverterAddress); IERC20Token reserveToken = IERC20Token(_reserveAddress); ISmartToken _poolToken = _liquidityPoolConverter.poolToken(IERC20Token(_reserveAddress)); //withdraw always transfers the pool tokens to the caller and the reward tokens to the passed address liquidityMiningContract.withdraw(address(_poolToken), _amount, msg.sender); uint256 reserveAmount = _liquidityPoolConverter.removeLiquidity(_poolToken, _amount, _minReturn); if(_reserveAddress == wrbtcTokenAddress){ IWrbtcERC20(wrbtcTokenAddress).withdraw(reserveAmount); (bool success, ) = msg.sender.call.value(reserveAmount)(""); require(success, "Failed to send RBTC to the user"); } else{ require(reserveToken.transfer(msg.sender, reserveAmount), "Failed to transfer reserve tokens to the user"); } emit LiquidityRemoved(msg.sender, reserveAmount, _amount); return reserveAmount; } /** * @notice * Before calling this function to remove liquidity, users need approve this contract to be able to spend or transfer their pool tokens * * @dev * The process: * 1.Transfers pool tokens to this contract * 2.Calls 'removeLiquidity' on LiquidityPoolConverter contract * 3.Calls 'withdraw' on WRBTC contract in order to unwrap WRBTC to RBTC * 4.Sneds RBTC and/or other reserve tokens to user * * @param _liquidityPoolConverterAddress address of LiquidityPoolConverter contract * @param _amount amount of pool tokens to burn * @param _reserveTokens address of each reserve token. The first element should be the address of WRBTC * @param _reserveMinReturnAmounts minimum return-amount of each reserve token. The first element should be the minimum return-amount of WRBTC */ function removeLiquidityFromV1( address _liquidityPoolConverterAddress, uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts ) public checkAddress(_liquidityPoolConverterAddress) { require(_amount > 0, "The amount should larger than zero"); require(address(_reserveTokens[0]) == wrbtcTokenAddress, "The first reserve token must be WRBTC"); uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length); ILiquidityPoolV1Converter _liquidityPoolConverter = ILiquidityPoolV1Converter(_liquidityPoolConverterAddress); //withdraw always transfers the pool tokens to the caller and the reward tokens to the passed address liquidityMiningContract.withdraw(address(_liquidityPoolConverter.token()), _amount, msg.sender); uint256 lengthOfToken = _reserveTokens.length; uint256[] memory reserveAmountBefore = new uint256[](lengthOfToken); for (uint256 i = 0; i < lengthOfToken; i++) { reserveAmountBefore[i] = _reserveTokens[i].balanceOf(address(this)); } _liquidityPoolConverter.removeLiquidity(_amount, _reserveTokens, _reserveMinReturnAmounts); uint256 reserveAmount; bool successOfTransfer; for (uint256 i = 1; i < lengthOfToken; i++) { reserveAmount = _reserveTokens[i].balanceOf(address(this)).sub(reserveAmountBefore[i]); require(reserveAmount >= _reserveMinReturnAmounts[i], "min return too high"); reserveAmounts[i] = reserveAmount; successOfTransfer = IERC20Token(_reserveTokens[i]).transfer(msg.sender, reserveAmount); require(successOfTransfer, "Failed to transfer reserve token to user"); } uint256 wrbtcAmount = _reserveTokens[0].balanceOf(address(this)).sub(reserveAmountBefore[0]); require(wrbtcAmount >= _reserveMinReturnAmounts[0], "min return too high"); reserveAmounts[0] = wrbtcAmount; IWrbtcERC20(wrbtcTokenAddress).withdraw(wrbtcAmount); (bool successOfSendRBTC,) = msg.sender.call.value(wrbtcAmount)(""); require(successOfSendRBTC, "Failed to send RBTC to user"); emit LiquidityRemovedFromV1(msg.sender, _reserveTokens, reserveAmounts, _amount); } /** * @notice * Before calling this function to swap token to RBTC, users need approve this contract to be able to spend or transfer their tokens * * @param _path conversion path between two tokens in the network * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * * @return amount of tokens received from the conversion */ function convertByPath( IERC20Token[] memory _path, uint256 _amount, uint256 _minReturn ) public payable returns(uint256) { ISovrynSwapNetwork _sovrynSwapNetwork = ISovrynSwapNetwork(sovrynSwapNetworkAddress); if (msg.value != 0) { require(_path[0] == IERC20Token(wrbtcTokenAddress), "Value may only be sent for WRBTC transfers"); require(_amount == msg.value, "The provided amount should be identical to msg.value"); IWrbtcERC20(wrbtcTokenAddress).deposit.value(_amount)(); bool successOfApprove = IWrbtcERC20(wrbtcTokenAddress).approve(sovrynSwapNetworkAddress, _amount); require(successOfApprove); uint256 _targetTokenAmount = _sovrynSwapNetwork.convertByPath(_path, _amount, _minReturn, msg.sender, address(0), 0); emit TokenConverted(msg.sender, _amount, _targetTokenAmount, _path); return _targetTokenAmount; } else { require(_path[_path.length-1] == IERC20Token(wrbtcTokenAddress), "It only could be swapped to WRBTC"); IERC20Token _token = IERC20Token(_path[0]); bool successOfTransferFrom = _token.transferFrom(msg.sender, address(this), _amount); require(successOfTransferFrom); bool successOfApprove = _token.approve(sovrynSwapNetworkAddress, _amount); require(successOfApprove); uint256 _targetTokenAmount = _sovrynSwapNetwork.convertByPath(_path, _amount, _minReturn, address(this), address(0), 0); IWrbtcERC20(wrbtcTokenAddress).withdraw(_targetTokenAmount); (bool successOfSendRBTC,) = msg.sender.call.value(_targetTokenAmount)(""); require(successOfSendRBTC, "Failed to send RBTC to user"); emit TokenConverted(msg.sender, _amount, _targetTokenAmount, _path); return _targetTokenAmount; } } /** * @notice provides funds to a lending pool and deposits the pool tokens into the liquidity mining contract. * @param loanTokenAddress the address of the loan token (aka lending pool) * @param depositAmount he amount of underlying tokens to deposit */ function addToLendingPool(address loanTokenAddress, uint256 depositAmount) public{ LoanToken loanToken = LoanToken(loanTokenAddress); IERC20Token underlyingAsset = IERC20Token(loanToken.loanTokenAddress()); //retrieve the underlying asset from the user require(underlyingAsset.transferFrom(msg.sender, address(this), depositAmount), "Failed to transfer tokens to the wrapper proxy"); //add the tokens to the lending pool underlyingAsset.approve(loanTokenAddress, depositAmount); uint256 minted = loanToken.mint(address(this), depositAmount); //deposit the pool tokens in the liquidity mining contract on the sender's behalf loanToken.approve(address(liquidityMiningContract), minted); liquidityMiningContract.deposit(loanTokenAddress, minted, msg.sender); emit LoanTokensMinted(msg.sender, minted, depositAmount); } /** * @notice removes funds from the liquidity mining contract, burns them on the lending pool and * provides the underlying asset to the user * @param loanTokenAddress the address of the loan token (aka lending pool) * @param burnAmount the amount of pool tokens to withdraw from the lending pool and burn */ function removeFromLendingPool(address loanTokenAddress, uint256 burnAmount) public{ LoanToken loanToken = LoanToken(loanTokenAddress); //withdraw always transfers the pool tokens to the caller and the reward tokens to the passed address liquidityMiningContract.withdraw(loanTokenAddress, burnAmount, msg.sender); //burn pool token and directly send underlying tokens to the receiver loanToken.approve(address(liquidityMiningContract), burnAmount); uint256 redeemed = loanToken.burn(msg.sender, burnAmount); emit LoanTokensBurnt(msg.sender, burnAmount, redeemed); } }
Before calling this function to remove liquidity, users need approve this contract to be able to spend or transfer their pool tokens The process: 1.Transfers pool tokens to this contract 2.Calls 'removeLiquidity' on LiquidityPoolConverter contract 3.Calls 'withdraw' on WRBTC contract in order to unwrap WRBTC to RBTC 4.Sneds RBTC to user _liquidityPoolConverterAddress address of LiquidityPoolConverter contract _reserveAddress address of the reserve to add to the pool _amount amount of pool tokens to burn _minReturn minimum return-amount of reserve tokens return amount of liquidity removed also WRBTC unwrapped to RBTC/withdraw always transfers the pool tokens to the caller and the reward tokens to the passed address
function removeLiquidityFromV2( address _liquidityPoolConverterAddress, address _reserveAddress, uint256 _amount, uint256 _minReturn ) public checkAddress(_liquidityPoolConverterAddress) returns(uint256) { ILiquidityPoolV2Converter _liquidityPoolConverter = ILiquidityPoolV2Converter(_liquidityPoolConverterAddress); IERC20Token reserveToken = IERC20Token(_reserveAddress); ISmartToken _poolToken = _liquidityPoolConverter.poolToken(IERC20Token(_reserveAddress)); liquidityMiningContract.withdraw(address(_poolToken), _amount, msg.sender); uint256 reserveAmount = _liquidityPoolConverter.removeLiquidity(_poolToken, _amount, _minReturn); if(_reserveAddress == wrbtcTokenAddress){ IWrbtcERC20(wrbtcTokenAddress).withdraw(reserveAmount); (bool success, ) = msg.sender.call.value(reserveAmount)(""); require(success, "Failed to send RBTC to the user"); } else{ require(reserveToken.transfer(msg.sender, reserveAmount), "Failed to transfer reserve tokens to the user"); } emit LiquidityRemoved(msg.sender, reserveAmount, _amount); return reserveAmount; }
1,043,544
pragma solidity ^0.4.24; interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } interface FundForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface FundInterfaceForForwarder { function deposit(address _addr) external payable returns (bool); function migrationReceiver_setup() external returns (bool); } interface HourglassInterface { function() payable external; function buy(address _playerAddress) payable external returns(uint256); function sell(uint256 _amountOfTokens) external; function reinvest() external; function withdraw() external; function exit() external; function dividendsOf(address _playerAddress) external view returns(uint256); function balanceOf(address _playerAddress) external view returns(uint256); function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool); function stakingRequirement() external view returns(uint256); } interface otherFoMo3D { function potSwap() external payable; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } interface TeamInterface { function requiredSignatures() external view returns(uint256); function requiredDevSignatures() external view returns(uint256); function adminCount() external view returns(uint256); function devCount() external view returns(uint256); function adminName(address _who) external view returns(bytes32); function isAdmin(address _who) external view returns(bool); function isDev(address _who) external view returns(bool); } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead, 幸运儿 uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran 这个开关值得研究下 uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } /** * @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 NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** @title -MSFun- v0.2.4 * * ┌──────────────────────────────────────────────────────────────────────┐ * │ MSFun, is an importable library that gives your contract the ability │ * │ add multiSig requirement to functions. │ * └──────────────────────────────────────────────────────────────────────┘ * ┌────────────────────┐ * │ Setup Instructions │ * └────────────────────┘ * (Step 1) import the library into your contract * * import "./MSFun.sol"; * * (Step 2) set up the signature data for msFun * * MSFun.Data private msData; * ┌────────────────────┐ * │ Usage Instructions │ * └────────────────────┘ * at the beginning of a function * * function functionName() * { * if (MSFun.multiSig(msData, required signatures, "functionName") == true) * { * MSFun.deleteProposal(msData, "functionName"); * * // put function body here * } * } * ┌────────────────────────────────┐ * │ Optional Wrappers For TeamJust │ * └────────────────────────────────┘ * multiSig wrapper function (cuts down on inputs, improves readability) * this wrapper is HIGHLY recommended * * function multiSig(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredSignatures(), _whatFunction));} * function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} * * wrapper for delete proposal (makes code cleaner) * * function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} * ┌────────────────────────────┐ * │ Utility & Vanity Functions │ * └────────────────────────────┘ * delete any proposal is highly recommended. without it, if an admin calls a multiSig * function, with argument inputs that the other admins do not agree upon, the function * can never be executed until the undesirable arguments are approved. * * function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} * * for viewing who has signed a proposal & proposal data * * function checkData(bytes32 _whatFunction) onlyAdmins() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} * * lets you check address of up to 3 signers (address) * * function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} * * same as above but will return names in string format. * * function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} * ┌──────────────────────────┐ * │ Functions In Depth Guide │ * └──────────────────────────┘ * In the following examples, the Data is the proposal set for this library. And * the bytes32 is the name of the function. * * MSFun.multiSig(Data, uint256, bytes32) - Manages creating/updating multiSig * proposal for the function being called. The uint256 is the required * number of signatures needed before the multiSig will return true. * Upon first call, multiSig will create a proposal and store the arguments * passed with the function call as msgData. Any admins trying to sign the * function call will need to send the same argument values. Once required * number of signatures is reached this will return a bool of true. * * MSFun.deleteProposal(Data, bytes32) - once multiSig unlocks the function body, * you will want to delete the proposal data. This does that. * * MSFun.checkMsgData(Data, bytes32) - checks the message data for any given proposal * * MSFun.checkCount(Data, bytes32) - checks the number of admins that have signed * the proposal * * MSFun.checkSigners(data, bytes32, uint256) - checks the address of a given signer. * the uint256, is the log number of the signer (ie 1st signer, 2nd signer) */ library MSFun { //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // contact data setup struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { // a hash of msg.data bytes32 msgData; // number of signers uint256 count; // tracking of wither admins have signed mapping (address => bool) admin; // list of admins who have signed mapping (uint256 => address) log; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MULTI SIG FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { // our proposal key will be a hash of our function name + our contracts address // by adding our contracts address to this, we prevent anyone trying to circumvent // the proposal's security via external calls. bytes32 _whatProposal = whatProposal(_whatFunction); // this is just done to make the code more readable. grabs the signature count uint256 _currentCount = self.proposal_[_whatProposal].count; // store the address of the person sending the function call. we use msg.sender // here as a layer of security. in case someone imports our contract and tries to // circumvent function arguments. still though, our contract that imports this // library and calls multisig, needs to use onlyAdmin modifiers or anyone who // calls the function will be a signer. address _whichAdmin = msg.sender; // prepare our msg data. by storing this we are able to verify that all admins // are approving the same argument input to be executed for the function. we hash // it and store in bytes32 so its size is known and comparable bytes32 _msgData = keccak256(msg.data); // check to see if this is a new execution of this proposal or not if (_currentCount == 0) { // if it is, lets record the original signers data self.proposal_[_whatProposal].msgData = _msgData; // record original senders signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) // also useful if the calling function wants to give something to a // specific signer. self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; // if we now have enough signatures to execute the function, lets // return a bool of true. we put this here in case the required signatures // is set to 1. if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } // if its not the first execution, lets make sure the msgData matches } else if (self.proposal_[_whatProposal].msgData == _msgData) { // msgData is a match // make sure admin hasnt already signed if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { // record their signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; } // if we now have enough signatures to execute the function, lets // return a bool of true. // we put this here for a few reasons. (1) in normal operation, if // that last recorded signature got us to our required signatures. we // need to return bool of true. (2) if we have a situation where the // required number of signatures was adjusted to at or lower than our current // signature count, by putting this here, an admin who has already signed, // can call the function again to make it return a true bool. but only if // they submit the correct msg data if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } // deletes proposal signature data after successfully executing a multiSig function function deleteProposal(Data storage self, bytes32 _whatFunction) internal { //done for readability sake bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; //delete the admins votes & log. i know for loops are terrible. but we have to do this //for our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this. for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } //delete the rest of the data in the record delete self.proposal_[_whatProposal]; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // HELPER FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // VANITY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // returns a hashed version of msg.data sent by original signer for any given function function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } // returns number of signers for any given function function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } // returns address of an admin who signed for any given function function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } library UintCompressor { using SafeMath for *; function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end) internal pure returns(uint256) { // check conditions require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); // format our start/end points _end = exponent(_end).mul(10); _start = exponent(_start); // check that the include data fits into its segment require(_include < (_end / _start)); // build middle if (_include > 0) _include = _include.mul(_start); return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end))); } function extract(uint256 _input, uint256 _start, uint256 _end) internal pure returns(uint256) { // check conditions require(_end < 77 && _start < 77, "start/end must be less than 77"); require(_end >= _start, "end must be >= start"); // format our start/end points _end = exponent(_end).mul(10); _start = exponent(_start); // return requested section return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start); } function exponent(uint256 _position) private pure returns(uint256) { return((10).pwr(_position)); } } contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract FundForwarder { string public name = "FundForwarder"; FundInterfaceForForwarder private currentCorpBank_; address private newCorpBank_; bool needsBank_ = true; constructor() public { //constructor does nothing. } function() public payable { // done so that if any one tries to dump eth into this contract, we can // just forward it to corp bank. currentCorpBank_.deposit.value(address(this).balance)(address(currentCorpBank_)); } function deposit() public payable returns(bool) { require(msg.value > 0, "Forwarder Deposit failed - zero deposits not allowed"); require(needsBank_ == false, "Forwarder Deposit failed - no registered bank"); //wallet.transfer(toFund); if (currentCorpBank_.deposit.value(msg.value)(msg.sender) == true) return(true); else return(false); } //============================================================================== // _ _ . _ _ _ _|_. _ _ . // | | ||(_|| (_| | |(_)| | . //===========_|================================================================= function status() public view returns(address, address, bool) { return(address(currentCorpBank_), address(newCorpBank_), needsBank_); } function startMigration(address _newCorpBank) external returns(bool) { // make sure this is coming from current corp bank require(msg.sender == address(currentCorpBank_), "Forwarder startMigration failed - msg.sender must be current corp bank"); // communicate with the new corp bank and make sure it has the forwarder // registered if(FundInterfaceForForwarder(_newCorpBank).migrationReceiver_setup() == true) { // save our new corp bank address newCorpBank_ = _newCorpBank; return (true); } else return (false); } function cancelMigration() external returns(bool) { // make sure this is coming from the current corp bank (also lets us know // that current corp bank has not been killed) require(msg.sender == address(currentCorpBank_), "Forwarder cancelMigration failed - msg.sender must be current corp bank"); // erase stored new corp bank address; newCorpBank_ = address(0x0); return (true); } function finishMigration() external returns(bool) { // make sure its coming from new corp bank require(msg.sender == newCorpBank_, "Forwarder finishMigration failed - msg.sender must be new corp bank"); // update corp bank address currentCorpBank_ = (FundInterfaceForForwarder(newCorpBank_)); // erase new corp bank address newCorpBank_ = address(0x0); return (true); } //============================================================================== // . _ ._|_. _ | _ _ _|_ _ . // || || | |(_|| _\(/_ | |_||_) . (this only runs once ever) //==============================|=============================================== function setup(address _firstCorpBank) external { require(needsBank_ == true, "Forwarder setup failed - corp bank already registered"); currentCorpBank_ = FundInterfaceForForwarder(_firstCorpBank); needsBank_ = false; } } contract ModularLong is F3Devents {} contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address constant private DEV_1_ADDRESS = 0x7a9E13E044CB905957eA465488DabD5F5D34E2C4; bytes32 constant private DEV_1_NAME = "master"; FundForwarderInterface constant private FundForwarderConst = FundForwarderInterface(0x5095072aEE46a39D0b3753184514ead86405780f); TeamInterface constant private TeamJust = TeamInterface(0xf72848D3426d8dB71e52FAc6Df29585649bb7CBD); MSFun.Data private msData; function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name // game 需要实现PlayerBookReceiverInterface的接口 mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = DEV_1_ADDRESS; plyr_[1].name = DEV_1_NAME; plyr_[1].names = 1; pIDxAddr_[DEV_1_ADDRESS] = 1; pIDxName_[DEV_1_NAME] = 1; plyrNames_[1][DEV_1_NAME] = true; plyrNameList_[1][1] = DEV_1_NAME; pID_ = 1; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier onlyDevs() { require(TeamJust.isDev(msg.sender) == true, "msg sender is not a dev"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards FundForwarderConst.deposit.value(address(this).balance)(); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); if (multiSigDev("addGame") == true) { deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } } function setRegistrationFee(uint256 _fee) onlyDevs() public { if (multiSigDev("setRegistrationFee") == true) {deleteProposal("setRegistrationFee"); registrationFee_ = _fee; } } } contract Team { // set dev1 address constant private DEV_1_ADDRESS = 0x7a9E13E044CB905957eA465488DabD5F5D34E2C4; bytes32 constant private DEV_1_NAME = "master"; FundForwarderInterface private FundForwarderTeam = FundForwarderInterface(0x0); //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // SET UP MSFun (note, check signers by name is modified from MSFun sdk) //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ MSFun.Data private msData; function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} function checkData(bytes32 _whatFunction) onlyAdmins() public view returns(bytes32 message_data, uint256 signature_count) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(bytes32, bytes32, bytes32) {return(this.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), this.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), this.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETUP //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ struct Admin { bool isAdmin; bool isDev; bytes32 name; } mapping (address => Admin) admins_; uint256 adminCount_; uint256 devCount_; uint256 requiredSignatures_; uint256 requiredDevSignatures_; //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // CONSTRUCTOR //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructor() public { admins_[DEV_1_ADDRESS] = Admin(true, true, DEV_1_NAME); adminCount_ = 1; devCount_ = 1; requiredSignatures_ = 1; requiredDevSignatures_ = 1; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // FALLBACK, SETUP, AND FORWARD //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // there should never be a balance in this contract. but if someone // does stupidly send eth here for some reason. we can forward it // to jekyll island function () public payable { FundForwarderTeam.deposit.value(address(this).balance)(); } function setup(address _addr) onlyDevs() public { require( address(FundForwarderTeam) == address(0) ); FundForwarderTeam = FundForwarderInterface(_addr); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MODIFIERS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ modifier onlyDevs() { require(admins_[msg.sender].isDev == true, "onlyDevs failed - msg.sender is not a dev"); _; } modifier onlyAdmins() { require(admins_[msg.sender].isAdmin == true, "onlyAdmins failed - msg.sender is not an admin"); _; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DEV ONLY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /** * @dev DEV - use this to add admins. this is a dev only function. * @param _who - address of the admin you wish to add * @param _name - admins name * @param _isDev - is this admin also a dev? */ function addAdmin(address _who, bytes32 _name, bool _isDev) public onlyDevs() { if (MSFun.multiSig(msData, requiredDevSignatures_, "addAdmin") == true) { MSFun.deleteProposal(msData, "addAdmin"); // must check this so we dont mess up admin count by adding someone // who is already an admin if (admins_[_who].isAdmin == false) { // set admins flag to true in admin mapping admins_[_who].isAdmin = true; // adjust admin count and required signatures adminCount_ += 1; requiredSignatures_ += 1; } // are we setting them as a dev? // by putting this outside the above if statement, we can upgrade existing // admins to devs. if (_isDev == true) { // bestow the honored dev status admins_[_who].isDev = _isDev; // increase dev count and required dev signatures devCount_ += 1; requiredDevSignatures_ += 1; } } // by putting this outside the above multisig, we can allow easy name changes // without having to bother with multisig. this will still create a proposal though // so use the deleteAnyProposal to delete it if you want to admins_[_who].name = _name; } /** * @dev DEV - use this to remove admins. this is a dev only function. * -requirements: never less than 1 admin * never less than 1 dev * never less admins than required signatures * never less devs than required dev signatures * @param _who - address of the admin you wish to remove */ function removeAdmin(address _who) public onlyDevs() { // we can put our requires outside the multisig, this will prevent // creating a proposal that would never pass checks anyway. require(adminCount_ > 1, "removeAdmin failed - cannot have less than 2 admins"); require(adminCount_ >= requiredSignatures_, "removeAdmin failed - cannot have less admins than number of required signatures"); if (admins_[_who].isDev == true) { require(devCount_ > 1, "removeAdmin failed - cannot have less than 2 devs"); require(devCount_ >= requiredDevSignatures_, "removeAdmin failed - cannot have less devs than number of required dev signatures"); } // checks passed if (MSFun.multiSig(msData, requiredDevSignatures_, "removeAdmin") == true) { MSFun.deleteProposal(msData, "removeAdmin"); // must check this so we dont mess up admin count by removing someone // who wasnt an admin to start with if (admins_[_who].isAdmin == true) { //set admins flag to false in admin mapping admins_[_who].isAdmin = false; //adjust admin count and required signatures adminCount_ -= 1; if (requiredSignatures_ > 1) { requiredSignatures_ -= 1; } } // were they also a dev? if (admins_[_who].isDev == true) { //set dev flag to false admins_[_who].isDev = false; //adjust dev count and required dev signatures devCount_ -= 1; if (requiredDevSignatures_ > 1) { requiredDevSignatures_ -= 1; } } } } /** * @dev DEV - change the number of required signatures. must be between * 1 and the number of admins. this is a dev only function * @param _howMany - desired number of required signatures */ function changeRequiredSignatures(uint256 _howMany) public onlyDevs() { // make sure its between 1 and number of admins require(_howMany > 0 && _howMany <= adminCount_, "changeRequiredSignatures failed - must be between 1 and number of admins"); if (MSFun.multiSig(msData, requiredDevSignatures_, "changeRequiredSignatures") == true) { MSFun.deleteProposal(msData, "changeRequiredSignatures"); // store new setting. requiredSignatures_ = _howMany; } } /** * @dev DEV - change the number of required dev signatures. must be between * 1 and the number of devs. this is a dev only function * @param _howMany - desired number of required dev signatures */ function changeRequiredDevSignatures(uint256 _howMany) public onlyDevs() { // make sure its between 1 and number of admins require(_howMany > 0 && _howMany <= devCount_, "changeRequiredDevSignatures failed - must be between 1 and number of devs"); if (MSFun.multiSig(msData, requiredDevSignatures_, "changeRequiredDevSignatures") == true) { MSFun.deleteProposal(msData, "changeRequiredDevSignatures"); // store new setting. requiredDevSignatures_ = _howMany; } } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // EXTERNAL FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function requiredSignatures() external view returns(uint256) {return(requiredSignatures_);} function requiredDevSignatures() external view returns(uint256) {return(requiredDevSignatures_);} function adminCount() external view returns(uint256) {return(adminCount_);} function devCount() external view returns(uint256) {return(devCount_);} function adminName(address _who) external view returns(bytes32) {return(admins_[_who].name);} function isAdmin(address _who) external view returns(bool) {return(admins_[_who].isAdmin);} function isDev(address _who) external view returns(bool) {return(admins_[_who].isDev);} } contract FoMo3DlongUnlimited is ModularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; address constant private DEV_1_ADDRESS = 0x7a9E13E044CB905957eA465488DabD5F5D34E2C4; otherFoMo3D private otherF3D_; FundForwarderInterface constant private FundForwarderMain = FundForwarderInterface(0x5095072aEE46a39D0b3753184514ead86405780f); PlayerBookInterface constant private PlayerBookMain = PlayerBookInterface(0xf72848D3426d8dB71e52FAc6Df29585649bb7CBD); bool public activated_ = false; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "Fomo3D Long Unlimited"; string constant public symbol = "F3DLong"; uint256 private rndExtra_ = 10 minutes; //extSettings.getLongExtra(); // length of the very first ICO uint256 private rndGap_ = 10 minutes; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 0 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 2 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id //一个用户可以有多个名字 mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id // **************** // TEAM FEE DATA , Team的费用分配数据 // **************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { //Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls //Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(36,0); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(66,0); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(51,0); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(40,0); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(40,0); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // todo: 如果去为空怎么办? // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBookMain.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBookMain.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBookMain.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth, 分钱 _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBookMain), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBookMain), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBookMain.getPlayerID(msg.sender); bytes32 _name = PlayerBookMain.getPlayerName(_pID); uint256 _laff = PlayerBookMain.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(FundForwarderMain).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _p3d.add(_com); _com = 0; } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies if (_p3d > 0){ // Divies.deposit.value(_p3d)(); FundForwarderMain.deposit.value(_p3d)(); } // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; if (!address(FundForwarderMain).call.value(_com)(bytes4(keccak256("deposit()")))) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // pay 1% out to FoMo3D short uint256 _long = _eth / 100; otherF3D_.potSwap.value(_long)(); // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract // todo: 干掉 // Divies.deposit.value(_p3d)(); FundForwarderMain.deposit.value(_p3d)(); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ function activate() public { // only team just can activate require( msg.sender == DEV_1_ADDRESS, "only team just can activate" ); // make sure that its been linked. require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } function setOtherFomo(address _otherF3D) public { // only team just can activate require( msg.sender == DEV_1_ADDRESS, "only team just can set" ); // make sure that it HASNT yet been linked. require(address(otherF3D_) == address(0), "silly dev, you already did that"); // set up other fomo3d (fast or long) for pot swap otherF3D_ = otherFoMo3D(_otherF3D); } }
============================================================================== _ _ _|_ _ . _\(/_ | |_||_) .=============|================================================================
function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); if (multiSigDev("addGame") == true) { deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } }
6,448,210
./full_match/5/0x6BADcd7C02052a73a761DCA1aA01c3364bFD0C8F/sources/src/Seelies.sol
If public minting has not started by reaching timestamp or minting out the whitelist supply, revert. If enchanted claim is not ended, cap the supply to public max. If yes, free the rest of the supply for public.
function publicMint(uint256 quantity) external payable { if ( _totalMinted() < whitelistSupplyCap && block.timestamp < publicSaleStart ) { revert SaleNotStarted(); } revert QuantityOffLimits(); if (block.timestamp < enchantedClaimEnd) { if (_totalMinted() + quantity > publicSupplyCap) revert MaxSupplyReached(); if (_totalMinted() + quantity > maxSupplyCap) revert MaxSupplyReached(); } _mint(msg.sender, quantity); }
7,086,923
pragma solidity 0.5.16; library ExtendedMath { /** * @return The given number raised to the power of 2 */ function pow2(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * a; require(c / a == a, "ExtendedMath: squaring overflow"); return c; } /** * @return The square root of the given number */ function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Sacrifice { constructor(address payable _recipient) public payable { selfdestruct(_recipient); } } interface IERC20Mintable { function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function mint(address _to, uint256 _value) external returns (bool); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); } /** * @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; } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @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. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // 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, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } /** * @title EasyStaking * * Note: all percentage values are between 0 (0%) and 1 (100%) * and represented as fixed point numbers containing 18 decimals like with Ether * 100% == 1 ether */ contract EasyStaking is Ownable, ReentrancyGuard { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when a user deposits tokens. * @param sender User address. * @param id User's unique deposit ID. * @param amount The amount of deposited tokens. * @param balance Current user balance. * @param accruedEmission User's accrued emission. * @param prevDepositDuration Duration of the previous deposit in seconds. */ event Deposited( address indexed sender, uint256 indexed id, uint256 amount, uint256 balance, uint256 accruedEmission, uint256 prevDepositDuration ); /** * @dev Emitted when a user withdraws tokens. * @param sender User address. * @param id User's unique deposit ID. * @param amount The amount of withdrawn tokens. * @param balance Current user balance. * @param accruedEmission User's accrued emission. * @param lastDepositDuration Duration of the last deposit in seconds. */ event Withdrawn( address indexed sender, uint256 indexed id, uint256 amount, uint256 balance, uint256 accruedEmission, uint256 lastDepositDuration ); /** * @dev Emitted when a user withdraws Reward tokens. * @param sender User address. * @param id User's unique deposit ID. * @param rewardAmount The amount of withdrawn tokens. * @param claimedRewards The amount of already claimed rewards. */ event WithdrawnRewards( address indexed sender, uint256 indexed id, uint256 rewardAmount, uint256 claimedRewards ); /** * @dev Emitted when a new Liquidity Provider address value is set. * @param value A new address value. * @param sender The owner address at the moment of address changing. */ event LiquidityProviderAddressSet(address value, address sender); uint256 private constant YEAR = 365 days; // The maximum emission rate (in percentage) uint256 public constant MAX_EMISSION_RATE = 150 finney; // 15%, 0.15 ether // The period after which the new value of the parameter is set uint256 public constant PARAM_UPDATE_DELAY = 7 days; // STAKE token IERC20Mintable public token; // Reward Token IERC20Mintable public tokenReward; struct UintParam { uint256 oldValue; uint256 newValue; uint256 timestamp; } struct AddressParam { address oldValue; address newValue; uint256 timestamp; } // The address for the Liquidity Providers AddressParam public liquidityProviderAddressParam; // The deposit balances of users mapping (address => mapping (uint256 => uint256)) public balances; // The dates of users' deposits mapping (address => mapping (uint256 => uint256)) public depositDates; // The last deposit id mapping (address => uint256) public lastDepositIds; // Rewards tokens sum mapping (address => mapping (uint256 => uint256)) public claimedRewards; // To claim rewards tokens sum mapping (address => mapping (uint256 => uint256)) public toClaimRewards; // The total staked amount uint256 public totalStaked; // Variable that prevents _deposit method from being called 2 times bool private locked; // The library that is used to calculate user's current emission rate /** * @dev Initializes the contract. * @param _owner The owner of the contract. * @param _tokenAddress The address of the STAKE token contract. * @param _liquidityProviderAddress The address for the Liquidity Providers reward. */ function initialize( address _owner, address _tokenAddress, address _tokenReward, address _liquidityProviderAddress ) external initializer { require(_owner != address(0), "zero address"); require(_tokenAddress.isContract(), "not a contract address"); Ownable.initialize(msg.sender); ReentrancyGuard.initialize(); token = IERC20Mintable(_tokenAddress); tokenReward = IERC20Mintable(_tokenReward); setLiquidityProviderAddress(_liquidityProviderAddress); Ownable.transferOwnership(_owner); } /** * @dev This method is used to deposit tokens to the deposit opened before. * It calls the internal "_deposit" method and transfers tokens from sender to contract. * Sender must approve tokens first. * * Instead this, user can use the simple "transfer" method of STAKE token contract to make a deposit. * Sender's approval is not needed in this case. * * Note: each call updates the deposit date so be careful if you want to make a long staking. * * @param _depositId User's unique deposit ID. * @param _amount The amount to deposit. */ function deposit(uint256 _depositId, uint256 _amount) public { require (_depositId <=4 ); lastDepositIds[msg.sender]=3; _deposit(msg.sender, _depositId, _amount); _setLocked(true); require(token.transferFrom(msg.sender, address(this), _amount), "transfer failed"); _setLocked(false); } /** * @dev This method is used to make a withdrawal. * It calls the internal "_withdraw" method. * @param _depositId User's unique deposit ID * @param _amount The amount to withdraw (0 - to withdraw all). */ function makeWithdrawal(uint256 _depositId, uint256 _amount) external { uint256 requestDate = depositDates[msg.sender][_depositId]; uint256 timestamp = _now(); uint256 lockEnd = 0; if (_depositId==1) { lockEnd=60; } else if (_depositId==2) { lockEnd=60*60*24*30*3; // 3 months } else { lockEnd=60*60*24*30*6; // 6 months } require(timestamp >= requestDate+lockEnd, "too early. Lockup period"); _withdraw(msg.sender, _depositId, _amount); } /** * @dev This method is used to make a Rewards withdrawal. * It calls the internal "_withdraw" method. * @param _depositId User's unique deposit ID */ function makeWithdrawalRewards(uint256 _depositId) external { _withdrawRewards(msg.sender, _depositId); } /** * @dev This method is used to claim unsupported tokens accidentally sent to the contract. * It can only be called by the owner. * @param _token The address of the token contract (zero address for claiming native coins). * @param _to The address of the tokens/coins receiver. * @param _amount Amount to claim. */ function claimTokens(address _token, address payable _to, uint256 _amount) external onlyOwner { require(_to != address(0) && _to != address(this), "not a valid recipient"); require(_amount > 0, "amount should be greater than 0"); if (_token == address(0)) { if (!_to.send(_amount)) { // solium-disable-line security/no-send (new Sacrifice).value(_amount)(_to); } } else if (_token == address(token)) { uint256 availableAmount = token.balanceOf(address(this)).sub(totalStaked); require(availableAmount >= _amount, "insufficient funds"); require(token.transfer(_to, _amount), "transfer failed"); } else { IERC20 customToken = IERC20(_token); customToken.safeTransfer(_to, _amount); } } /** * @dev Sets the address for the Liquidity Providers reward. * Can only be called by owner. * @param _address The new address. */ function setLiquidityProviderAddress(address _address) public onlyOwner { require(_address != address(0), "zero address"); require(_address != address(this), "wrong address"); AddressParam memory param = liquidityProviderAddressParam; if (param.timestamp == 0) { param.oldValue = _address; } else if (_paramUpdateDelayElapsed(param.timestamp)) { param.oldValue = param.newValue; } param.newValue = _address; param.timestamp = _now(); liquidityProviderAddressParam = param; emit LiquidityProviderAddressSet(_address, msg.sender); } /** * @param _depositDate Deposit date. * @param _amount Amount based on which emission is calculated and accrued. * @return Total accrued emission user share, and seconds passed since the previous deposit started. */ function getAccruedEmission( uint256 _depositDate, uint256 _amount, uint256 stakeType ) public view returns (uint256 userShare, uint256 timePassed) { if (_amount == 0 || _depositDate == 0) return (0, 0); timePassed = _now().sub(_depositDate); if (timePassed == 0) return (0, 0); uint256 stakeRate = 0 finney; if (stakeType==1) { stakeRate = 50 finney; //5% } else if (stakeType==2) { stakeRate = 100 finney; //10% } else if (stakeType==3) { stakeRate = 150 finney; //15% } userShare = _amount.mul(stakeRate).mul(timePassed).div(YEAR * 1 ether); } /** * @dev Calls internal "_mint" method, increases the user balance, and updates the deposit date. * @param _sender The address of the sender. * @param _id User's unique deposit ID. * @param _amount The amount to deposit. */ function _deposit(address _sender, uint256 _id, uint256 _amount) internal nonReentrant { require(_amount > 0, "deposit amount should be more than 0"); //(uint256 sigmoidParamA,,) = getSigmoidParameters(); //if (sigmoidParamA == 0 && totalSupplyFactor() == 0) revert("emission stopped"); // new deposit, calculate interests (uint256 userShare, uint256 timePassed) = _calcRewards(_sender, _id, 0); uint256 newBalance = balances[_sender][_id].add(_amount); balances[_sender][_id] = newBalance; totalStaked = totalStaked.add(_amount); depositDates[_sender][_id] = _now(); emit Deposited(_sender, _id, _amount, newBalance, userShare, timePassed); } /** * @dev Calls internal "_mint" method and then transfers tokens to the sender. * @param _sender The address of the sender. * @param _id User's unique deposit ID. * @param _amount The amount to withdraw (0 - to withdraw all). */ function _withdraw(address _sender, uint256 _id, uint256 _amount) internal nonReentrant { require(_id > 0, "wrong deposit id"); require(balances[_sender][_id] > 0 && balances[_sender][_id] >= _amount, "insufficient funds"); uint256 amount = _amount == 0 ? balances[_sender][_id] : _amount; require(token.transfer(_sender, amount), "transfer failed"); (uint256 accruedEmission, uint256 timePassed) = _calcRewards(_sender, _id, amount); balances[_sender][_id] = balances[_sender][_id].sub(amount); totalStaked = totalStaked.sub(amount); if (balances[_sender][_id] == 0) { depositDates[_sender][_id] = 0; } emit Withdrawn(_sender, _id, _amount, balances[_sender][_id], accruedEmission, timePassed); } /** * @dev Calls internal "_mint" method and then transfers tokens to the sender. * @param _sender The address of the sender. * @param _id User's unique deposit ID. */ function _withdrawRewards(address _sender, uint256 _id) internal nonReentrant { require(_id > 0, "wrong deposit id"); (uint256 userShare, uint256 timePassed) = _calcRewards(_sender, _id, 0); uint256 toClaim=0; if (toClaimRewards[_sender][_id] < claimedRewards[_sender][_id]) { toClaim = 0; } else { toClaim = toClaimRewards[_sender][_id].sub(claimedRewards[_sender][_id]); } require(toClaim > 0, "nothing to claim"); claimedRewards[_sender][_id]=claimedRewards[_sender][_id].add(toClaimRewards[_sender][_id]); require(tokenReward.transferFrom(liquidityProviderAddress(),_sender, toClaim), "Liquidity pool transfer failed"); emit WithdrawnRewards( _sender, _id, toClaim, claimedRewards[_sender][_id]); } /** * @dev Calculate MAX_EMISSION_RATE per annum and distributes. * @param _user User's address. * @param _id User's unique deposit ID. * @param _amount Amount based on which emission is calculated and accrued. When 0, current deposit balance is used. */ function _calcRewards(address _user, uint256 _id, uint256 _amount) internal returns (uint256, uint256) { uint256 currentBalance = balances[_user][_id]; uint256 amount = _amount == 0 ? currentBalance : _amount; (uint256 accruedEmission, uint256 timePassed) = getAccruedEmission(depositDates[_user][_id], amount,_id); toClaimRewards[_user][_id]=toClaimRewards[_user][_id].add(accruedEmission); return (accruedEmission, timePassed); } /** * @dev Sets the next value of the parameter and the timestamp of this setting. */ function _updateUintParam(UintParam storage _param, uint256 _newValue) internal { if (_param.timestamp == 0) { _param.oldValue = _newValue; } else if (_paramUpdateDelayElapsed(_param.timestamp)) { _param.oldValue = _param.newValue; } _param.newValue = _newValue; _param.timestamp = _now(); } /** * @return Returns current liquidity providers reward address. */ function liquidityProviderAddress() public view returns (address) { AddressParam memory param = liquidityProviderAddressParam; return param.newValue; } /** * @return Returns the current value of the parameter. */ function _getUintParamValue(UintParam memory _param) internal view returns (uint256) { return _paramUpdateDelayElapsed(_param.timestamp) ? _param.newValue : _param.oldValue; } /** * @return Returns true if param update delay elapsed. */ function _paramUpdateDelayElapsed(uint256 _paramTimestamp) internal view returns (bool) { return _now() > _paramTimestamp.add(PARAM_UPDATE_DELAY); } /** * @dev Sets lock to prevent reentrance. */ function _setLocked(bool _locked) internal { locked = _locked; } /** * @return Returns current timestamp. */ function _now() internal view returns (uint256) { // Note that the timestamp can have a 900-second error: // https://github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md return now; // solium-disable-line security/no-block-members } }
Sets the address for the Liquidity Providers reward. Can only be called by owner. _address The new address./
function setLiquidityProviderAddress(address _address) public onlyOwner { require(_address != address(0), "zero address"); require(_address != address(this), "wrong address"); AddressParam memory param = liquidityProviderAddressParam; if (param.timestamp == 0) { param.oldValue = _address; param.oldValue = param.newValue; } param.newValue = _address; param.timestamp = _now(); liquidityProviderAddressParam = param; emit LiquidityProviderAddressSet(_address, msg.sender); } else if (_paramUpdateDelayElapsed(param.timestamp)) { }
13,141,574
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; contract DAudio { uint public audioCount = 0; string public contractName = "DAudio"; mapping(uint => Audio) public audios; mapping(string => Audio) public audiohash2metadata; //retrieve metadata by audio hash mapping(address => Audio[]) public address2catalogue; // retrieve catalogue of address struct Audio { uint id; string hash; // hash of audio string title; // song title string[] keywords; // keywords like genre, style etc.. address author; } event AudioUploaded( uint id, string hash, string title, string[] keywords, address author ); constructor() public { } function uploadAudio(string memory _audioHash, string memory _title, string[] memory _keywords) public { // Make sure the audio hash exists require(bytes(_audioHash).length > 0); // Make sure audio title exists require(bytes(_title).length > 0); // Make sure audio keywords exists //require(bytes(_keywords).length > 0); // Make sure uploader address exists require(msg.sender!=address(0)); // create struct Audio memory _audio = Audio(audioCount, _audioHash, _title, _keywords, msg.sender); // Increment audio id audioCount ++; // Add audio to the contract audios[audioCount] = _audio; // Add audio hash to metadata audiohash2metadata[_audioHash] = _audio; // Add audio hash to address mapping address2catalogue[msg.sender].push( _audio ); // to test as "0x00",0 - need to specify the index of the array // Trigger an event emit AudioUploaded(audioCount, _audioHash, _title, _keywords, msg.sender); } }
Make sure the audio hash exists Make sure audio title exists Make sure audio keywords existsrequire(bytes(_keywords).length > 0); Make sure uploader address exists create struct Increment audio id Add audio to the contract Add audio hash to metadata Add audio hash to address mapping to test as "0x00",0 - need to specify the index of the array Trigger an event
function uploadAudio(string memory _audioHash, string memory _title, string[] memory _keywords) public { require(bytes(_audioHash).length > 0); require(bytes(_title).length > 0); require(msg.sender!=address(0)); Audio memory _audio = Audio(audioCount, _audioHash, _title, _keywords, msg.sender); audioCount ++; audios[audioCount] = _audio; audiohash2metadata[_audioHash] = _audio; address2catalogue[msg.sender].push( _audio ); emit AudioUploaded(audioCount, _audioHash, _title, _keywords, msg.sender); }
887,050
./partial_match/3/0xC2B3D062F995703A8Ab5B46677226dFe454B2756/sources/LnFeeSystemTest.sol
------------------ system config ----------------------
function updateAddressCache(LnAddressStorage _addressStorage) public override onlyAdmin { accessCtrl = LnAccessControl( _addressStorage.getAddressWithRequire( "LnAccessControl", "LnAccessControl address not valid" ) ); assetSys = LnAssetSystem( _addressStorage.getAddressWithRequire( "LnAssetSystem", "LnAssetSystem address not valid" ) ); feeSystem = LnFeeSystem( _addressStorage.getAddressWithRequire( "LnFeeSystem", "LnFeeSystem address not valid" ) ); emit updateCachedAddress("LnAccessControl", address(accessCtrl)); emit updateCachedAddress("LnAssetSystem", address(assetSys)); emit updateCachedAddress("LnFeeSystem", address(feeSystem)); }
5,234,122
// Copyright 2019 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. /// @title Step pragma solidity ^0.7.0; import "./RiscVConstants.sol"; import "./RiscVDecoder.sol"; import "./MemoryInteractor.sol"; import {Fetch} from "./Fetch.sol"; import {Execute} from "./Execute.sol"; import {Interrupts} from "./Interrupts.sol"; /// @title Step /// @author Felipe Argento /// @notice State transiction function that takes the machine from state s[i] to s[i + 1] contract Step { event StepGiven(uint8 exitCode); event StepStatus(uint64 cycle, bool halt); MemoryInteractor mi; constructor(address miAddress) { mi = MemoryInteractor(miAddress); } /// @notice Run step define by a MemoryManager instance. /// @return Returns an exit code. /// @param _rwPositions position of all read and writes /// @param _rwValues value of all read and writes /// @param _isRead bool specifying if access is a read /// @return Returns an exit code and the amount of memory accesses function step( uint64[] memory _rwPositions, bytes8[] memory _rwValues, bool[] memory _isRead ) public returns (uint8, uint256) { mi.initializeMemory(_rwPositions, _rwValues, _isRead); // Read iflags register and check its H flag, to see if machine is halted. // If machine is halted - nothing else to do. H flag is stored on the least // signficant bit on iflags register. // Reference: The Core of Cartesi, v1.02 - figure 1. uint64 halt = mi.readIflagsH(); if (halt != 0) { //machine is halted emit StepStatus(0, true); return endStep(0); } uint64 yield = mi.readIflagsY(); if (yield != 0) { //cpu is yielded emit StepStatus(0, true); return endStep(0); } //Raise the highest priority interrupt Interrupts.raiseInterruptIfAny(mi); //Fetch Instruction Fetch.fetchStatus fetchStatus; uint64 pc; uint32 insn; (fetchStatus, insn, pc) = Fetch.fetchInsn(mi); if (fetchStatus == Fetch.fetchStatus.success) { // If fetch was successfull, tries to execute instruction if (Execute.executeInsn( mi, insn, pc ) == Execute.executeStatus.retired ) { // If executeInsn finishes successfully we need to update the number of // retired instructions. This number is stored on minstret CSR. // Reference: riscv-priv-spec-1.10.pdf - Table 2.5, page 12. uint64 minstret = mi.readMinstret(); mi.writeMinstret(minstret + 1); } } // Last thing that has to be done in a step is to update the cycle counter. // The cycle counter is stored on mcycle CSR. // Reference: riscv-priv-spec-1.10.pdf - Table 2.5, page 12. uint64 mcycle = mi.readMcycle(); mi.writeMcycle(mcycle + 1); emit StepStatus(mcycle + 1, false); return endStep(0); } function getMemoryInteractor() public view returns (address) { return address(mi); } function endStep(uint8 exitCode) internal returns (uint8, uint256) { emit StepGiven(exitCode); return (exitCode, mi.getRWIndex()); } }
Run step define by a MemoryManager instance. return Returns an exit code. _rwPositions position of all read and writes _rwValues value of all read and writes _isRead bool specifying if access is a read return Returns an exit code and the amount of memory accesses Read iflags register and check its H flag, to see if machine is halted. If machine is halted - nothing else to do. H flag is stored on the least signficant bit on iflags register. Reference: The Core of Cartesi, v1.02 - figure 1.machine is haltedcpu is yielded If fetch was successfull, tries to execute instruction If executeInsn finishes successfully we need to update the number of retired instructions. This number is stored on minstret CSR. Reference: riscv-priv-spec-1.10.pdf - Table 2.5, page 12.
function step( uint64[] memory _rwPositions, bytes8[] memory _rwValues, bool[] memory _isRead ) public returns (uint8, uint256) { mi.initializeMemory(_rwPositions, _rwValues, _isRead); uint64 halt = mi.readIflagsH(); if (halt != 0) { emit StepStatus(0, true); return endStep(0); } uint64 yield = mi.readIflagsY(); if (yield != 0) { emit StepStatus(0, true); return endStep(0); } uint64 pc; uint32 insn; (fetchStatus, insn, pc) = Fetch.fetchInsn(mi); if (fetchStatus == Fetch.fetchStatus.success) { if (Execute.executeInsn( mi, insn, pc ) == Execute.executeStatus.retired ) { uint64 minstret = mi.readMinstret(); mi.writeMinstret(minstret + 1); } } mi.writeMcycle(mcycle + 1); emit StepStatus(mcycle + 1, false); return endStep(0); }
12,786,498
// Dependency file: contracts/interfaces/INFT.sol // SPDX-License-Identifier: MIT // pragma solidity >=0.8.4 <0.9.0; interface INFT { function init( address registry_, bytes32 domain_, string memory name_, string memory symbol_, string memory uri_ ) external returns (bool); function safeTransfer( address from, address to, uint256 tokenId ) external returns (bool); function batchMint(address to, uint256[] memory tokenIds) external returns (bool); function batchBurn(address to, uint256[] memory tokenIds) external returns (bool); function ownerOf(uint256 tokenId) external view returns (address); function mint(address to, uint256 tokenId) external returns (bool); function burn(uint256 tokenId) external returns (bool); function changeBaseURI(string memory uri_) external returns (bool); } // Dependency file: contracts/libraries/Bytes.sol // pragma solidity >=0.8.4 <0.9.0; library Bytes { // Convert bytes to bytes32[] function toBytes32Array(bytes memory input) public pure returns (bytes32[] memory) { require(input.length % 32 == 0, 'Bytes: invalid data length should divied by 32'); bytes32[] memory result = new bytes32[](input.length / 32); assembly { // Read length of data from offset let length := mload(input) // Seek offset to the beginning let offset := add(input, 0x20) // Next is size of chunk let resultOffset := add(result, 0x20) for { let i := 0 } lt(i, length) { i := add(i, 0x20) } { mstore(resultOffset, mload(add(offset, i))) resultOffset := add(resultOffset, 0x20) } } return result; } // Read address from input bytes buffer function readAddress(bytes memory input, uint256 offset) public pure returns (address result) { require(offset + 20 <= input.length, 'Bytes: Out of range, can not read address from bytes'); assembly { result := shr(96, mload(add(add(input, 0x20), offset))) } } // Read uint256 from input bytes buffer function readUint256(bytes memory input, uint256 offset) public pure returns (uint256 result) { require(offset + 32 <= input.length, 'Bytes: Out of range, can not read uint256 from bytes'); assembly { result := mload(add(add(input, 0x20), offset)) } } // Read bytes from input bytes buffer function readBytes( bytes memory input, uint256 offset, uint256 length ) public pure returns (bytes memory) { require(offset + length <= input.length, 'Bytes: Out of range, can not read bytes from bytes'); bytes memory result = new bytes(length); assembly { // Seek offset to the beginning let seek := add(add(input, 0x20), offset) // Next is size of data let resultOffset := add(result, 0x20) for { let i := 0 } lt(i, length) { i := add(i, 0x20) } { mstore(add(resultOffset, i), mload(add(seek, i))) } } return result; } } // Dependency file: contracts/libraries/Verifier.sol // pragma solidity >=0.8.4 <0.9.0; library Verifier { function verifySerialized(bytes memory message, bytes memory signature) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { // Singature need to be 65 in length // if (signature.length !== 65) revert(); if iszero(eq(mload(signature), 65)) { revert(0, 0) } // r = signature[:32] // s = signature[32:64] // v = signature[64] r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return verify(message, r, s, v); } function verify( bytes memory message, bytes32 r, bytes32 s, uint8 v ) public pure returns (address) { if (v < 27) { v += 27; } // V must be 27 or 28 require(v == 27 || v == 28, 'Invalid v value'); // Get hashes of message with Ethereum proof prefix bytes32 hashes = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n', uintToStr(message.length), message)); return ecrecover(hashes, v, r, s); } function uintToStr(uint256 value) public pure returns (string memory result) { // 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); } } // Dependency file: contracts/interfaces/IRegistry.sol // pragma solidity >=0.8.4 <0.9.0; interface IRegistry { event Registered(bytes32 domain, bytes32 indexed name, address indexed addr); function isExistRecord(bytes32 domain, bytes32 name) external view returns (bool); function set( bytes32 domain, bytes32 name, address addr ) external returns (bool); function batchSet( bytes32[] calldata domains, bytes32[] calldata names, address[] calldata addrs ) external returns (bool); function getAddress(bytes32 domain, bytes32 name) external view returns (address); function getDomainAndName(address addr) external view returns (bytes32, bytes32); } // Dependency file: contracts/libraries/RegistryUser.sol // pragma solidity >=0.8.4 <0.9.0; // import 'contracts/interfaces/IRegistry.sol'; abstract contract RegistryUser { // Registry contract IRegistry internal _registry; // Active domain bytes32 internal _domain; // Initialized bool private _initialized = false; // Allow same domain calls modifier onlyAllowSameDomain(bytes32 name) { require(msg.sender == _registry.getAddress(_domain, name), 'UserRegistry: Only allow call from same domain'); _; } // Allow cross domain call modifier onlyAllowCrossDomain(bytes32 fromDomain, bytes32 name) { require( msg.sender == _registry.getAddress(fromDomain, name), 'UserRegistry: Only allow call from allowed cross domain' ); _; } /******************************************************* * Internal section ********************************************************/ // Constructing with registry address and its active domain function _registryUserInit(address registry_, bytes32 domain_) internal returns (bool) { require(!_initialized, "UserRegistry: It's only able to initialize once"); _registry = IRegistry(registry_); _domain = domain_; _initialized = true; return true; } // Get address in the same domain function _getAddressSameDomain(bytes32 name) internal view returns (address) { return _registry.getAddress(_domain, name); } /******************************************************* * View section ********************************************************/ // Return active domain function getDomain() external view returns (bytes32) { return _domain; } // Return registry address function getRegistry() external view returns (address) { return address(_registry); } } // Root file: contracts/dao/Swap.sol pragma solidity >=0.8.4 <0.9.0; // import 'contracts/interfaces/INFT.sol'; // import 'contracts/libraries/Bytes.sol'; // import 'contracts/libraries/Verifier.sol'; // import 'contracts/libraries/RegistryUser.sol'; /** * Swap can transfer NFT by consume cryptography proof * Name: Swap * Domain: Infrastructure */ contract Swap is RegistryUser { // Verify signature using Verifier for bytes; // Decode bytes array using Bytes for bytes; // Partner of duelistking mapping(address => bool) private _partners; // Nonce mapping(address => uint256) private _nonceStorage; // List partner event ListPartner(address indexed partnerAddress); // Delist partner event DelistPartner(address indexed partnerAddress); // Only allow partner to execute modifier onlyPartner() { require(_partners[msg.sender] == true, 'Swap: Sender was not partner'); _; } // Pass constructor parameter to User constructor(address registry_, bytes32 domain_) { _registryUserInit(registry_, domain_); } /******************************************************* * Partner section ********************************************************/ // Partners can trigger delegate transfer right with a cyrptography proof from owner function delegateTransfer(bytes memory proof) external onlyPartner returns (bool) { // Check for size of the proof require(proof.length >= 169, 'Swap: Wrong size of the proof, it must be greater than 169 bytes'); bytes memory signature = proof.readBytes(0, 65); bytes memory message = proof.readBytes(65, proof.length - 65); address from = message.verifySerialized(signature); address to = message.readAddress(0); address nft = message.readAddress(20); uint256 nonce = message.readUint256(40); bytes memory nftTokenIds = message.readBytes(72, proof.length - 72); require(nftTokenIds.length % 32 == 0, 'Swap: Invalid token ID length'); // Transfer one by one for (uint256 i = 0; i < nftTokenIds.length; i += 32) { INFT(nft).safeTransfer(from, to, nftTokenIds.readUint256(i)); } // Each nonce is only able to be use once require(nonce - _nonceStorage[from] == 1, 'Swap: Incorrect nonce of signer'); _nonceStorage[from] += 1; return true; } /******************************************************* * Operator section ********************************************************/ // List a new partner function listPartner(address partnerAddress) external onlyAllowSameDomain('Operator') returns (bool) { _partners[partnerAddress] = true; emit ListPartner(partnerAddress); return true; } // Delist a partner function delistPartner(address partnerAddress) external onlyAllowSameDomain('Operator') returns (bool) { _partners[partnerAddress] = false; emit DelistPartner(partnerAddress); return true; } /******************************************************* * View section ********************************************************/ // Get nonce of an address function getValidNonce(address owner) external view returns (uint256) { return _nonceStorage[owner] + 1; } // Check an address is partner or not function isPartner(address partner) external view returns (bool) { return _partners[partner]; } }
Singature need to be 65 in length if (signature.length !== 65) revert();
function verifySerialized(bytes memory message, bytes memory signature) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { if iszero(eq(mload(signature), 65)) { revert(0, 0) } s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return verify(message, r, s, v); }
6,408,102
/** @title Onasander Token Contract * * @author: Andrzej Wegrzyn * Contact: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6828390838a89968b838892a6898887958788828394c885898b">[email&#160;protected]</a> * Date: May 5, 2018 * Location: New York, USA * Token: Onasander * Symbol: ONA * * @notice This is a simple contract due to solidity bugs and complications. * * @notice Owner has the option to burn all the remaining tokens after the ICO. That way Owners will not end up with majority of the tokens. * @notice Onasander would love to give every user the option to burn the remaining tokens, but due to Solidity VM bugs and risk, we will process * @notice all coin burns and refunds manually. * * @notice How to run the contract: * * Requires: * Wallet Address * * Run: * 1. Create Contract * 2. Set Minimum Goal * 3. Set Tokens Per ETH * 4. Create PRE ICO Sale (can have multiple PRE-ICOs) * 5. End PRE ICO Sale * 6. Create ICO Sale * 7. End ICO Sale * 8. END ICO * 9. Burn Remaining Tokens * * e18 for every value except tokens per ETH * * @dev This contract allows you to configure as many Pre-ICOs as you need. It&#39;s a very simple contract written to give contract admin lots of dynamic options. * @dev Here, most features except for total supply, max tokens for sale, company reserves, and token standard features, are dynamic. You can configure your contract * @dev however you want to. * * @dev IDE: Remix with Mist 0.10 * @dev Token supply numbers are provided in 0e18 format in MIST in order to bypass MIST number format errors. */ pragma solidity ^0.4.23; contract OnasanderToken { using SafeMath for uint; address private wallet; // Address where funds are collected address public owner; // contract owner string constant public name = "Onasander"; string constant public symbol = "ONA"; uint8 constant public decimals = 18; uint public totalSupply = 88000000e18; uint public totalTokensSold = 0e18; // total number of tokens sold to date uint public totalTokensSoldInThisSale = 0e18; // total number of tokens sold in this sale uint public maxTokensForSale = 79200000e18; // 90% max tokens we can ever sale uint public companyReserves = 8800000e18; // 10% company reserves. this is what we end up with after eco ends and burns the rest if any uint public minimumGoal = 0e18; // hold minimum goal uint public tokensForSale = 0e18; // total number of tokens we are selling in the current sale (ICO, preICO) bool public saleEnabled = false; // enables all sales: ICO and tokensPreICO bool public ICOEnded = false; // flag checking if the ICO has completed bool public burned = false; // Excess tokens burned flag after ICO ends uint public tokensPerETH = 800; // amount of Onasander tokens you get for 1 ETH bool public wasGoalReached = false; // checks if minimum goal was reached address private lastBuyer; uint private singleToken = 1e18; constructor(address icoWallet) public { require(icoWallet != address(0), "ICO Wallet address is required."); owner = msg.sender; wallet = icoWallet; balances[owner] = totalSupply; // give initial full balance to contract owner emit TokensMinted(owner, totalSupply); } event ICOHasEnded(); event SaleEnded(); event OneTokenBugFixed(); event ICOConfigured(uint minimumGoal); event TokenPerETHReset(uint amount); event ICOCapReached(uint amount); event SaleCapReached(uint amount); event GoalReached(uint amount); event Burned(uint amount); event BuyTokens(address buyer, uint tokens); event SaleStarted(uint tokensForSale); event TokensMinted(address targetAddress, uint tokens); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowances; function balanceOf(address accountAddress) public constant returns (uint balance) { return balances[accountAddress]; } function allowance(address sender, address spender) public constant returns (uint remainingAllowedAmount) { return allowances[sender][spender]; } function transfer(address to, uint tokens) public returns (bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); require (balances[to] + tokens > balances[to], "Overflow is not allowed."); // actual transfer // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns(bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); require (balances[to] + tokens > balances[to], "Overflow is not allowed."); // actual transfer balances[from] = balances[from].sub(tokens); allowances[from][msg.sender] = allowances[from][msg.sender].sub(tokens); // lower the allowance by the amount of tokens balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function approve(address spender, uint tokens) public returns(bool success) { require (ICOEnded, "ICO has not ended. Can not transfer."); allowances[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // in case some investor pays by wire or credit card we will transfer him the tokens manually. function wirePurchase(address to, uint numberOfTokenPurchased) onlyOwner public { require (saleEnabled, "Sale must be enabled."); require (!ICOEnded, "ICO already ended."); require (numberOfTokenPurchased > 0, "Tokens must be greater than 0."); require (tokensForSale > totalTokensSoldInThisSale, "There is no more tokens for sale in this sale."); // calculate amount uint buyAmount = numberOfTokenPurchased; uint tokens = 0e18; // this check is not perfect as someone may want to buy more than we offer for sale and we lose a sale. // the best would be to calclate and sell you only the amout of tokens that is left and refund the rest of money if (totalTokensSoldInThisSale.add(buyAmount) >= tokensForSale) { tokens = tokensForSale.sub(totalTokensSoldInThisSale); // we allow you to buy only up to total tokens for sale, and refund the rest // need to program the refund for the rest,or do it manually. } else { tokens = buyAmount; } // transfer only as we do not need to take the payment since we already did in wire require (balances[to].add(tokens) > balances[to], "Overflow is not allowed."); balances[to] = balances[to].add(tokens); balances[owner] = balances[owner].sub(tokens); lastBuyer = to; // update counts totalTokensSold = totalTokensSold.add(tokens); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(tokens); emit BuyTokens(to, tokens); emit Transfer(owner, to, tokens); isGoalReached(); isMaxCapReached(); } function buyTokens() payable public { require (saleEnabled, "Sale must be enabled."); require (!ICOEnded, "ICO already ended."); require (tokensForSale > totalTokensSoldInThisSale, "There is no more tokens for sale in this sale."); require (msg.value > 0, "Must send ETH"); // calculate amount uint buyAmount = SafeMath.mul(msg.value, tokensPerETH); uint tokens = 0e18; // this check is not perfect as someone may want to buy more than we offer for sale and we lose a sale. // the best would be to calclate and sell you only the amout of tokens that is left and refund the rest of money if (totalTokensSoldInThisSale.add(buyAmount) >= tokensForSale) { tokens = tokensForSale.sub(totalTokensSoldInThisSale); // we allow you to buy only up to total tokens for sale, and refund the rest // need to program the refund for the rest } else { tokens = buyAmount; } // buy require (balances[msg.sender].add(tokens) > balances[msg.sender], "Overflow is not allowed."); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); lastBuyer = msg.sender; // take the money out right away wallet.transfer(msg.value); // update counts totalTokensSold = totalTokensSold.add(tokens); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(tokens); emit BuyTokens(msg.sender, tokens); emit Transfer(owner, msg.sender, tokens); isGoalReached(); isMaxCapReached(); } // Fallback function. Used for buying tokens from contract owner by simply // sending Ethers to contract. function() public payable { // we buy tokens using whatever ETH was sent in buyTokens(); } // Called when ICO is closed. Burns the remaining tokens except the tokens reserved // Must be called by the owner to trigger correct transfer event function burnRemainingTokens() public onlyOwner { require (!burned, "Remaining tokens have been burned already."); require (ICOEnded, "ICO has not ended yet."); uint difference = balances[owner].sub(companyReserves); if (wasGoalReached) { totalSupply = totalSupply.sub(difference); balances[owner] = companyReserves; } else { // in case we did not reach the goal, we burn all tokens except tokens purchased. totalSupply = totalTokensSold; balances[owner] = 0e18; } burned = true; emit Transfer(owner, address(0), difference); // this is run in order to update token holders in the website emit Burned(difference); } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { address preOwner = owner; owner = newOwner; uint previousBalance = balances[preOwner]; // transfer balance balances[newOwner] = balances[newOwner].add(previousBalance); balances[preOwner] = 0; //emit Transfer(preOwner, newOwner, previousBalance); // required to update the Token Holders on the network emit OwnershipTransferred(preOwner, newOwner, previousBalance); } // Set the number of ONAs sold per ETH function setTokensPerETH(uint newRate) onlyOwner public { require (!ICOEnded, "ICO already ended."); require (newRate > 0, "Rate must be higher than 0."); tokensPerETH = newRate; emit TokenPerETHReset(newRate); } // Minimum goal is based on USD, not on ETH. Since we will have different dynamic prices based on the daily pirce of ETH, we // will need to be able to adjust our minimum goal in tokens sold, as our goal is set in tokens, not USD. function setMinimumGoal(uint goal) onlyOwner public { require(goal > 0e18,"Minimum goal must be greater than 0."); minimumGoal = goal; // since we can edit the goal, we want to check if we reached the goal before in case we lowered the goal number. isGoalReached(); emit ICOConfigured(goal); } function createSale(uint numberOfTokens) onlyOwner public { require (!saleEnabled, "Sale is already going on."); require (!ICOEnded, "ICO already ended."); require (totalTokensSold < maxTokensForSale, "We already sold all our tokens."); totalTokensSoldInThisSale = 0e18; uint tryingToSell = totalTokensSold.add(numberOfTokens); // in case we are trying to create a sale with too many tokens, we subtract and sell only what&#39;s left if (tryingToSell > maxTokensForSale) { tokensForSale = maxTokensForSale.sub(totalTokensSold); } else { tokensForSale = numberOfTokens; } tryingToSell = 0e18; saleEnabled = true; emit SaleStarted(tokensForSale); } function endSale() public { if (saleEnabled) { saleEnabled = false; tokensForSale = 0e18; emit SaleEnded(); } } function endICO() onlyOwner public { if (!ICOEnded) { // run this before end of ICO and end of last sale fixTokenCalcBug(); endSale(); ICOEnded = true; lastBuyer = address(0); emit ICOHasEnded(); } } function isGoalReached() internal { // check if we reached the goal if (!wasGoalReached) { if (totalTokensSold >= minimumGoal) { wasGoalReached = true; emit GoalReached(minimumGoal); } } } function isMaxCapReached() internal { if (totalTokensSoldInThisSale >= tokensForSale) { emit SaleCapReached(totalTokensSoldInThisSale); endSale(); } if (totalTokensSold >= maxTokensForSale) { emit ICOCapReached(maxTokensForSale); endICO(); } } // This is a hack to add the lost token during final full sale. function fixTokenCalcBug() internal { require(!burned, "Fix lost token can only run before the burning of the tokens."); if (maxTokensForSale.sub(totalTokensSold) == singleToken) { totalTokensSold = totalTokensSold.add(singleToken); totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(singleToken); balances[lastBuyer] = balances[lastBuyer].add(singleToken); balances[owner] = balances[owner].sub(singleToken); emit Transfer(owner, lastBuyer, singleToken); emit OneTokenBugFixed(); } } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } 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 // uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } 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 c) { c = a + b; assert(c >= a); return c; } }
calculate amount this check is not perfect as someone may want to buy more than we offer for sale and we lose a sale. the best would be to calclate and sell you only the amout of tokens that is left and refund the rest of money need to program the refund for the rest
function buyTokens() payable public { require (saleEnabled, "Sale must be enabled."); require (!ICOEnded, "ICO already ended."); require (tokensForSale > totalTokensSoldInThisSale, "There is no more tokens for sale in this sale."); require (msg.value > 0, "Must send ETH"); uint buyAmount = SafeMath.mul(msg.value, tokensPerETH); uint tokens = 0e18; if (totalTokensSoldInThisSale.add(buyAmount) >= tokensForSale) { } else { tokens = buyAmount; } balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); lastBuyer = msg.sender; totalTokensSoldInThisSale = totalTokensSoldInThisSale.add(tokens); emit BuyTokens(msg.sender, tokens); emit Transfer(owner, msg.sender, tokens); isGoalReached(); isMaxCapReached(); }
2,073,859
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Certik DCK-01 import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol"; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Refer to Pancake SmartChef Contract: https://bscscan.com/address/0xCc2D359c3a99d9cfe8e6F31230142efF1C828e6D#readContract contract GameSlot is Ownable, ReentrancyGuard, IERC721Receiver { using SafeMath for uint256; using SafeBEP20 for IBEP20; IBEP20 public nativeToken; IBEP20 public gamePointToken; // The address of the manager address public SLOT_MANAGER; // Whether it is initialized bool public isInitialized; // The reserved tokens in the slot uint256 public reservedAmount; uint256 public unlockLimit; // GSD-03 uint256 public constant MAX_PERFORMANCE_FEE = 5000; // 50% uint256 public performanceFee = 200; // 2% // Whether it is suspended bool public suspended = false; uint256 public tokenId; address public ownerAccount; address public admin; IERC721 public NFT; // The NFT token address that each game provider should hold // address public treasury; address public treasury; // Send funds to blacklisted addresses are not allowed mapping(address => bool) public blacklistAddresses; event AdminTokenRecovery(address indexed tokenRecovered, uint256 amount); // Certik GSD-01 event EmergencyWithdraw(address indexed user, uint256 amount); event AddSlotEvent(uint256 indexed tokenId, address indexed gameAccount); event StatusChanged(address indexed slotAddress, bool suspended); event SlotUnlocked(address indexed user, address indexed gameAccount, uint256 amount); event AdminUpdated(address indexed user, address indexed admin); event Payout(address indexed user, address indexed receiver, uint256 amount); event CashoutPoints(address indexed user, uint256 amount); event AddToWhitelist(address indexed entry); event RemoveFromWhitelist(address indexed entry); event SetReservedAmount(uint256 amount); event SetPerformanceFee(uint256 amount); event SetUnlockLimitAmount(uint256 amount); event SetTreasury(address indexed amount); // Certik constructor( address _NFT, address _nativeToken, address _gamePointToken, uint256 _reservedAmount, address _manager ) public { require(_NFT != address(0), "_NFT is a zero address"); // Certik GSD-02 require(_nativeToken != address(0), "_nativeToken is a zero address"); require(_gamePointToken != address(0), "_gamePointToken is a zero address"); NFT = IERC721(_NFT); // Set manager to SlotManager rather than factory SLOT_MANAGER = _manager; nativeToken = IBEP20(_nativeToken); gamePointToken = IBEP20(_gamePointToken); reservedAmount = _reservedAmount; treasury = _manager; } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } /* * @notice Initialize the contract, owner may not be the msg.sender * @param _tokenId: tokenId of the NFT * @param _owner: The current owner of NFT */ function initialize( uint256 _tokenId, address _owner ) external { require(!isInitialized, "Already initialized"); require(msg.sender == SLOT_MANAGER, "Not manager"); tokenId = _tokenId; _add(_tokenId, _owner); // Make this contract initialized isInitialized = true; emit AddSlotEvent(_tokenId, msg.sender); } /** * Game provider to bid slot * @param _owner is the NFT owner (Game provider) * @param _tokenId is the token owned by owner and to be transffered into this slot */ function _add(uint256 _tokenId, address _owner) private nonReentrant { require(NFT.ownerOf(_tokenId) != address(this), "Already owner"); NFT.safeTransferFrom( _owner, address(this), _tokenId ); // require(NFT.ownerOf(_tokenId) == address(this), "Not received"); // Certik GSD-09 ownerAccount = _owner; // Admin account is set to same account of ownerAccount first admin = _owner; } /** * @notice This function is private and not privilege checking * Safe token transfer function for nativeToken, just in case if rounding error causes pool to not have enough tokens. */ function safeTransfer(address _to, uint256 _amount) private { uint256 bal = nativeToken.balanceOf(address(this)); if (_amount > bal) { nativeToken.safeTransfer(_to, bal); // Certik GSD-07 } else { nativeToken.safeTransfer(_to, _amount); // Certik GSD-07 } } /** * @notice This function is private and not privilege checking * Safe token transfer function for point token, just in case if rounding error causes pool to not have enough tokens. */ function safeTransferPoints(address _to, uint256 _amount) private { uint256 bal = gamePointToken.balanceOf(address(this)); if (_amount > bal) { gamePointToken.safeTransfer(_to, bal); // Certik GSD-07 } else { gamePointToken.safeTransfer(_to, _amount); // Certik GSD-07 } } // Owner is the GameSlot, and triggered by Game Slot owner / admin function payout(address _to, uint256 _amount) external nonReentrant { require(_to != address(0), "Cannot send to 0 address"); require(_amount > 0, "Must more than 0"); require(!suspended, "Slot is suspended"); require(msg.sender == admin, "Only the game admin can payout"); require(_balance() > reservedAmount, "Balance must more than reserved"); require(_amount <= (_balance() - reservedAmount), "Exceeded max payout-able amount"); require(!blacklistAddresses[_to], "user is blacklisted"); uint256 currentPerformanceFee = _amount.mul(performanceFee).div(10000); safeTransfer(treasury, currentPerformanceFee); safeTransfer(_to, _amount.sub(currentPerformanceFee)); emit Payout(msg.sender, _to, _amount); } /** * @notice Owner is the GameSlot, and triggered by Game Slot owner * There is no theshold to cashout */ function cashoutPoints(uint256 _amount) external nonReentrant { require(_amount > 0, "Must more than 0"); require(!suspended, "Slot is suspended"); require(msg.sender == admin || msg.sender == ownerAccount, "Only the game owner or admin can cashout"); require(_amount <= _balanceOfPoints(), "Exceeded max game points amount"); safeTransferPoints(ownerAccount, _amount); emit CashoutPoints(msg.sender, _amount); } /** * Unlock NFT and return the slot back * Only return the current tokenId back to ownerAccount * * TODO: need more rules to unlock slot */ function unlock() external onlyOwner { require(_balance() < unlockLimit, "Balance must be less than balance before unlock"); // Certik GSD-03 NFT.transferFrom( address(this), ownerAccount, tokenId ); isInitialized = false; emit SlotUnlocked(msg.sender, ownerAccount, tokenId); } function addToBlacklist(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "NULL_ADDRESS"); blacklistAddresses[entry] = true; emit AddToWhitelist(entry); } } function removeFromBlacklist(address[] calldata entries) external onlyOwner { for(uint256 i = 0; i < entries.length; i++) { address entry = entries[i]; require(entry != address(0), "NULL_ADDRESS"); blacklistAddresses[entry] = false; emit RemoveFromWhitelist(entry); } } /* * @notice Withdraw staked tokens without caring other factor * The funds will be sent to treasury, and the team need to manually refund back to users affected * * @dev TODO: Needs to be for emergency. */ function emergencyWithdraw() external onlyOwner { uint256 balance = _balance(); nativeToken.safeTransfer(treasury, balance); emit EmergencyWithdraw(msg.sender, balance); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(nativeToken), "Cannot be native token"); require(_tokenAddress != address(gamePointToken), "Cannot be point token"); IBEP20(_tokenAddress).safeTransfer(treasury, _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /** * @notice Sets Reserved Amount of native token * Can be zero only if the owner want to leave the slot * * @dev Only callable by the contract admin. */ function setAdmin(address _admin) external { require(_admin != address(0), "Address cannot be 0"); require(msg.sender == ownerAccount, "Only the game owener can update admin"); admin = _admin; emit AdminUpdated(msg.sender, _admin); } /** * @notice Sets Reserved Amount of native token * Can be zero only if the owner want to leave the slot * * @dev Only callable by the contract admin. */ function setReservedAmount(uint256 _reservedAmount) external onlyOwner { reservedAmount = _reservedAmount; emit SetReservedAmount(reservedAmount); } /** * @notice Only if unlockLimit is set and the balance is less than unlockLimit * Then it's able to unlock */ function setUnlockLimitAmount(uint256 _unlockLimit) external onlyOwner { unlockLimit = _unlockLimit; emit SetUnlockLimitAmount(_unlockLimit); } /** * @notice Sets performance fee * @dev Only callable by the contract admin. */ function setPerformanceFee(uint256 _performanceFee) external onlyOwner { require(_performanceFee <= MAX_PERFORMANCE_FEE, "performanceFee cannot be more than MAX_PERFORMANCE_FEE"); performanceFee = _performanceFee; emit SetPerformanceFee(performanceFee); } /** * @notice Sets treasury address * @dev Only callable by the contract owner. */ function setTreasury(address _treasury) external onlyOwner { require(_treasury != address(0), "Cannot be zero address"); treasury = _treasury; emit SetTreasury(treasury); } /** * @notice Sets treasury address * @dev Only callable by the contract owner. */ function flipSuspendState() external onlyOwner { suspended = !suspended; emit StatusChanged(msg.sender, suspended); } /** View functions */ function initialized() external view returns (bool) { return isInitialized; } function isSuspended() external view returns (bool) { return suspended; } function balanceOfPoints() external view returns (uint256) { return _balanceOfPoints(); } function _balanceOfPoints() private view returns (uint256) { return gamePointToken.balanceOf(address(this)); } function balance() external view returns (uint256) { return _balance(); } function _balance() private view returns (uint256) { return nativeToken.balanceOf(address(this)); } }
Only if unlockLimit is set and the balance is less than unlockLimit Then it's able to unlock/
function setUnlockLimitAmount(uint256 _unlockLimit) external onlyOwner { unlockLimit = _unlockLimit; emit SetUnlockLimitAmount(_unlockLimit); }
929,692
./full_match/1/0x8C874963E95128C48151a53d1A39826CcC9835Cc/sources/src/core/coins/ShortDurationYieldCoin.sol
Processes fees based on accrued interest takes fee based on new interest accumulated since the last time the function was called _interest is the balance with 2 decimals of precision _price is the last round price of SDYC/USD with 8 decimals of precision/ converting to SDYC decimal {6} + price decimals {8} take fee as percentage of interest in terms of SDYC price
function processFees(uint256 _interest, uint256 _price) external returns (uint256 fee) { if (msg.sender != address(oracle)) revert NoAccess(); uint256 mgmtFee = managementFee; if (mgmtFee == 0) return 0; _interest *= 1e12; fee = _interest.mulDivDown(mgmtFee, 100 * FEE_MULTIPLIER * _price); _mint(feeRecipient, fee); emit FeeProcessed(feeRecipient, fee); } ERC20 Functions
2,926,626
./partial_match/3/0xa190b106Be9F81de40c9469c05EEb881f6484D8b/sources/MasterChef.sol
Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVenPerShare).div(1e12).sub(user.rewardDebt); safeVenTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accVenPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
5,196,995
./partial_match/1/0x18B32bC20951b0eaE36247Aa5C8C22A77244d6cd/sources/contracts/ERC721X.sol
See {IERC721-ownerOf}./
function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721X: owner query for nonexistent token"); return _owners[tokenId] != address(0) ? _owners[tokenId] : _owners[tokenId - 1]; }
4,202,181
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private authorizedCaller = address(0); // Account used to deploy contract address private contractOwner; // Blocks all state changes throughout the contract if false bool private operational = true; struct Airline { bool isRegistered; bool isFunded; address airlineAddress; } //Maps airline address to struct mapping(address => Airline) public registeredAirlines; //Array of airline addresses; easier to get all of the registered airlines address[] public registered; //ACTIVE is the initial contract state after passenger has purchased insurance. //VOID is not currently used, but if the airline is not at fault for a late flight, then this status could be used to indicate the passenger should not receive a payouts //PAID indicates that the payout has been credited to the passenger enum InsContractStatusEnum {VOID,ACTIVE,PAID} struct InsContract { string flight; address passenger; uint256 insPaid; InsContractStatusEnum status; } //Maps passenger address to insurance contracts mapping(address => InsContract[]) private passengerInsurance; //Maps the flight to passenger address mapping(string => address[]) flightInsPassengers; //Maps passenger address to insurance credits mapping(address => uint256) private credits; /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address airline) public payable { contractOwner = msg.sender; registerFirstAirline(airline); } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizedCallerSet(address authorized); /********************************************************************************************/ /* 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 authorized caller to be the function caller */ modifier requireAuthorizedCaller() { require(authorizedCaller == msg.sender, "Caller is not authorized"); _; } /** * @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"); _; } /** * @dev Modifier that requires the contract owner to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires that the function be called by or is passed a registered airline */ modifier requireRegisteredAirline(address airline) { require(registeredAirlines[airline].isRegistered == true, "Caller is not a registered airline"); _; } /** * @dev Modifier that requires that the function be called by or is passed a funded airline */ modifier requireFundedAirline(address airline) { require(registeredAirlines[airline].isFunded == true, "Caller is not a funded airline"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Authorize the provided caller (this would be the FlightSuretyApp) */ function setAuthorizedCaller(address authorized) public requireContractOwner { authorizedCaller = authorized; emit AuthorizedCallerSet(authorized); } /** * @dev Retrieve the authorized caller address. For testing purposes only. * * @return returns the authorized caller */ function getAuthorizedCaller() public view returns(address) { return authorizedCaller; } /** * @dev Check 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; } /** * @dev Check if caller is authorized to access contract functions * * @return A bool that is the current operating status */ function isAuthorized(address caller) public view returns(bool) { return (authorizedCaller == caller); } /** * @dev Check if airline is registered * * @return true if airline is registered already */ function isRegistered(address airline) public view returns(bool) { return registeredAirlines[airline].isRegistered; } /** * @dev Check if airline is funded * * @return true if airline is already funded */ function isFunded(address airline) public view returns(bool) { return registeredAirlines[airline].isFunded; } /** * @dev Check if the passenger is already insured for a flight * * @return true if the passenger is insured for the flight */ function isInsured(address passenger, string flight) external view requireAuthorizedCaller returns(bool) { bool result = false; address[] insuredFlightPassengers = flightInsPassengers[flight]; for (uint i=0; i<insuredFlightPassengers.length; i++) { if (passenger == insuredFlightPassengers[i]) { result = true; break; } } return result; } /** * @dev Gets the list of insured passengers for a flight to process payout. * * @return Array of passenger addresses */ function getPassengersInsured(string flight) external view requireAuthorizedCaller requireIsOperational returns(address[] passengers) { return flightInsPassengers[flight]; } /** * @dev Gets the insured amount for a passenger for the specified flight * * @return the amount insured */ function getInsuredAmount(string flight, address passenger) external view requireIsOperational requireAuthorizedCaller returns(uint amount) { amount = 0; InsContract[] insContracts = passengerInsurance[passenger]; for (uint i=0; i<insContracts.length; i++) { if (insContracts[i].status == InsContractStatusEnum.ACTIVE) { amount = insContracts[i].insPaid; break; } } return amount; } /** * @dev Gets the passenger credits * * @return amount of passenger credits */ function getCredits(address passenger) external view requireIsOperational returns(uint creditsWei) { return credits[passenger]; } /** * @dev Gets the contract balance * * @return contract balance */ function getContractBalance() external view requireIsOperational returns(uint256) { return address(this).balance; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Register the first airline. This is performed during initialization. * */ function registerFirstAirline (address airline) internal requireIsOperational { require(msg.sender == contractOwner, "Only the contract owner may call this function"); registeredAirlines[airline] = Airline({isRegistered: true, isFunded: false, airlineAddress: airline}); registered.push(airline); } /** * @dev Register an airline * */ function registerAirline(address airline, address sender) external requireIsOperational requireAuthorizedCaller requireRegisteredAirline(sender) { require(!registeredAirlines[airline].isRegistered, "Airline is already registered."); registeredAirlines[airline] = Airline({isRegistered: true, isFunded: false, airlineAddress: airline}); registered.push(airline); } /** * @dev Get number of airlines registered * * @return the number of registered airlines */ function getNumRegisteredAirlines() external view requireIsOperational returns(uint256) { return registered.length; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining. * */ function fund(address airline) public requireIsOperational requireAuthorizedCaller { registeredAirlines[airline].isFunded = true; } /** * @dev Allows passengers to buy specified amount of insurance for a flight * */ function buy(address passenger, string flight, uint256 insAmount, address sender) public requireIsOperational requireAuthorizedCaller { passengerInsurance[passenger].push(InsContract({flight: flight, passenger: passenger, insPaid: insAmount, status: InsContractStatusEnum.ACTIVE})); flightInsPassengers[flight].push(passenger); } /** * @dev Credits payouts to insurees. * */ function creditInsuree(string flight, address passenger, uint amount) external requireIsOperational requireAuthorizedCaller { InsContract[] insContracts = passengerInsurance[passenger]; for (uint i=0; i<insContracts.length; i++) { if ((keccak256(abi.encodePacked((insContracts[i].flight)))) == (keccak256(abi.encodePacked(flight)))) { insContracts[i].status = InsContractStatusEnum.PAID; credits[passenger] = credits[passenger].add(amount); break; } } } /** * @dev Transfers eligible payout funds to insuree. * * @return the amount that is paid to the insuree */ function pay(address passenger) external payable requireIsOperational returns(uint) { require(credits[passenger] > 0, "There are no credits available."); uint amount = credits[passenger]; credits[passenger] = 0; //contractBalance = contractBalance.sub(amount); passenger.transfer(amount); return amount; } /** * @dev Enables the FlightSuretyApp to transfer money to this contract. Fallback function for funding smart contract. * */ function() external payable { //fund(); } }
Credits payouts to insurees./
function creditInsuree(string flight, address passenger, uint amount) external requireIsOperational requireAuthorizedCaller { InsContract[] insContracts = passengerInsurance[passenger]; for (uint i=0; i<insContracts.length; i++) { if ((keccak256(abi.encodePacked((insContracts[i].flight)))) == (keccak256(abi.encodePacked(flight)))) { insContracts[i].status = InsContractStatusEnum.PAID; credits[passenger] = credits[passenger].add(amount); break; } } }
7,265,405
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
update totalRewardsEarned, update cumulative profit per lp token
function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount
1,731,149
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title A storage for book rights /// @author Ifebhor Odion Nonse /// @notice This contract is used to mint the rights to a book /// in form of a token which can then be sold on a marketplace /// @dev this is an ERC721 token contract OpenBooks is Ownable, ERC721("OpenBooks", "OPB"){ /// @notice Initializes the contract /// @dev sets the _baseURI /// @param _baseURI the string to be stored as _baseURI. constructor(string memory _baseURI) public{ _setBaseURI(_baseURI); } /// @notice Creates a new book /// @dev mints a book with a unique a id /// @param _tokenURI the URI of the books image function mint(string calldata _tokenURI) external{ uint tokenId = totalSupply().add(1); _safeMint(msg.sender, tokenId, ""); _setTokenURI(tokenId, _tokenURI); } /// @notice Destroys a book /// @dev removes the books id from the list and sends to a zero address /// @param _tokenId the id of the book to be burnt function burn(uint _tokenId) external{ _burn(_tokenId); } /// @notice Used to check if a book with an id exists /// @param _tokenId the id of the book to be checked /// @return a boolean, "true" if it exists and "false" if it doesn't function exists(uint _tokenId) external view returns(bool){ return _exists(_tokenId); } /// @notice Changes the _baseURI to one supplied /// @dev can only be called by the contract's owner /// @param _baseURI the new _baseURI function setBaseURI(string calldata _baseURI) external onlyOwner{ _setBaseURI(_baseURI); } }
Creates a new book mints a book with a unique a id _tokenURI the URI of the books image
function mint(string calldata _tokenURI) external{ uint tokenId = totalSupply().add(1); _safeMint(msg.sender, tokenId, ""); _setTokenURI(tokenId, _tokenURI); }
7,275,932
./full_match/3/0x904cd015Ea7a66Bc347A0E9b446165cCEDA098D5/sources/reserver.eth.sol
Function rounds up after input of 4.
function log2(uint x) public pure returns (uint y) {
8,091,172
./full_match/5/0xd93e66F6DC9bf63009690FB0860058A5453bdd56/sources/contracts/Equb.sol
Find the pool by equbAddresscheck the member skip countCheck the current date and compare it to the contribution date uint256 today = getCountDown(pools[poolIndex].contributionDate,);check if this is first time that member skip contributionincrement the skip countEmit eventremove the member from the pool If the transfer was successful, update the amount raised by the campaign
function contribution( address equbAddress, address member, uint contAmount ) public payable { uint poolIndex = getPoolIndex(equbAddress); uint amount = priceConsumer.convertUsdToEth(contAmount) / 10000000000; uint skipCount = getRemainingSkipCount(equbAddress, member); if (skipCount < 3) { removeMember(equbAddress, member); revert( "You have skipped the contribution for three times, You will be removed from the pool." ); } require( msg.value == amount, "The cont amount must be equal to contributionAmount" ); if (contributions[equbAddress][member]) { pools[poolIndex].contributionSkipCount += 1; emit SkipContributionEvent(member, equbAddress); if (skipCount == 2) { removeMember(equbAddress, member); emit MemberRemovedEvent(member, equbAddress); } if (success) { pools[poolIndex].equbBalance += msg.value; } member, amount, pools[poolIndex].equbBalance ); uint256 nextContribution = getCountDown( pools[poolIndex].contributionDate ); emit NextContributionTime(nextContribution); } }
1,876,596
./full_match/8453/0x7690166442e81B473D6eb413e865AA6379490371/sources/contracts/tokenlock/TokenLock.sol
Gets surplus amount in the contract based on outstanding amount to release All funds over outstanding amount is considered surplus that can be withdrawn by beneficiary return Amount of tokens considered as surplus/
function surplusAmount() public override view returns (uint256) { uint256 balance = currentBalance(); uint256 outstandingAmount = totalOutstandingAmount(); if (balance > outstandingAmount) { return balance - outstandingAmount; } return 0; }
11,541,232
./full_match/56/0x3260Ebd17d9038d2C2a3b24FFe5c8f1eA10603df/sources/project_/contracts/ClimbToken.sol
Updates The Sell, Mint, and Transfer Fees /
function updateFees( uint256 newSellFee, uint256 newMintFee, uint256 newTransferFee ) external onlyOwner { require( newSellFee <= 995 && newMintFee <= 995 && newTransferFee <= 995, "invalid fees" ); sellFee = newSellFee; mintFee = newMintFee; transferFee = newTransferFee; emit UpdateFees(sellFee, mintFee, transferFee); }
3,243,860
pragma solidity ^0.4.24; contract Pokemon { uint public pokemonCount = 0; uint public wildPokemonCount = 0; uint public tradePokemonCount = 0; constructor () public { _createPokemon("Pikachu", "Lightning", 2, 100); _createPokemon("Charizard", "Fire", 4, 200); _createPokemon("Snorlax", "Earth", 3, 50); _createPokemon("Magikarp", "Water",1, 25); _createPokemon("Onyx", "Earth", 4, 150); } struct Pokemon { uint256 pokId; // Id for each unique pokemon string name; // Name of the pokemon string pokType; // monType of the pokemon -- "Fire, Earth, Water, Air, Lightning" uint64 level; // Level for each pokemon uint64 exp; // Experience acquired by a pokemon uint64 value; // Value of the pokemon in some units uint64 train_value; // value required to train pokemon. } Pokemon[] public pokemons; // A list of ALL the pokemons in existence uint256[] public wildPokemons; mapping(uint256 => uint) public tradePokemons; // 1 if a pokemon is tradeble, otherwise 0 mapping(uint256 => uint) public trainPokemon; mapping(uint256 => uint256) public tradeTime; mapping(uint256 => address) public pokIndexToOwner; // The mapping defining the owner of specific pokemon mapping(address => uint) public pendingReturns; // Storing the pending returns of some user mapping(address => uint256[]) public ownedPoks; // All the pokemons owned by an address(includes the ones which are trade market also) mapping(address => uint256) public ownedPoksCount; // The number of pokemons owned by an address(includes the tradable ones also) mapping(address => uint256) public tradePoksCount; // Number of pokemons put up for trade by and address mapping(uint256 => uint256) public pokemonTransactionHash; // Store the transaction with which the pokemon is related to //Getter functions // Events -- front end will update if it is listening to an event event Transferred(address _from, address _to, uint256 _pokId, uint256 txnHash); event PokemonCreated(uint256 _pokId, string _name, uint64 _level, string _pokType, uint _value, uint256 txnHash); event TradingTurnedOn(uint256 _pokId, address _owner, uint256 txnHash); event TradingTurnedOff(uint256 _pokId, address _owner, uint256 txnHash); /* Function to transfer pokemon from one address to another */ function _transfer(address _from, address _to, uint256 _pokId) internal { require(_from == pokIndexToOwner[_pokId], "You are not the owner of the pokemon"); require(_to != pokIndexToOwner[_pokId], "You can not transfer the pokemon to yourselves"); uint i = 0; pokIndexToOwner[_pokId] = _to; ownedPoks[_to].push(_pokId); ownedPoksCount[_to]++; tradePokemons[_pokId] = 0; // Trading is turned off when the pokemon is bought by someone else /* When some user already owns the pokemon */ if(_from != address(0)) { /* Deleting the pokemon from previous owner's array */ for(i = 0;i < ownedPoks[_from].length; i++) { if(ownedPoks[_from][i] == _pokId) break; } ownedPoks[_from][i] = ownedPoks[_from][ownedPoks[_from].length - 1]; delete ownedPoks[_from][ownedPoks[_from].length - 1]; ownedPoks[_from].length--; ownedPoksCount[_from]--; tradePoksCount[_from]--; // This traded pokemon is now sold tradePokemonCount--; // Total number of tradable pokemon in the market reduces by one } else { for(uint j = 0; j < wildPokemons.length; j++) { if(wildPokemons[j] == _pokId) break; } wildPokemons[j] = wildPokemons[wildPokemons.length - 1]; delete wildPokemons[wildPokemons.length - 1]; wildPokemons.length--; wildPokemonCount--; } pokemonTransactionHash[_pokId]++; emit Transferred (_from, _to, _pokId, pokemonTransactionHash[_pokId]); } /* Function to buy a pokemon from the trade market */ function buyFromTradeMarket(uint256 _pokId) public payable { require(msg.value >= pokemons[_pokId].value, "Did not supply the proper amount"); pendingReturns[pokIndexToOwner[_pokId]] += pokemons[_pokId].value; pendingReturns[msg.sender] += msg.value - pokemons[_pokId].value; _transfer(pokIndexToOwner[_pokId], msg.sender, _pokId); // Transfer the ownership of pokemon to the buyer } /* Function to disable trade on a pokemon that is put up for sale on trade market */ function disableTrade(uint256 _pokId) public returns(bool) { require(msg.sender == pokIndexToOwner[_pokId], "You are not the owner of this pokemon"); tradePokemons[_pokId] = 0; tradePokemonCount--; tradePoksCount[msg.sender]--; pokemonTransactionHash[_pokId]++; emit TradingTurnedOff(_pokId, msg.sender, pokemonTransactionHash[_pokId]); return true; } /* Function to allow trading of a pokemon */ function allowTrading(uint64 _value, uint256 _pokId) public returns(bool){ require(now >= tradeTime[_pokId], "Trade disallowed at this timestamp."); require(msg.sender == pokIndexToOwner[_pokId], "You are not the owner of this pokemon"); tradePokemons[_pokId] = 1; tradePokemonCount++; tradePoksCount[msg.sender]++; pokemons[_pokId].value = _value; pokemonTransactionHash[_pokId]++; emit TradingTurnedOn(_pokId, msg.sender, pokemonTransactionHash[_pokId]); return true; } /* Function to create pokemon */ function _createPokemon(string _name, string _pokType, uint64 _level, uint64 _value) internal returns(uint256) { Pokemon memory _pokemon = Pokemon({ pokId : pokemonCount, name : _name, pokType : _pokType, level : _level, exp : 0, value : _value, train_value : 0 }); wildPokemons.push(pokemonCount); wildPokemonCount++; pokemons.push(_pokemon); pokemonTransactionHash[_pokemon.pokId]++; emit PokemonCreated(pokemonCount, _name ,_level, _pokType, _value, pokemonTransactionHash[_pokemon.pokId]); pokemonCount++; return pokemonCount; } /* Function to catch pokemon's One needs to pay some amount to catch the pokemon Returns true if the pokemon is caught Else return's false */ function catchPokemon(uint256 pokID) public payable returns(bool) { require(pokIndexToOwner[pokID] == address(0), "This pokemon is already caught by someone"); require(pokemons[pokID].value <= msg.value, "Not supplied the required amount"); _transfer(0, msg.sender, pokID); pendingReturns[msg.sender] += msg.value - pokemons[pokID].value; tradeTime[pokID] = now; return true; } function trainPokemon(uint256 pokId) public payable returns(bool) { // console.log(now); require(tradeTime[pokId] <= now, "The pokemon is not eligible for training."); require(tradePokemons[pokId] == 0, "The pokemon is not eligible for training."); require(pokIndexToOwner[pokId] == msg.sender, "You should own the pokemon to train it."); require(pokemons[pokId].train_value <= msg.value, "Insufficient funds for training."); pendingReturns[msg.sender] += msg.value - pokemons[pokId].train_value; pokemons[pokId].level +=1; tradeTime[pokId] = now + 25; } function withdraw() public returns(bool) { uint amount = pendingReturns[msg.sender]; if(amount > 0){ pendingReturns[msg.sender] = 0; msg.sender.transfer(amount); } return true; } }
Function to transfer pokemon from one address to another / When some user already owns the pokemon / Deleting the pokemon from previous owner's array /
function _transfer(address _from, address _to, uint256 _pokId) internal { require(_from == pokIndexToOwner[_pokId], "You are not the owner of the pokemon"); require(_to != pokIndexToOwner[_pokId], "You can not transfer the pokemon to yourselves"); uint i = 0; pokIndexToOwner[_pokId] = _to; ownedPoks[_to].push(_pokId); ownedPoksCount[_to]++; if(_from != address(0)) { for(i = 0;i < ownedPoks[_from].length; i++) { if(ownedPoks[_from][i] == _pokId) break; } ownedPoks[_from][i] = ownedPoks[_from][ownedPoks[_from].length - 1]; delete ownedPoks[_from][ownedPoks[_from].length - 1]; ownedPoks[_from].length--; ownedPoksCount[_from]--; } else { for(uint j = 0; j < wildPokemons.length; j++) { if(wildPokemons[j] == _pokId) break; } wildPokemons[j] = wildPokemons[wildPokemons.length - 1]; delete wildPokemons[wildPokemons.length - 1]; wildPokemons.length--; wildPokemonCount--; } pokemonTransactionHash[_pokId]++; emit Transferred (_from, _to, _pokId, pokemonTransactionHash[_pokId]); }
5,526,875
./full_match/5/0x009f95073E1755834Bc1BE9E4989eA0696b7c48D/sources/contracts/Vault.sol
Returns the current underlying (e.g., DAI's) balance together with the invested amount (if DAI is invested elsewhere by the strategy)./ initial state, when not set
function underlyingBalanceWithInvestment() public view override returns (uint256) { if (address(strategy()) == address(0)) { return underlyingBalanceInVault(); } return underlyingBalanceInVault().add( IStrategy(strategy()).investedUnderlyingBalance() ); }
1,908,138
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./SafeMath.sol"; import "./IUniswapV2Router02.sol"; import "./IUniswapV2Factory.sol"; import "./IFactoryV2.sol"; import "./IERC20.sol"; import "./IUniswapV2Pair.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; contract LIFEGAMES is ERC20Upgradeable { using SafeMath for uint256; struct Fees { uint16 distributionToHoldersFee; uint16 buyFee; uint16 sellFee; uint16 transferFee; } struct StaticValuesStruct { uint16 maxTotalFee; uint16 maxDistributionToHoldersFee; uint16 maxBuyFee; uint16 maxSellFee; uint16 maxTransferFee; uint16 masterTaxDivisor; } struct Ratios { uint16 liquidityRatio; uint16 buyBurnRatio; uint16 total; } Fees public _taxRates; Ratios public _ratios; StaticValuesStruct public staticVals; // reflection uint256 private _tTotal; uint256 private MAX; uint256 private _rTotal; uint256 private _tFeeTotal; uint16 private _previousTaxFee; mapping(address => uint256) private _rOwned; address[] private _excluded; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; bool public takeFeeEnabled; // --------------------------------------------------- bool private gasLimitActive; uint256 private gasPriceLimit; // 15 gWei / gWei -> Default 10 mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled; uint256 private initialBlock; bool private autoAddliquidityEnabled; uint256 private autoliquidityTokenPriceThreshold; uint256 public autoAddliquidityThreshold; event Burn( address indexed sender, uint256 amount ); //mapping(address => bool) public bridges; address private _owner; mapping(address => uint256) _tOwned; mapping(address => bool) private lpPairs; uint256 private timeSinceLastPair; mapping(address => mapping(address => uint256)) _allowances; mapping(address => bool) _isFeeExcluded; mapping(address => bool) private _isSniper; mapping(address => bool) private _liquidityRatioHolders; string private _name; string private _symbol; uint8 private _decimals; uint256 private snipeBlockAmt; uint256 public snipersCaught; bool private sameBlockActive; bool private sniperProtection; uint256 private _liqAddBlock; IUniswapV2Router02 public dexRouter; address public lpPair; address public DEAD; address public zero; address payable public busdForLiquidityAddress; address payable public busdBuyBurnAddress; bool public contractSwapEnabled; uint256 public swapThreshold ; uint256 public swapAmount; bool inSwap; bool public tradingActive; //bool public hasLiqBeenAdded; address public busdAddress; uint256 whaleFeePercent; uint256 whaleFee; bool public transferToPoolsOnSwaps; modifier swapping() { inSwap = true; _; inSwap = false; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event ContractSwapEnabledUpdated(bool enabled); event AutoLiquify(uint256 amountAVAX, uint256 amount); event SniperCaught(address sniperAddress); function initialize() public initializer { __ERC20_init("LIFEGAMES", "LFG"); _mint(msg.sender, 1 * 1e7 * 1e18); _owner = msg.sender; address[] memory addresses = new address[](4); addresses[0] = 0x78867BbEeF44f2326bF8DDd1941a4439382EF2A7; addresses[1] = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3; addresses[2] = 0xd235eD438FB2D6Bd428F5AEdF67bc8AB03bcFB96; addresses[3] = 0x09f33F64aAADf6A02956C9732b25d42DD9c2d4bC; _taxRates = Fees({ distributionToHoldersFee : 150, buyFee : 150, sellFee : 150, transferFee : 0 }); _ratios = Ratios({ liquidityRatio : 50, buyBurnRatio : 100, total : 150 }); staticVals = StaticValuesStruct({ maxTotalFee : 300, maxDistributionToHoldersFee : 300, maxBuyFee : 300, maxSellFee : 300, maxTransferFee : 300, masterTaxDivisor : 10000 }); _tTotal = 1 * 1e7 * 1e18; MAX = ~uint256(0); _rTotal = (MAX - (MAX % _tTotal)); _tFeeTotal; _previousTaxFee = 0; takeFeeEnabled = true; gasLimitActive = false; gasPriceLimit = 15000000000; // 15 gWei / gWei -> Default 10 transferDelayEnabled = false; autoAddliquidityEnabled = false; autoliquidityTokenPriceThreshold = 1000000000000000000; autoAddliquidityThreshold = 0; timeSinceLastPair = 0; _name = "LIFEGAMES"; _symbol = "LFG"; _decimals = 18; snipeBlockAmt = 0; snipersCaught = 0; sameBlockActive = true; sniperProtection = true; _liqAddBlock = 0; DEAD = 0x000000000000000000000000000000000000dEaD; zero = 0x0000000000000000000000000000000000000000; contractSwapEnabled = true; swapThreshold = 100000000000000000000; swapAmount = 99000000000000000000; tradingActive = false; //hasLiqBeenAdded = false; whaleFeePercent = 0; whaleFee = 0; transferToPoolsOnSwaps = false; // constructor _rOwned[msg.sender] = _rTotal; _owner = msg.sender; busdAddress = address(addresses[0]); _isExcludedFromFee[_owner] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[busdAddress] = true; // exclude LiquidityAddress and busdBuyBurnAddress _isExcludedFromFee[addresses[2]] = true; _isExcludedFromFee[addresses[3]] = true; _approve(msg.sender, addresses[1], type(uint256).max); _approve(address(this), addresses[2], type(uint256).max); _approve(msg.sender, busdAddress, type(uint256).max); _approve(address(this), busdAddress, type(uint256).max); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(addresses[1]); lpPair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), busdAddress); lpPairs[lpPair] = true; dexRouter = _uniswapV2Router; setLiquidityAddress(addresses[2]); setBusdBuyBurnAddress(addresses[3]); initialBlock = block.number; emit Transfer(zero, msg.sender, _tTotal); emit OwnershipTransferred(address(0), msg.sender); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and renouncements. // This allows for removal of ownership privileges from the owner once renounced or transferred. function owner() public view returns (address) { return _owner; } function transferOwner(address newOwner) external onlyOwner { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); _isFeeExcluded[_owner] = false; _isFeeExcluded[newOwner] = true; if (_tOwned[_owner] > 0) { _transfer(_owner, newOwner, _tOwned[_owner]); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== receive() external payable {} function totalSupply() public view virtual override returns (uint256) {return _tTotal;} function decimals() public view virtual override returns (uint8) {return _decimals;} function symbol() public view virtual override returns (string memory) {return _symbol;} function name() public view virtual override returns (string memory) {return _name;} function getOwner() external view returns (address) {return owner();} function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function allowance(address tokenOwner, address spender) public view virtual override returns (uint256) {return _allowances[tokenOwner][spender];} function approve(address spender, uint256 amount) public virtual override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function _approve( address tokenOwner, address spender, uint256 amount ) internal virtual override { require(tokenOwner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[tokenOwner][spender] = amount; emit Approval(tokenOwner, spender, amount); } function transfer(address to, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, to, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function isFeeExcluded(address account) public view returns (bool) { return _isFeeExcluded[account]; } function enableTrading() public onlyOwner { require(!tradingActive, "Trading already enabled!"); //require(hasLiqBeenAdded, "liquidityRatio must be added."); _liqAddBlock = block.number; tradingActive = true; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function setTaxes(uint16 distributionToHoldersFee, uint16 buyFee, uint16 sellFee, uint16 transferFee) external onlyOwner { // check each individual fee dont be higer than 3% require( distributionToHoldersFee <= staticVals.maxDistributionToHoldersFee && buyFee <= staticVals.maxBuyFee && sellFee <= staticVals.maxSellFee && transferFee <= staticVals.maxTransferFee, "MAX TOTAL BUY FEES EXCEEDED 3%"); // check max fee dont be higer than 3% require((distributionToHoldersFee + buyFee + transferFee) <= staticVals.maxTotalFee, "MAX TOTAL BUY FEES EXCEEDED 3%"); require((distributionToHoldersFee + sellFee + transferFee) <= staticVals.maxTotalFee, "MAX TOTAL SELL FEES EXCEEDED 3%"); _taxRates.distributionToHoldersFee = distributionToHoldersFee; _taxRates.buyFee = buyFee; _taxRates.sellFee = sellFee; _taxRates.transferFee = transferFee; } function setRatios(uint16 liquidityRatio, uint16 buyBurnRatio) external onlyOwner { _ratios.liquidityRatio = liquidityRatio; _ratios.buyBurnRatio = buyBurnRatio; _ratios.total = liquidityRatio + buyBurnRatio; } function setLiquidityAddress(address _busdForLiquidityAddress) public onlyOwner { require( _busdForLiquidityAddress != address(0), "_busdForLiquidityAddress address cannot be 0" ); busdForLiquidityAddress = payable(_busdForLiquidityAddress); } function setBusdBuyBurnAddress(address _busdBuyBurnAddress) public onlyOwner { require( _busdBuyBurnAddress != address(0), "_busdBuyBurnAddress address cannot be 0" ); busdBuyBurnAddress = payable(_busdBuyBurnAddress); } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; } function getCirculatingSupply() public view returns (uint256) { return (_tTotal - (balanceOf(DEAD) + balanceOf(address(0)))); } function setNewRouter(address newRouter, address busd) public onlyOwner() { //require(!hasLiqBeenAdded); IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IFactoryV2(_newRouter.factory()).getPair(address(busd), address(this)); if (get_pair == address(0)) { lpPair = IFactoryV2(_newRouter.factory()).createPair(address(busd), address(this)); } else { lpPair = get_pair; } lpPairs[lpPair] = true; dexRouter = _newRouter; _approve(address(this), address(dexRouter), type(uint256).max); } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled = false) { lpPairs[pair] = false; } else { if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 3 days, "Cannot set a new pair this week!"); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } function _hasLimits(address from, address to) private view returns (bool) { return from != _owner && to != _owner && tx.origin != _owner && !_liquidityRatioHolders[to] && !_liquidityRatioHolders[from] && to != DEAD && to != address(0) && from != address(this); } function _transfer( address from, address to, uint256 amount ) internal virtual override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (_hasLimits(from, to)) { if (!tradingActive) { revert("Trading not yet enabled!"); } } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && lpPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled && block.number < (initialBlock + (1200))) { if (transferDelayEnabled && block.number < (initialBlock + 60)) { if (from != owner() && to != address(dexRouter) && to != address(lpPair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _finalizeTransfer(from, to, amount, takeFee && takeFeeEnabled); } function _finalizeTransfer(address from, address to, uint256 amount, bool takeFee) internal returns (bool) { if (inSwap) { removeAllFee(); _tokenTransferNoFee(from, to, amount); restoreAllFee(); return true; } uint256 contractTokenBalance = balanceOf(address(this)); if ( contractTokenBalance >= swapThreshold && !inSwap && from != lpPair && balanceOf(lpPair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && contractSwapEnabled ) { contractSwap(contractTokenBalance); } //uint256 amountReceived = amount; // apply buy, sell or transfer fees if (takeFee) { // BUY if (from == lpPair) { } // SELL else if (to == lpPair) { } // TRANSFER else { removeAllFee(); _tokenTransferNoFee(from, to, amount); restoreAllFee(); return true; } takeBuySellTransferFee(from, to, amount); } _tokenTransfer(from, to, amount, takeFee); return true; } // todo max whale fees function setWhaleFeesPercentage(uint256 _whaleFeePercent) external onlyOwner { whaleFeePercent = _whaleFeePercent; } function updateAutoliquidityTokenPriceThreshold(bool newVal) external onlyOwner { transferDelayEnabled = newVal; } // todo max whale fees function setWhaleFees(uint256 _whaleFee) external onlyOwner { whaleFee = _whaleFee; } function takeBuySellTransferFee(address from, address to, uint256 amount) internal returns (uint256) { uint256 takesAmount = 0; uint256 totalFee = 0; // BUY if (from == lpPair) { if (_taxRates.buyFee > 0) { totalFee += _taxRates.buyFee; } } // SELL else if (to == lpPair) { if (_taxRates.sellFee > 0) { totalFee += _taxRates.sellFee; } } // TRANSFER else { if (_taxRates.transferFee > 0) { totalFee += _taxRates.transferFee; } } // CALC FEES AMOUT AND SEND TO CONTRACT if (totalFee > 0) { uint256 feeAmount = (amount * totalFee) / staticVals.masterTaxDivisor; _takeFees(feeAmount); emit Transfer(from, address(this), feeAmount); takesAmount = amount - feeAmount; } return takesAmount; } function contractSwap(uint256 numTokensToSwap) internal swapping { // cancel swap if fees are zero if (_ratios.total == 0) { return; } // check allowances // todo if (_allowances[address(this)][address(dexRouter)] != type(uint256).max) { _allowances[address(this)][address(dexRouter)] = type(uint256).max; } // calculate percentage to bsud reserver and manual buyback and burn uint256 tokensToliquidityAmount = (numTokensToSwap * _ratios.liquidityRatio) / (_ratios.total); uint256 tokensToBuyBurnAmount = (numTokensToSwap * _ratios.buyBurnRatio) / (_ratios.total); //uint256 minOut = getOutEstimatedTokensForTokens(address(this), busdAddress, numTokensToSwap); // swap tokens for busd and send to busd liquidity address if (tokensToliquidityAmount > 0) { address[] memory tokensBusdPath = getPathForTokensToTokens(address(this), busdAddress); IERC20(address(this)).approve(address(dexRouter), numTokensToSwap); IERC20(busdAddress).approve(address(dexRouter), numTokensToSwap); dexRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokensToliquidityAmount, 0, tokensBusdPath, busdForLiquidityAddress, block.timestamp + 600 ); } // swap tokens for busd and send to manual busd buyback and burn address if (tokensToBuyBurnAmount > 0) { address[] memory tokensBusdPath = getPathForTokensToTokens(address(this), busdAddress); IERC20(address(this)).approve(address(dexRouter), numTokensToSwap); IERC20(busdAddress).approve(address(dexRouter), numTokensToSwap); dexRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokensToBuyBurnAmount, 0, tokensBusdPath, busdBuyBurnAddress, block.timestamp + 600 ); } // todo test auto liquidityRatio if (autoAddliquidityEnabled) { uint256 tokenPriceInBusd = getOutEstimatedTokensForTokens(address(this), busdAddress, 1000000000000000000); // todo create update autoliquidity price condition if (tokenPriceInBusd > autoliquidityTokenPriceThreshold) { // amounts uint256 estimatedTokensForAutoliquidity = getOutEstimatedTokensForTokens(address(this), busdAddress, 100000000000000000000); uint256 estimatedBusdForAutoliquidity = getOutEstimatedTokensForTokens(busdAddress, address(this), estimatedTokensForAutoliquidity); // if hit threshold // transfer tokens and busd contract if (estimatedTokensForAutoliquidity > autoAddliquidityThreshold) { IERC20(address(busdAddress)).transferFrom(busdForLiquidityAddress, address(this), estimatedBusdForAutoliquidity); IERC20(address(busdAddress)).transferFrom(busdBuyBurnAddress, address(this), estimatedTokensForAutoliquidity); // swap busd for tokens? addLiquidity(address(this), busdAddress, estimatedTokensForAutoliquidity, estimatedBusdForAutoliquidity, 0, 0, owner()); } } } } function _checkliquidityRatioAdd(address from, address to) private { //require(!hasLiqBeenAdded, "liquidityRatio already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { _liqAddBlock = block.number; _liquidityRatioHolders[from] = true; //hasLiqBeenAdded = true; contractSwapEnabled = true; emit ContractSwapEnabledUpdated(true); } } function multiSendTokens(address[] memory accounts, uint256[] memory amounts) external { require(accounts.length == amounts.length, "Lengths do not match."); for (uint8 i = 0; i < accounts.length; i++) { require(_tOwned[msg.sender] >= amounts[i]); _transfer(msg.sender, accounts[i], amounts[i] * 10 ** _decimals); } } function multiSendPercents(address[] memory accounts, uint256[] memory percents, uint256[] memory divisors) external { require(accounts.length == percents.length && percents.length == divisors.length, "Lengths do not match."); for (uint8 i = 0; i < accounts.length; i++) { require(_tOwned[msg.sender] >= (_tTotal * percents[i]) / divisors[i]); _transfer(msg.sender, accounts[i], (_tTotal * percents[i]) / divisors[i]); } } function updateTransferToPoolsOnSwaps(bool newValue) external onlyOwner { transferToPoolsOnSwaps = newValue; } function updateBUSDAddress(address newAddress) external onlyOwner { require(newAddress != address(0), "ROUTER CANNOT BE ZERO"); require( newAddress != address(busdAddress), "TKN: The BUSD already has that address" ); busdAddress = address(newAddress); } function updateAutoAddliquidityEnabled(bool newValue) external onlyOwner { autoAddliquidityEnabled = newValue; } function updateAutoAddliquidityThreshold(uint256 newValue) external onlyOwner { autoAddliquidityThreshold = newValue; } function getReserves() public view returns (uint[] memory) { IUniswapV2Pair pair = IUniswapV2Pair(lpPair); (uint Res0, uint Res1,) = pair.getReserves(); uint[] memory reserves = new uint[](2); reserves[0] = Res0; reserves[1] = Res1; return reserves; } function getTokenPrice(uint amount) public view returns (uint) { uint[] memory reserves = getReserves(); uint res0 = reserves[0] * (10 ** _decimals); return ((amount * res0) / reserves[1]); // return amount of token0 needed to buy token1 } function getOutEstimatedTokensForTokens(address tokenAddressA, address tokenAddressB, uint amount) public view returns (uint256) { return dexRouter.getAmountsOut(amount, getPathForTokensToTokens(tokenAddressA, tokenAddressB))[1]; } function getInEstimatedTokensForTokens(address tokenAddressA, address tokenAddressB, uint amount) public view returns (uint256) { return dexRouter.getAmountsIn(amount, getPathForTokensToTokens(tokenAddressA, tokenAddressB))[1]; } function getPathForTokensToTokens(address tokenAddressA, address tokenAddressB) private pure returns (address[] memory) { address[] memory path = new address[](2); path[0] = tokenAddressA; path[1] = tokenAddressB; return path; } function burn(address to, uint256 amount) public { require(amount >= 0, "Burn amount should be greater than zero"); if (msg.sender != to) { uint256 currentAllowance = _allowances[to][msg.sender]; if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); } } require( amount <= balanceOf(to), "Burn amount should be less than account balance" ); _tOwned[to] = _tOwned[to] - amount; _tTotal = _tTotal - amount; emit Burn(to, amount); } // reflection ------------------------------------------------------------------------------------------- function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxRates.distributionToHoldersFee).div(staticVals.masterTaxDivisor); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) internal view returns (uint256) { require(tAmount <= _tTotal, "Amt must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) internal view returns (uint256) { require(rAmount <= _rTotal, "Amt must be less than tot refl"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function excludeFromReward(address account) public onlyOwner() { require(!_isFeeExcluded[account], "Account is already excluded from reward"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isFeeExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if (_taxRates.distributionToHoldersFee == 0) return; _previousTaxFee = _taxRates.distributionToHoldersFee; _taxRates.distributionToHoldersFee = 0; } function restoreAllFee() private { _taxRates.distributionToHoldersFee = _previousTaxFee; } function _takeFees(uint256 tFee) private { uint256 currentRate = _getRate(); uint256 rFee = tFee.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rFee); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tFee); } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _tokenTransferNoFee(address sender, address recipient, uint256 amount) private { uint256 currentRate = _getRate(); uint256 rAmount = amount.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rAmount); if (_isExcluded[sender]) { _tOwned[sender] = _tOwned[sender].sub(amount); } if (_isExcluded[recipient]) { _tOwned[recipient] = _tOwned[recipient].add(amount); } emit Transfer(sender, recipient, amount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private returns (bool) { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); return true; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to ) private { _approve(address(this), address(dexRouter), amountADesired); _approve(address(this), address(dexRouter), amountBDesired); dexRouter.addLiquidity( tokenA, tokenB, amountADesired, // slippage is unavoidable amountBDesired, // slippage is unavoidable amountAMin, amountBMin, to, block.timestamp ); } }
todo max whale fees
function setWhaleFees(uint256 _whaleFee) external onlyOwner { whaleFee = _whaleFee; }
12,942,783
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./Accountant.sol"; import "./CreditLine.sol"; import "./CreditLineFactory.sol"; /** * @title Goldfinch's CreditDesk contract * @notice Main entry point for borrowers and underwriters. * Handles key logic for creating CreditLine's, borrowing money, repayment, etc. * @author Goldfinch */ contract CreditDesk is BaseUpgradeablePausable, ICreditDesk { // Approximate number of blocks per day uint256 public constant BLOCKS_PER_DAY = 5760; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; struct Underwriter { uint256 governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentApplied( address indexed payer, address indexed creditLine, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount ); event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; mapping(address => address) private creditLines; /** * @notice Run only once, on initialization * @param owner The address of who should have the "OWNER_ROLE" of this contract * @param _config The address of the GoldfinchConfig contract */ function initialize(address owner, GoldfinchConfig _config) public initializer { __BaseUpgradeablePausable__init(owner); config = _config; } /** * @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create" * @param underwriterAddress The address of the underwriter for whom the limit shall change * @param limit What the new limit will be set to * Requirements: * * - the caller must have the `OWNER_ROLE`. */ function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external override onlyAdmin whenNotPaused { require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol"); underwriters[underwriterAddress].governanceLimit = limit; emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit); } /** * @notice Allows an underwriter to create a new CreditLine for a single borrower * @param _borrower The borrower for whom the CreditLine will be created * @param _limit The maximum amount a borrower can drawdown from this CreditLine * @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer. * We assume 8 digits of precision. For example, to submit 15.34%, you would pass up 15340000, * and 5.34% would be 5340000 * @param _paymentPeriodInDays How many days in each payment period. * ie. the frequency with which they need to make payments. * @param _termInDays Number of days in the credit term. It is used to set the `termEndBlock` upon first drawdown. * ie. The credit line should be fully paid off {_termIndays} days after the first drawdown. * @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your * normal rate is 15%, then you will pay 18% while you are late. * * Requirements: * * - the caller must be an underwriter with enough limit (see `setUnderwriterGovernanceLimit`) */ function createCreditLine( address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public override whenNotPaused returns (address) { Underwriter storage underwriter = underwriters[msg.sender]; Borrower storage borrower = borrowers[_borrower]; require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line"); address clAddress = getCreditLineFactory().createCreditLine(""); CreditLine cl = CreditLine(clAddress); cl.initialize( address(this), _borrower, msg.sender, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr ); underwriter.creditLines.push(clAddress); borrower.creditLines.push(clAddress); creditLines[clAddress] = clAddress; emit CreditLineCreated(_borrower, clAddress); cl.grantRole(keccak256("OWNER_ROLE"), config.protocolAdminAddress()); cl.authorizePool(address(config)); return clAddress; } /** * @notice Allows a borrower to drawdown on their creditline. * `amount` USDC is sent to the borrower, and the credit line accounting is updated. * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown * @param creditLineAddress The creditline from which they would like to drawdown * @param addressToSendTo The address where they would like the funds sent. If the zero address is passed, * it will be defaulted to the borrower's address (msg.sender). This is a convenience feature for when they would * like the funds sent to an exchange or alternate wallet, different from the authentication address * * Requirements: * * - the caller must be the borrower on the creditLine */ function drawdown( uint256 amount, address creditLineAddress, address addressToSendTo ) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); Borrower storage borrower = borrowers[msg.sender]; require(borrower.creditLines.length > 0, "No credit lines exist for this borrower"); require(amount > 0, "Must drawdown more than zero"); require(cl.borrower() == msg.sender, "You do not belong to this credit line"); require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); require(withinCreditLimit(amount, cl), "The borrower does not have enough credit limit for this drawdown"); if (addressToSendTo == address(0)) { addressToSendTo = msg.sender; } if (cl.balance() == 0) { cl.setInterestAccruedAsOfBlock(blockNumber()); cl.setLastFullPaymentBlock(blockNumber()); } // Must get the interest and principal accrued prior to adding to the balance. (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, blockNumber()); uint256 balance = cl.balance().add(amount); updateCreditLineAccounting(cl, balance, interestOwed, principalOwed); // Must put this after we update the credit line accounting, so we're using the latest // interestOwed require(!isLate(cl), "Cannot drawdown when payments are past due"); emit DrawdownMade(msg.sender, address(cl), amount); bool success = config.getPool().transferFrom(config.poolAddress(), addressToSendTo, amount); require(success, "Failed to drawdown"); } /** * @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to * the individual CreditLine), but it is not *applied* unless it is after the nextDueBlock, or until we assess * the credit line (ie. payment period end). * Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective * interest rate). If there is still any left over, it will remain in the USDC Balance * of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's. * @param creditLineAddress The credit line to be paid back * @param amount The amount, in USDC atomic units, that a borrower wishes to pay */ function pay(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { require(amount > 0, "Must pay more than zero"); CreditLine cl = CreditLine(creditLineAddress); collectPayment(cl, amount); assessCreditLine(creditLineAddress); } /** * @notice Assesses a particular creditLine. This will apply payments, which will update accounting and * distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone * is allowed to call it. * @param creditLineAddress The creditline that should be assessed. */ function assessCreditLine(address creditLineAddress) public override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); // Do not assess until a full period has elapsed or past due require(cl.balance() > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (blockNumber() < cl.nextDueBlock() && !isLate(cl)) { return; } cl.setNextDueBlock(calculateNextDueBlock(cl)); uint256 blockToAssess = cl.nextDueBlock(); // We always want to assess for the most recently *past* nextDueBlock. // So if the recalculation above sets the nextDueBlock into the future, // then ensure we pass in the one just before this. if (cl.nextDueBlock() > blockNumber()) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); blockToAssess = cl.nextDueBlock().sub(blocksPerPeriod); } applyPayment(cl, getUSDCBalance(address(cl)), blockToAssess); } function migrateCreditLine( CreditLine clToMigrate, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public onlyAdmin { require(clToMigrate.limit() > 0, "Can't migrate empty credit line!"); address newClAddress = createCreditLine(_borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr); CreditLine newCl = CreditLine(newClAddress); // Set accounting state vars. newCl.setBalance(clToMigrate.balance()); newCl.setInterestOwed(clToMigrate.interestOwed()); newCl.setPrincipalOwed(clToMigrate.principalOwed()); newCl.setTermEndBlock(clToMigrate.termEndBlock()); newCl.setNextDueBlock(clToMigrate.nextDueBlock()); newCl.setInterestAccruedAsOfBlock(clToMigrate.interestAccruedAsOfBlock()); newCl.setWritedownAmount(clToMigrate.writedownAmount()); newCl.setLastFullPaymentBlock(clToMigrate.lastFullPaymentBlock()); // Close out the original credit line clToMigrate.setLimit(0); clToMigrate.setBalance(0); bool success = config.getPool().transferFrom( address(clToMigrate), address(newCl), config.getUSDC().balanceOf(address(clToMigrate)) ); require(success, "Failed to transfer funds"); } // Public View Functions (Getters) /** * @notice Simple getter for the creditlines of a given underwriter * @param underwriterAddress The underwriter address you would like to see the credit lines of. */ function getUnderwriterCreditLines(address underwriterAddress) public view whenNotPaused returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } /** * @notice Simple getter for the creditlines of a given borrower * @param borrowerAddress The borrower address you would like to see the credit lines of. */ function getBorrowerCreditLines(address borrowerAddress) public view whenNotPaused returns (address[] memory) { return borrowers[borrowerAddress].creditLines; } /* * Internal Functions */ /** * @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line. * Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be collected */ function collectPayment(CreditLine cl, uint256 amount) internal { require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); require(config.getUSDC().balanceOf(msg.sender) >= amount, "You have insufficent balance for this payment"); emit PaymentCollected(msg.sender, address(cl), amount); bool success = config.getPool().transferFrom(msg.sender, address(cl), amount); require(success, "Failed to collect payment"); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be applied * @param blockNumber The blockNumber on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function applyPayment( CreditLine cl, uint256 amount, uint256 blockNumber ) internal { (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment(cl, amount, blockNumber); updateWritedownAmounts(cl); if (interestPayment > 0) { emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); config.getPool().collectInterestRepayment(address(cl), interestPayment); } if (principalPayment > 0) { emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); config.getPool().collectPrincipalRepayment(address(cl), principalPayment); } } function handlePayment( CreditLine cl, uint256 paymentAmount, uint256 asOfBlock ) internal returns ( uint256, uint256, uint256 ) { (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, asOfBlock); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(paymentAmount, cl.balance(), interestOwed, principalOwed); uint256 newBalance = cl.balance().sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = cl.balance().sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( cl, newBalance, interestOwed.sub(pa.interestPayment), principalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function updateWritedownAmounts(CreditLine cl) internal { (uint256 writedownPercent, uint256 writedownAmount) = Accountant.calculateWritedownFor( cl, blockNumber(), config.getLatenessGracePeriodInDays(), config.getLatenessMaxDays() ); if (writedownPercent == 0 && cl.writedownAmount() == 0) { return; } int256 writedownDelta = int256(cl.writedownAmount()) - int256(writedownAmount); cl.setWritedownAmount(writedownAmount); if (writedownDelta > 0) { // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns. totalWritedowns = totalWritedowns.sub(uint256(writedownDelta)); } else { totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1)); } config.getPool().distributeLosses(address(cl), writedownDelta); } function isLate(CreditLine cl) internal view returns (bool) { uint256 blocksElapsedSinceFullPayment = blockNumber().sub(cl.lastFullPaymentBlock()); return blocksElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); } function getCreditLineFactory() internal view returns (CreditLineFactory) { return CreditLineFactory(config.getAddress(uint256(ConfigOptions.Addresses.CreditLineFactory))); } function subtractClFromTotalLoansOutstanding(CreditLine cl) internal { totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance()); } function addCLToTotalLoansOutstanding(CreditLine cl) internal { totalLoansOutstanding = totalLoansOutstanding.add(cl.balance()); } function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 blockNumber) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(cl, blockNumber, config.getLatenessGracePeriodInDays()); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOfBLock to the block that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. cl.setInterestAccruedAsOfBlock(blockNumber); } return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued)); } function withinCreditLimit(uint256 amount, CreditLine cl) internal view returns (bool) { return cl.balance().add(amount) <= cl.limit(); } function withinTransactionLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit)); } function calculateNewTermEndBlock(CreditLine cl) internal view returns (uint256) { // If there's no balance, there's no loan, so there's no term end block if (cl.balance() == 0) { return 0; } // Don't allow any weird bugs where we add to your current end block. This // function should only be used on new credit lines, when we are setting them up if (cl.termEndBlock() != 0) { return cl.termEndBlock(); } return blockNumber().add(BLOCKS_PER_DAY.mul(cl.termInDays())); } function calculateNextDueBlock(CreditLine cl) internal view returns (uint256) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); uint256 balance = cl.balance(); // Your paid off, or have not taken out a loan yet, so no next due block. if (balance == 0 && cl.nextDueBlock() != 0) { return 0; } // You must have just done your first drawdown if (cl.nextDueBlock() == 0 && balance > 0) { return blockNumber().add(blocksPerPeriod); } // Active loan that has entered a new period, so return the *next* nextDueBlock. // But never return something after the termEndBlock if (balance > 0 && blockNumber() >= cl.nextDueBlock()) { uint256 blocksToAdvance = (blockNumber().sub(cl.nextDueBlock()).div(blocksPerPeriod)).add(1).mul(blocksPerPeriod); uint256 nextDueBlock = cl.nextDueBlock().add(blocksToAdvance); return Math.min(nextDueBlock, cl.termEndBlock()); } // Active loan in current period, where we've already set the nextDueBlock correctly, so should not change. if (balance > 0 && blockNumber() < cl.nextDueBlock()) { return cl.nextDueBlock(); } revert("Error: could not calculate next due block."); } function blockNumber() internal view virtual returns (uint256) { return block.number; } function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter) internal view returns (bool) { require(underwriter.governanceLimit != 0, "underwriter does not have governance limit"); uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter); uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount); return totalToBeExtended <= underwriter.governanceLimit; } function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit)); } function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) { uint256 creditExtended; uint256 length = underwriter.creditLines.length; for (uint256 i = 0; i < length; i++) { CreditLine cl = CreditLine(underwriter.creditLines[i]); creditExtended = creditExtended.add(cl.limit()); } return creditExtended; } function updateCreditLineAccounting( CreditLine cl, uint256 balance, uint256 interestOwed, uint256 principalOwed ) internal nonReentrant { subtractClFromTotalLoansOutstanding(cl); cl.setBalance(balance); cl.setInterestOwed(interestOwed); cl.setPrincipalOwed(principalOwed); // This resets lastFullPaymentBlock. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueBlock. (ie. creditline isn't pre-drawdown) if (cl.interestOwed() == 0 && cl.nextDueBlock() != 0) { // If interest was fully paid off, then set the last full payment as the previous due block uint256 mostRecentLastDueBlock; if (blockNumber() < cl.nextDueBlock()) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); mostRecentLastDueBlock = cl.nextDueBlock().sub(blocksPerPeriod); } else { mostRecentLastDueBlock = cl.nextDueBlock(); } cl.setLastFullPaymentBlock(mostRecentLastDueBlock); } addCLToTotalLoansOutstanding(cl); cl.setTermEndBlock(calculateNewTermEndBlock(cl)); cl.setNextDueBlock(calculateNextDueBlock(cl)); } function getUSDCBalance(address _address) internal returns (uint256) { return config.getUSDC().balanceOf(_address); } modifier onlyValidCreditLine(address clAddress) { require(creditLines[clAddress] != address(0), "Unknown credit line"); _; } }
If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
function updateWritedownAmounts(CreditLine cl) internal { (uint256 writedownPercent, uint256 writedownAmount) = Accountant.calculateWritedownFor( cl, blockNumber(), config.getLatenessGracePeriodInDays(), config.getLatenessMaxDays() ); if (writedownPercent == 0 && cl.writedownAmount() == 0) { return; } int256 writedownDelta = int256(cl.writedownAmount()) - int256(writedownAmount); cl.setWritedownAmount(writedownAmount); if (writedownDelta > 0) { totalWritedowns = totalWritedowns.sub(uint256(writedownDelta)); totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1)); } config.getPool().distributeLosses(address(cl), writedownDelta); }
969,489
./full_match/137/0x51F8A7175D0678E465A10D8b26A92d6fa940E0d7/sources/contracts/Finns.sol
Mintable/ERC2981 royalty handler
function royaltyInfo(uint256 /*_tokenId*/, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { return (owner(), (_salePrice * royaltyBPS)/10000); }
4,687,975
pragma solidity 0.4.25; // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ; bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager"; bytes32 internal constant _ISGRToken_ = "ISGRToken" ; bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ; bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ; bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ; bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: contracts/saga-genesis/interfaces/ISogurExchanger.sol /** * @title Sogur Exchanger Interface. */ interface ISogurExchanger { /** * @dev Transfer SGR to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function transferSgrToSgnHolder(address _to, uint256 _value) external; } // File: contracts/saga-genesis/interfaces/ISagaExchanger.sol /** * @title Saga Exchanger Interface. * @dev Old exchanger adapting by SagaExchangerSogurAdapter to the new ISogurExchanger. */ interface ISagaExchanger { /** * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function transferSgaToSgnHolder(address _to, uint256 _value) external; } // File: contracts/saga-genesis/SagaExchangerSogurAdapter.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title Saga Exchanger Sogur Adapter. * @dev Adapt old saga exchanger interface to the new sogur exchanger interface. */ contract SagaExchangerSogurAdapter is ContractAddressLocatorHolder, ISagaExchanger { string public constant VERSION = "1.0.0"; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements ISogurExchanger interface. */ function getSogurExchanger() public view returns (ISogurExchanger) { return ISogurExchanger(getContractAddress(_ISogurExchanger_)); } /** * @dev Transfer SGR to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function transferSgaToSgnHolder(address _to, uint256 _value) external only(_ISGNToken_) { getSogurExchanger().transferSgrToSgnHolder(_to, _value); } }
Transfer SGR to an SGN holder. _to The address of the SGN holder. _value The amount of SGR to transfer./
function transferSgaToSgnHolder(address _to, uint256 _value) external only(_ISGNToken_) { getSogurExchanger().transferSgrToSgnHolder(_to, _value); }
14,897,502
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ 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 uint256 ~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); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ 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 uint256 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)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed 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 an int256 ~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 SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed 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 an int256 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 Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } 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; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(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. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual 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. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // 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; uint256 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; uint256 time; int256 price; int256 salt; } /** * @notice Commit a 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. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @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. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. 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. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { 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. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // 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 CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; 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 RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a 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. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @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. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. 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. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // 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; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => 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. uint256 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`. uint256 index; bytes ancillaryData; } 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; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public 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[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public 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 public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface 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 public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @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. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a 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. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // 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); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; 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 (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else 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 eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 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), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 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 have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @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. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. 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. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 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 snapshotted 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(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 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; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual 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. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => 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`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 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; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { 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 exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; 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 { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); 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 (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 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(uint256 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(uint256 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(uint256 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. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 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); } revert("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, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 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, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 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( uint256 roleId, uint256 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 an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` 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( uint256 roleId, uint256 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" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, 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 } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol 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; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ 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 virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } 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"); // 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. 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]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This 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 { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract 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(uint256 value) external virtual; /** * @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, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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; } } 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.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; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ 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; } } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions 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(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 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 a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // 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 bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // 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() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @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() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev 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()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/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, _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 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 `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()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } 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( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } 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: 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.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: 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); } } 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); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
The maximum of `a` and `b`. a a FixedPoint. b a FixedPoint. return the maximum of `a` and `b`./
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; }
98,865
./full_match/5/0x6C7e4fDaf188d3C4fBB1093F7364f5D96882127a/sources/github/safemoonprotocol/Safemoon.sol/Safemoon.sol
Allows Withdrawal of any remaining ETH/BNB for owner when the extra isn't added to LP
function withdraw() public onlyOwner { msg.sender.transfer(address(this).balance); }
1,860,416
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import { BaseStrategy, StrategyParams } from "@yearnvaults/contracts/BaseStrategy.sol"; import "../interfaces/frax/IFrax.sol"; import "../interfaces/uniswap/IUniNFT.sol"; import "../interfaces/uniswap/IUni.sol"; import "../interfaces/uniswap/IUniV3.sol"; import "../interfaces/curve/ICurve.sol"; import "../libraries/UnsafeMath.sol"; import "../libraries/FixedPoint96.sol"; import "../libraries/FullMath.sol"; import "../libraries/LowGasSafeMath.sol"; import "../libraries/SafeCast.sol"; import "../libraries/SqrtPriceMath.sol"; import "../libraries/TickMath.sol"; import "../libraries/LiquidityAmounts.sol"; interface IName { function name() external view returns (string memory); } interface IBaseFee { function isCurrentBaseFeeAcceptable() external view returns (bool); } contract StrategyFraxUniswapUSDC is BaseStrategy { using Address for address; using SafeMath for uint128; /* ========== STATE VARIABLES ========== */ // variables for determining how much governance token to hold for voting rights uint256 internal constant DENOMINATOR = 10000; uint256 public keepFXS; uint256 public fraxTimelockSet; address public refer; address public voter; uint256 public nftUnlockTime; // timestamp that we can withdraw our staked NFT. init at max so we must mint first. // these are variables specific to our want-FRAX pair uint256 public nftId; address internal constant fraxLock = 0x3EF26504dbc8Dd7B7aa3E97Bc9f3813a9FC0B4B0; address internal constant uniV3Pool = 0xc63B0708E2F7e69CB8A1df0e1389A98C35A76D52; // tokens IERC20 internal constant frax = IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e); IERC20 internal constant fxs = IERC20(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); // uniswap v3 NFT address address internal constant uniNFT = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88; // routers/pools for swaps address internal constant unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; ICurveFi internal constant curve = ICurveFi(0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B); // setters bool public reLockProfits; // true if we choose to re-lock profits following each harvest and automatically start another epoch bool public checkTrueHoldings; // bool to reset our profit/loss based on the amount we have if we withdrew everything at once uint256 public slippageMax; // in bips, how much slippage we allow between our optimistic assets and pessimistic. 50 = 0.5% slippage. Remember curve swap costs 0.04%. bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us // check for cloning bool internal isOriginal = true; /* ========== CONSTRUCTOR ========== */ constructor(address _vault) public BaseStrategy(_vault) { _initializeStrat(); } /* ========== CLONING ========== */ event Cloned(address indexed clone); // initializetime function _initializeStrat() internal { require(nftId == 0); refer = 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7; voter = 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7; fraxTimelockSet = 86400; nftId = 1; reLockProfits = true; slippageMax = 50; nftUnlockTime = type(uint256).max; want.approve(address(curve), type(uint256).max); frax.approve(address(curve), type(uint256).max); want.approve(uniNFT, type(uint256).max); frax.approve(uniNFT, type(uint256).max); fxs.approve(unirouter, type(uint256).max); } function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(); } function cloneFraxUni( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { require(isOriginal); // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } StrategyFraxUniswapUSDC(newStrategy).initialize( _vault, _strategist, _rewards, _keeper ); emit Cloned(newStrategy); } /* ========== VIEWS ========== */ function name() external view override returns (string memory) { return "StrategyFraxUniswapUSDC"; } // returns balance of want token function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } // returns balance of frax token function balanceOfFrax() public view returns (uint256) { return frax.balanceOf(address(this)); } /// @notice Returns additional USDC we get if we swap our FRAX on Curve function valueOfFrax() public view returns (uint256) { // see how much USDC we would get for our FRAX on curve uint256 currentFrax = balanceOfFrax(); if (currentFrax > 0) { return curve.get_dy_underlying(0, 2, currentFrax); } else { return 0; } } // returns balance of our UniV3 LP, assuming 1 FRAX = 1 want, factoring curve swap fee function balanceOfNFToptimistic() public view returns (uint256) { (uint256 fraxBalance, uint256 usdcBalance) = principal(); uint256 fraxRebase = fraxBalance.div(1e12).mul(9996).div(DENOMINATOR); // div by 1e12 to convert frax to usdc, assume 1:1 swap on curve with fees return fraxRebase.add(usdcBalance); } /// @notice Returns balance of our UniV3 LP, swapping all FRAX to want using Curve. function balanceOfNFTpessimistic() public view returns (uint256) { (uint256 fraxBalance, uint256 usdcBalance) = principal(); // only bother adding/converting if we have anything, otherwise just return usdcBalance if (fraxBalance > 0) { uint256 usdcCurveOut = curve.get_dy_underlying(0, 2, fraxBalance); return usdcCurveOut.add(usdcBalance); } else { return usdcBalance; } } // assume pessimistic value; used directly in emergencyExit function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(valueOfFrax()).add(balanceOfNFTpessimistic()); } /* ========== MUTATIVE FUNCTIONS ========== */ // claim profit and swap for want function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // in normal situations we can simply use our loose tokens as profit // do this so we don't count dust leftover from LPing as profit uint256 beforeStableBalance = balanceOfWant().add(valueOfFrax()); // claim our rewards. this will give us FXS (emissions), FRAX, and USDC (fees) // however, only claim if we have an NFT staked if (IFrax(fraxLock).lockedLiquidityOf(address(this)) > 0) { IFrax(fraxLock).getReward(); } // send some FXS to our voter for boosted emissions uint256 fxsBalance = fxs.balanceOf(address(this)); if (fxsBalance > 0) { uint256 tokensToSend = fxsBalance.mul(keepFXS).div(DENOMINATOR); if (tokensToSend > 0) { fxs.transfer(voter, tokensToSend); } uint256 tokensRemain = fxs.balanceOf(address(this)); if (tokensRemain > 0) { _swapFXS(tokensRemain); } } // convert all of our FRAX profits to USDC for ease of accounting uint256 fraxToSwap = balanceOfFrax(); if (fraxToSwap > 0) { _curveSwapToWant(fraxToSwap); } // check how much we have after claiming our rewards uint256 wantBal = balanceOfWant(); // slightly pessimistic profits since we convert our FRAX to USDC before counting it uint256 afterStableBalance = valueOfFrax().add(wantBal); _profit = afterStableBalance.sub(beforeStableBalance); _debtPayment = _debtOutstanding; // use this to check our profit/loss if we suspect the pool is imbalanced in one way or the other, or if we get donations if (checkTrueHoldings) { uint256 assets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; // if assets are greater than debt, things are working great! if (assets > debt) { _profit = assets.sub(debt); } // Losses should never happen unless FRAX depegs, but if it does, let's record it accurately. else { _loss = debt.sub(assets); _profit = 0; } // reset since we've adjusted for our true holdings checkTrueHoldings = false; } else { // check our peg to make sure everything is okay checkFraxPeg(); } // we need to free up all of our profit as USDC uint256 toFree = _debtPayment.add(_profit); if (toFree > wantBal) { toFree = toFree.sub(wantBal); _withdrawSome(toFree); // check what we got back out wantBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, wantBal); // make sure we pay our debt first, then count profit. if not enough to pay debt, then only loss. if (wantBal > _debtPayment) { _profit = wantBal.sub(_debtPayment); } else { _profit = 0; _loss = _debtOutstanding.sub(_debtPayment); } } // we're done harvesting, so reset our trigger if we used it forceHarvestTriggerOnce = false; } // Swap FXS -> FRAX on UniV2 function _swapFXS(uint256 _amountIn) internal { address[] memory path = new address[](2); path[0] = address(fxs); path[1] = address(frax); IUni(unirouter).swapExactTokensForTokens( _amountIn, 0, path, address(this), block.timestamp ); } function _curveSwapToFrax(uint256 _amountIn) internal { // use our slippage tolerance, convert between USDC (1e6) -> FRAX (1e18) uint256 _amountOut = _amountIn.mul(DENOMINATOR.sub(slippageMax)).div(DENOMINATOR).mul( 1e12 ); // USDC is 2, DAI is 1, Tether is 3, frax is 0 curve.exchange_underlying(2, 0, _amountIn, _amountOut); } function _curveSwapToWant(uint256 _amountIn) internal { // use our slippage tolerance, convert between FRAX (1e18) -> USDC (1e6) uint256 _amountOut = _amountIn.mul(DENOMINATOR.sub(slippageMax)).div(DENOMINATOR).div( 1e12 ); // USDC is 2, DAI is 1, Tether is 3, frax is 0 curve.exchange_underlying(0, 2, _amountIn, _amountOut); } // Deposit value to NFT & stake NFT function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit || nftId == 1) { return; } // NFT has to be unlocked before we can do anything with it require(block.timestamp > nftUnlockTime, "Wait for NFT to unlock!"); // unstake our NFT so we can withdraw or deposit more as needed _nftUnstake(); // only re-lock our profits if our bool is true if (reLockProfits) { // Invest the rest of the want uint256 wantBal = balanceOfWant(); if (wantBal > 0) { // need to swap half want to frax, but use the proper conversion // based on the current exchange rate in the LP (uint256 fraxBal, uint256 usdcBal) = principal(); uint256 fraxPercentage = 5e17; // default our percentage to 50%, 100% is 1e18 if (usdcBal > 0 || fraxBal > 0) { fraxPercentage = fraxBal.mul(1e18).div( (usdcBal.mul(1e12)).add(fraxBal) ); // multiply usdc by 1e12 to convert to frax, 1e18 } uint256 fraxNeeded = wantBal.mul(fraxPercentage).div(1e18); // this will be 1e6, which matches our valueOfFrax // we should only have USDC holdings after our harvest // doing this will leave us with a little USDC leftover each time if (fraxNeeded > 0) { _curveSwapToFrax(fraxNeeded); } // add more liquidity to our NFT IUniNFT.increaseStruct memory setIncrease = IUniNFT.increaseStruct( nftId, balanceOfFrax(), balanceOfWant(), 0, 0, block.timestamp ); IUniNFT(uniNFT).increaseLiquidity(setIncrease); } // re-lock our NFT _nftStake(); } } // this is only called externally by user withdrawals function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // check if we have enough free funds to cover the withdrawal uint256 wantBal = balanceOfWant(); if (wantBal < _amountNeeded) { // make sure our pool is healthy enough for a normal withdrawal checkFraxPeg(); // We need to withdraw to get back more want uint256 toFree = _amountNeeded.sub(wantBal); _withdrawSome(toFree); // reload balance of want after withdrawing funds wantBal = balanceOfWant(); } // check again if we have enough balance available to cover the liquidation if (wantBal >= _amountNeeded) { _liquidatedAmount = _amountNeeded; } else { // we took a loss :( _liquidatedAmount = wantBal; _loss = _amountNeeded.sub(wantBal); } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { // amount here doesn't really matter, since in withdrawSome we always withdraw everything // if emergencyExit is true, so just use more than we would have loose in the strategy (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } // before we go crazy withdrawing or harvesting, make sure our FRAX peg is healthy function checkFraxPeg() internal { uint256 virtualBalance = balanceOfNFToptimistic(); uint256 realBalance = balanceOfNFTpessimistic(); // don't bother checking if either of our vars are 0 since we will revert if (realBalance == 0 || virtualBalance == 0) { return; } if (virtualBalance > realBalance) { require( (slippageMax > (virtualBalance.sub(realBalance)).mul(DENOMINATOR).div( realBalance )), "too much FRAX" ); } else { require( (slippageMax > (realBalance.sub(virtualBalance)).mul(DENOMINATOR).div( virtualBalance )), "too much USDC" ); } } // withdraw some want from the vaults, probably don't want to allow users to initiate this function _withdrawSome(uint256 _amount) internal { if (nftId == 1) { return; } // NFT has to be unlocked before we can do anything with it require(block.timestamp > nftUnlockTime, "Wait for NFT to unlock!"); // if we don't have enough free funds, unstake our NFT _nftUnstake(); // use our "ideal" amount for this so we under-estimate and assess losses on each debt reduction // calculate the share of the NFT that our amount needed should be uint256 debt = vault.strategies(address(this)).totalDebt; uint256 optimisticBal = Math.max(balanceOfNFToptimistic(), debt); uint256 fraction; if (optimisticBal > 0) { // don't want to divide by 0 fraction = (_amount).mul(1e18).div(optimisticBal); // multiply by 1e18 for precision reasons } else { return; } (, , , , , , , uint128 liquidity, , , , ) = IUniNFT(uniNFT).positions(nftId); // convert between uint128 and uint256, fun! uint256 _liquidity = uint256(liquidity); uint256 liquidityToRemove = _liquidity.mul(fraction).div(1e18); // divide by 1e18 since that's how big our fraction is // remove it all if we're in emergency exit if (fraction >= 1e18 || emergencyExit) { liquidityToRemove = _liquidity; } // convert between uint128 and uint256, fun! uint128 _liquidityToRemove = uint128(liquidityToRemove); // remove our specified liquidity amount IUniNFT.decreaseStruct memory setDecrease = IUniNFT.decreaseStruct( nftId, _liquidityToRemove, 0, 0, block.timestamp ); IUniNFT(uniNFT).decreaseLiquidity(setDecrease); IUniNFT.collectStruct memory collectParams = IUniNFT.collectStruct( nftId, address(this), type(uint128).max, type(uint128).max ); IUniNFT(uniNFT).collect(collectParams); // swap any FRAX we have to USDC uint256 currentFrax = balanceOfFrax(); if (currentFrax > 0) { _curveSwapToWant(currentFrax); } } // transfers all tokens to new strategy function prepareMigration(address _newStrategy) internal override { frax.transfer(_newStrategy, balanceOfFrax()); fxs.transfer(_newStrategy, fxs.balanceOf(address(this))); // NFT has to be unlocked before we can do anything with it require(block.timestamp > nftUnlockTime, "Wait for NFT to unlock!"); // unstake and send our NFT to our new strategy, don't try migrating if we don't have an NFT if (nftId != 1) { _nftUnstake(); IERC721(uniNFT).transferFrom(address(this), _newStrategy, nftId); // approvals automatically revoke when we migrate. and set our NFTid back to 1 _setGovParams(address(0), address(0), 0, 1, 0, 0); } } /* ========== SETTERS ========== */ // sets the id of the minted NFT. Unknowable until mintNFT is called function _setGovParams( address _refer, address _voter, uint256 _keepFXS, uint256 _nftId, uint256 _timelockInSeconds, uint256 _currentUnlockTime ) internal { refer = _refer; voter = _voter; keepFXS = _keepFXS; nftId = _nftId; fraxTimelockSet = _timelockInSeconds; nftUnlockTime = _currentUnlockTime; } function setGovParams( address _refer, address _voter, uint256 _keepFXS, uint256 _nftId, uint256 _timelockInSeconds, uint256 _currentUnlockTime ) external onlyGovernance { _setGovParams( _refer, _voter, _keepFXS, _nftId, _timelockInSeconds, _currentUnlockTime ); } ///@notice This allows us to decide to automatically re-lock our NFT with profits after a harvest function setManagerParams( bool _reLockProfits, bool _checkTrueHoldings, uint256 _slippageMax ) external onlyVaultManagers { require(_slippageMax < 10001, "10000 = 100% slippage"); reLockProfits = _reLockProfits; checkTrueHoldings = _checkTrueHoldings; slippageMax = _slippageMax; } ///@notice This allows us to manually harvest with our keeper as needed function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce) external onlyAuthorized { forceHarvestTriggerOnce = _forceHarvestTriggerOnce; } /* ========== NFT HELPERS ========== */ // This function is needed to initialize the entire strategy. // want needs to be airdropped to the strategy in a nominal amount. Say ~1k USD worth. // This will run through the process of minting the NFT on UniV3 // that NFT will be the NFT we use for this strat. We will add/sub balances, but never burn the NFT // it will always have dust, accordingly function mintNFT() external onlyVaultManagers { require( (balanceOfWant() > 0 && IUniNFT(uniNFT).balanceOf(address(this)) == 0), "can't mint" ); // swap < half to frax, don't care about using real pricing since it's a small amount // and is only meant to seed the LP. prefer extra want left over for accounting reasons. uint256 swapAmt = balanceOfWant().mul(40).div(100); _curveSwapToFrax(swapAmt); IUniNFT.nftStruct memory setNFT = IUniNFT.nftStruct( address(frax), address(want), 500, (-276380), (-276270), balanceOfFrax(), balanceOfWant(), 0, 0, address(this), block.timestamp ); //time to mint the NFT (uint256 tokenOut, , , ) = IUniNFT(uniNFT).mint(setNFT); nftId = tokenOut; // reset our unlock time, we have our NFT but it's not locked nftUnlockTime = 0; } /// turning PositionValue.sol into an internal function // positionManager is uniNFT, nftId, sqrt function principal() public view returns ( //contraqct uniNFT, //nftId, // uint160 sqrtRatioX96 uint256 fraxHoldings, uint256 usdcHoldings ) { if (nftId == 1) { // this is our "placeholder" ID, means we need to mint our NFT still return (0, 0); } else { // check where our NFT is, hopefully staked or in our strategy 😬 address nftOwner = IUniNFT(uniNFT).ownerOf(nftId); if (nftOwner == address(this) || nftOwner == fraxLock) { ( , , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = IUniNFT(uniNFT).positions(nftId); (uint160 sqrtRatioX96, , , , , , ) = IUniV3(uniV3Pool).slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } else { // we don't have our NFT, that's not good return (0, 0); } } } /// @notice This is here so our contract can receive ERC721 tokens. function onERC721Received( address, address, uint256, bytes calldata ) public pure virtual returns (bytes4) { return this.onERC721Received.selector; } function _nftUnstake() internal { address nftOwner = IUniNFT(uniNFT).ownerOf(nftId); if (nftOwner == fraxLock) { IFrax(fraxLock).withdrawLocked(nftId); } } function nftUnstake() external onlyVaultManagers { _nftUnstake(); } function _nftStake() internal { IERC721(uniNFT).approve(fraxLock, nftId); IFrax(fraxLock).stakeLocked(nftId, fraxTimelockSet); // update our new unlock time nftUnlockTime = block.timestamp.add(fraxTimelockSet); } function nftStake() external onlyVaultManagers { _nftStake(); } /// @notice Include this so gov can sweep our NFT if needed. function sweepNFT(address _destination) external onlyGovernance { IERC721(uniNFT).safeTransferFrom(address(this), _destination, nftId); } /* ========== KEEP3RS ========== */ // use this to determine when to harvest function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { // Should not trigger if strategy is not active (no assets and no debtRatio). This means we don't need to adjust keeper job. if (!isActive()) { return false; } if (!isBaseFeeAcceptable()) { return false; } // harvest if our NFT can be unlocked if (block.timestamp > nftUnlockTime) { return true; } // trigger if we want to manually harvest if (forceHarvestTriggerOnce) { return true; } // otherwise, we don't harvest return false; } // check if the current baseFee is below our external target function isBaseFeeAcceptable() internal view returns (bool) { return IBaseFee(0xb5e1CAcB567d98faaDB60a1fD4820720141f064F) .isCurrentBaseFeeAcceptable(); } /* ========== FUNCTION GRAVEYARD ========== */ function ethToWant(uint256 _amtInWei) public view override returns (uint256) {} function protectedTokens() internal view override returns (address[] memory) {} }
This function is needed to initialize the entire strategy. want needs to be airdropped to the strategy in a nominal amount. Say ~1k USD worth. This will run through the process of minting the NFT on UniV3 that NFT will be the NFT we use for this strat. We will add/sub balances, but never burn the NFT it will always have dust, accordingly swap < half to frax, don't care about using real pricing since it's a small amount and is only meant to seed the LP. prefer extra want left over for accounting reasons.time to mint the NFT reset our unlock time, we have our NFT but it's not locked
function mintNFT() external onlyVaultManagers { require( (balanceOfWant() > 0 && IUniNFT(uniNFT).balanceOf(address(this)) == 0), "can't mint" ); uint256 swapAmt = balanceOfWant().mul(40).div(100); _curveSwapToFrax(swapAmt); IUniNFT.nftStruct memory setNFT = IUniNFT.nftStruct( address(frax), address(want), 500, (-276380), (-276270), balanceOfFrax(), balanceOfWant(), 0, 0, address(this), block.timestamp ); (uint256 tokenOut, , , ) = IUniNFT(uniNFT).mint(setNFT); nftId = tokenOut; nftUnlockTime = 0; }
12,567,359
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IStaking { event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); function stake(uint256 amount) external; function stakeFor(address user, uint256 amount) external; function unstake(uint256 amount) external; function totalStakedFor(address addr) external view returns (uint256); function totalStaked() external view returns (uint256); function token() external view returns (address); } contract TokenPool is Ownable { IERC20 public token; constructor(IERC20 _token) public { token = _token; } function balance() public view returns (uint256) { return token.balanceOf(address(this)); } function transfer(address to, uint256 value) external onlyOwner returns (bool) { return token.transfer(to, value); } function rescueFunds(address tokenToRescue, address to, uint256 amount) external onlyOwner returns (bool) { require(address(token) != tokenToRescue, 'TokenPool: Cannot claim token held by the contract'); return IERC20(tokenToRescue).transfer(to, amount); } } contract MYSTStaker is IStaking, Ownable { using SafeMath for uint256; event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); event TokensClaimed(address indexed user, uint256 amount); event TokensLocked(uint256 amount, uint256 durationSec, uint256 total); // amount: Unlocked tokens, total: Total locked tokens event TokensUnlocked(uint256 amount, uint256 total); TokenPool private _stakingPool; TokenPool private _unlockedPool; TokenPool private _lockedPool; // // Time-bonus params // uint256 public constant BONUS_DECIMALS = 2; uint256 public startBonus = 0; uint256 public bonusPeriodSec = 0; // // Global accounting state // uint256 public totalLockedShares = 0; uint256 public totalStakingShares = 0; uint256 public _totalStakingShareSeconds = 0; uint256 public _lastAccountingTimestampSec = now; uint256 public _maxUnlockSchedules = 0; uint256 public _initialSharesPerToken = 0; bool public _stakeEnable = false; uint256 public _lockTerm = 0 days; // // User accounting state // // Represents a single stake for a user. A user may have multiple. struct Stake { uint256 stakingShares; uint256 timestampSec; } // Caches aggregated values from the User->Stake[] map to save computation. // If lastAccountingTimestampSec is 0, there's no entry for that user. struct UserTotals { uint256 stakingShares; uint256 stakingShareSeconds; uint256 lastAccountingTimestampSec; } // Aggregated staking values per user mapping(address => UserTotals) public _userTotals; // The collection of stakes for each user. Ordered by timestamp, earliest to latest. mapping(address => Stake[]) public _userStakes; // // Locked/Unlocked Accounting state // struct UnlockSchedule { uint256 initialLockedShares; uint256 unlockedShares; uint256 lastUnlockTimestampSec; uint256 endAtSec; uint256 durationSec; } UnlockSchedule[] public unlockSchedules; /** * @param stakingToken The token users deposit as stake. * @param distributionToken The token users receive as they unstake. * @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit. * @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point. * e.g. 25% means user gets 25% of max distribution tokens. * @param bonusPeriodSec_ Length of time for bonus to increase linearly to max. * @param initialSharesPerToken Number of shares to mint per staking token on first stake. */ constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules, uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public { // The start bonus must be some fraction of the max. (i.e. <= 100%) require(startBonus_ <= 10**BONUS_DECIMALS, 'MYSTStaker: start bonus too high'); // If no period is desired, instead set startBonus = 100% // and bonusPeriod to a small value like 1sec. require(bonusPeriodSec_ != 0, 'MYSTStaker: bonus period is zero'); require(initialSharesPerToken > 0, 'MYSTStaker: initialSharesPerToken is zero'); _stakingPool = new TokenPool(stakingToken); _unlockedPool = new TokenPool(distributionToken); _lockedPool = new TokenPool(distributionToken); startBonus = startBonus_; bonusPeriodSec = bonusPeriodSec_; _maxUnlockSchedules = maxUnlockSchedules; _initialSharesPerToken = initialSharesPerToken; } /** * @return The token users deposit as stake. */ function getStakingToken() public view returns (IERC20) { return _stakingPool.token(); } /** * @return The token users receive as they unstake. */ function getDistributionToken() public view returns (IERC20) { assert(_unlockedPool.token() == _lockedPool.token()); return _unlockedPool.token(); } /** * @dev Transfers amount of deposit tokens from the user. * @param amount Number of deposit tokens to stake. */ function stake(uint256 amount) external override { _stakeFor(msg.sender, msg.sender, amount); } /** * @dev Transfers amount of deposit tokens from the caller on behalf of user. * @param user User address who gains credit for this stake operation. * @param amount Number of deposit tokens to stake. */ function stakeFor(address user, uint256 amount) external override onlyOwner { _stakeFor(msg.sender, user, amount); } /** * @dev Private implementation of staking methods. * @param staker User address who deposits tokens to stake. * @param beneficiary User address who gains credit for this stake operation. * @param amount Number of deposit tokens to stake. */ function _stakeFor(address staker, address beneficiary, uint256 amount) private { require(amount > 0, 'MYSTStaker: stake amount is zero'); require(_stakeEnable, 'Stake not enabled yet'); require(beneficiary != address(0), 'MYSTStaker: beneficiary is zero address'); require(totalStakingShares == 0 || totalStaked() > 0, 'MYSTStaker: Invalid state. Staking shares exist, but no staking tokens do'); uint256 mintedStakingShares = (totalStakingShares > 0) ? totalStakingShares.mul(amount).div(totalStaked()) : amount.mul(_initialSharesPerToken); require(mintedStakingShares > 0, 'MYSTStaker: Stake amount is too small'); updateAccounting(); // 1. User Accounting UserTotals storage totals = _userTotals[beneficiary]; totals.stakingShares = totals.stakingShares.add(mintedStakingShares); totals.lastAccountingTimestampSec = now; Stake memory newStake = Stake(mintedStakingShares, now); _userStakes[beneficiary].push(newStake); // 2. Global Accounting totalStakingShares = totalStakingShares.add(mintedStakingShares); // Already set in updateAccounting() // _lastAccountingTimestampSec = now; // interactions require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount), 'MYSTStaker: transfer into staking pool failed'); emit Staked(beneficiary, amount, totalStakedFor(beneficiary), ""); } /** * @dev Unstakes a certain amount of previously deposited tokens. User also receives their * alotted number of distribution tokens. * @param amount Number of deposit tokens to unstake / withdraw. */ function unstake(uint256 amount) external override { _unstake(amount); } /** * @param amount Number of deposit tokens to unstake / withdraw. * @return The total number of distribution tokens that would be rewarded. */ function unstakeQuery(uint256 amount) public returns (uint256) { return _unstake(amount); } /** * @dev Unstakes a certain amount of previously deposited tokens. User also receives their * alotted number of distribution tokens. * @param amount Number of deposit tokens to unstake / withdraw. * @return The total number of distribution tokens rewarded. */ function _unstake(uint256 amount) private returns (uint256) { updateAccounting(); // checks require(amount > 0, 'MYSTStaker: unstake amount is zero'); require(totalStakedFor(msg.sender) >= amount, 'MYSTStaker: unstake amount is greater than total user stakes'); uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked()); require(stakingSharesToBurn > 0, 'MYSTStaker: Unable to unstake amount this small'); // 1. User Accounting UserTotals storage totals = _userTotals[msg.sender]; Stake[] storage accountStakes = _userStakes[msg.sender]; require(block.timestamp.sub(accountStakes[accountStakes.length - 1].timestampSec) >= _lockTerm, 'You need to wait more to unstake.'); // Redeem from most recent stake and go backwards in time. uint256 stakingShareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 rewardAmount = 0; while (sharesLeftToBurn > 0) { Stake storage lastStake = accountStakes[accountStakes.length - 1]; uint256 stakeTimeSec = now.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; if (lastStake.stakingShares <= sharesLeftToBurn) { // fully redeem a past stake newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec); rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec); stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn); sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares); accountStakes.pop(); } else { // partially redeem a past stake newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec); rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, 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); // Already set in updateAccounting // totals.lastAccountingTimestampSec = now; // 2. Global Accounting _totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn); totalStakingShares = totalStakingShares.sub(stakingSharesToBurn); // Already set in updateAccounting // _lastAccountingTimestampSec = now; // interactions require(_stakingPool.transfer(msg.sender, amount), 'MYSTStaker: transfer out of staking pool failed'); require(_unlockedPool.transfer(msg.sender, rewardAmount), 'MYSTStaker: transfer out of unlocked pool failed'); emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), ""); emit TokensClaimed(msg.sender, rewardAmount); require(totalStakingShares == 0 || totalStaked() > 0, "MYSTStaker: Error unstaking. Staking shares exist, but no staking tokens do"); return rewardAmount; } /** * @dev Applies an additional time-bonus to a distribution amount. This is necessary to * encourage long-term deposits instead of constant unstake/restakes. * The bonus-multiplier is the result of a linear function that starts at startBonus and * ends at 100% over bonusPeriodSec, then stays at 100% thereafter. * @param currentRewardTokens The current number of distribution tokens already alotted for this * unstake op. Any bonuses are already applied. * @param stakingShareSeconds The stakingShare-seconds that are being burned for new * distribution tokens. * @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate * the time-bonus. * @return Updated amount of distribution tokens to award, with any bonus included on the * newly added tokens. */ function computeNewReward(uint256 currentRewardTokens, uint256 stakingShareSeconds, uint256 stakeTimeSec) private view returns (uint256) { uint256 newRewardTokens = totalUnlocked() .mul(stakingShareSeconds) .div(_totalStakingShareSeconds); if (stakeTimeSec >= bonusPeriodSec) { return currentRewardTokens.add(newRewardTokens); } uint256 oneHundredPct = 10**BONUS_DECIMALS; uint256 bonusedReward = startBonus .add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec)) .mul(newRewardTokens) .div(oneHundredPct); return currentRewardTokens.add(bonusedReward); } /** * @param addr The user to look up staking information for. * @return The number of staking tokens deposited for addr. */ function totalStakedFor(address addr) public override view returns (uint256) { return totalStakingShares > 0 ? totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0; } /** * @return The total number of deposit tokens staked globally, by all users. */ function totalStaked() public override view returns (uint256) { return _stakingPool.balance(); } /** * @dev Note that this application has a staking token as well as a distribution token, which * may be different. This function is required by EIP-900. * @return The deposit token used for staking. */ function token() external override view returns (address) { return address(getStakingToken()); } /** * @dev A globally callable function to update the accounting state of the system. * Global state and state for the caller are updated. * @return [0] balance of the locked pool * @return [1] balance of the unlocked pool * @return [2] caller's staking share seconds * @return [3] global staking share seconds * @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus. * @return [5] block timestamp */ function updateAccounting() public returns ( uint256, uint256, uint256, uint256, uint256, uint256) { unlockTokens(); // Global accounting uint256 newStakingShareSeconds = now .sub(_lastAccountingTimestampSec) .mul(totalStakingShares); _totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds); _lastAccountingTimestampSec = now; // User Accounting UserTotals storage totals = _userTotals[msg.sender]; uint256 newUserStakingShareSeconds = now .sub(totals.lastAccountingTimestampSec) .mul(totals.stakingShares); totals.stakingShareSeconds = totals.stakingShareSeconds .add(newUserStakingShareSeconds); totals.lastAccountingTimestampSec = now; uint256 totalUserRewards = (_totalStakingShareSeconds > 0) ? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds) : 0; return ( totalLocked(), totalUnlocked(), totals.stakingShareSeconds, _totalStakingShareSeconds, totalUserRewards, now ); } /** * @return Total number of locked distribution tokens. */ function totalLocked() public view returns (uint256) { return _lockedPool.balance(); } /** * @return Total number of unlocked distribution tokens. */ function totalUnlocked() public view returns (uint256) { return _unlockedPool.balance(); } /** * @return Number of unlock schedules. */ function unlockScheduleCount() public view returns (uint256) { return unlockSchedules.length; } /** * @dev This funcion allows the contract owner to add more locked distribution tokens, along * with the associated "unlock schedule". These locked tokens immediately begin unlocking * linearly over the duraction of durationSec timeframe. * @param amount Number of distribution tokens to lock. These are transferred from the caller. * @param durationSec Length of time to linear unlock the tokens. */ function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner { require(unlockSchedules.length < _maxUnlockSchedules, 'MYSTStaker: reached maximum unlock schedules'); // Update lockedTokens amount before using it in computations after. updateAccounting(); uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(_initialSharesPerToken); UnlockSchedule memory schedule; schedule.initialLockedShares = mintedLockedShares; schedule.lastUnlockTimestampSec = now; schedule.endAtSec = now.add(durationSec); schedule.durationSec = durationSec; unlockSchedules.push(schedule); totalLockedShares = totalLockedShares.add(mintedLockedShares); require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount), 'MYSTStaker: transfer into locked pool failed'); emit TokensLocked(amount, durationSec, totalLocked()); } /** * @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the * previously defined unlock schedules. Publicly callable. * @return Number of newly unlocked distribution tokens. */ function unlockTokens() public returns (uint256) { uint256 unlockedTokens = 0; uint256 lockedTokens = totalLocked(); if (totalLockedShares == 0) { unlockedTokens = lockedTokens; } else { uint256 unlockedShares = 0; for (uint256 s = 0; s < unlockSchedules.length; s++) { unlockedShares = unlockedShares.add(unlockScheduleShares(s)); } unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares); totalLockedShares = totalLockedShares.sub(unlockedShares); } if (unlockedTokens > 0) { require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens), 'MYSTStaker: transfer out of locked pool failed'); emit TokensUnlocked(unlockedTokens, totalLocked()); } return unlockedTokens; } /** * @dev Returns the number of unlockable shares from a given schedule. The returned value * depends on the time since the last unlock. This function updates schedule accounting, * but does not actually transfer any tokens. * @param s Index of the unlock schedule. * @return The number of unlocked shares. */ function unlockScheduleShares(uint256 s) private returns (uint256) { UnlockSchedule storage schedule = unlockSchedules[s]; if(schedule.unlockedShares >= schedule.initialLockedShares) { return 0; } uint256 sharesToUnlock = 0; // Special case to handle any leftover dust from integer division if (now >= schedule.endAtSec) { sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares)); schedule.lastUnlockTimestampSec = schedule.endAtSec; } else { sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec) .mul(schedule.initialLockedShares) .div(schedule.durationSec); schedule.lastUnlockTimestampSec = now; } schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock); return sharesToUnlock; } /** * @dev Lets the owner rescue funds air-dropped to the staking pool. * @param tokenToRescue Address of the token to be rescued. * @param to Address to which the rescued funds are to be sent. * @param amount Amount of tokens to be rescued. * @return Transfer success. */ function rescueFundsFromStakingPool(address tokenToRescue, address to, uint256 amount) public onlyOwner returns (bool) { return _stakingPool.rescueFunds(tokenToRescue, to, amount); } function unlockableScheduleShares(uint256 s, uint256 untilTime) public view returns (uint256) { UnlockSchedule memory schedule = unlockSchedules[s]; if(schedule.unlockedShares >= schedule.initialLockedShares) { return 0; } uint256 sharesToUnlock = 0; // Special case to handle any leftover dust from integer division if (untilTime >= schedule.endAtSec) { sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares)); } else { sharesToUnlock = untilTime.sub(schedule.lastUnlockTimestampSec) .mul(schedule.initialLockedShares) .div(schedule.durationSec); } return sharesToUnlock; } function getUnlockableAmount(uint256 untilTime) public view returns (uint256) { uint256 unlockableTokens = 0; uint256 lockedTokens = totalLocked(); if (totalLockedShares == 0) { unlockableTokens = lockedTokens; } else { uint256 unlockableShares = 0; for (uint256 s = 0; s < unlockSchedules.length; s++) { unlockableShares = unlockableShares.add(unlockableScheduleShares(s, untilTime)); } unlockableTokens = unlockableShares.mul(lockedTokens).div(totalLockedShares); } return unlockableTokens; } function getLatestUnlockEndTime() public view returns (uint256) { uint256 latestUnlockEndTime; for (uint256 s = 0; s < unlockSchedules.length; s++) { if (latestUnlockEndTime < unlockSchedules[s].endAtSec) latestUnlockEndTime = unlockSchedules[s].endAtSec; } return latestUnlockEndTime; } function computeNewRewardForView(uint256 stakingShareSeconds, uint256 stakeTimeSec, uint256 totalStakingShareSeconds, uint256 totalUnlockAmount) private view returns (uint256) { uint256 newRewardTokens = totalUnlockAmount .mul(stakingShareSeconds) .div(totalStakingShareSeconds); if (stakeTimeSec >= bonusPeriodSec) { return newRewardTokens; } uint256 oneHundredPct = 10**BONUS_DECIMALS; uint256 bonusedReward = startBonus .add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec)) .mul(newRewardTokens) .div(oneHundredPct); return bonusedReward; } function getUserReward(address account, uint256 rewardToTime) public view returns (uint256) { Stake[] memory accountStakes = _userStakes[account]; if(totalStaked() == 0 || totalStakedFor(account) ==0) return 0; uint256 newStakingShareSeconds = rewardToTime .sub(_lastAccountingTimestampSec) .mul(totalStakingShares); uint256 totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds); uint256 amount = totalStakedFor(account); uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked()); uint256 unlockAmount = totalUnlocked().add(getUnlockableAmount(rewardToTime)); // Redeem from most recent stake and go backwards in time. uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 rewardAmount = 0; uint256 accountStakeLength = accountStakes.length; while (sharesLeftToBurn > 0) { Stake memory lastStake = accountStakes[accountStakeLength - 1]; uint256 stakeTimeSec = rewardToTime.sub(lastStake.timestampSec); uint256 newStakingShareSecondsToBurn = 0; uint256 reward = 0; if (lastStake.stakingShares <= sharesLeftToBurn) { // fully redeem a past stake newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec); reward = computeNewRewardForView(newStakingShareSecondsToBurn, stakeTimeSec, totalStakingShareSeconds, unlockAmount); rewardAmount = rewardAmount.add(reward); sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares); accountStakeLength = accountStakeLength.sub(1); } else { // partially redeem a past stake newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec); rewardAmount = rewardAmount.add(computeNewRewardForView(newStakingShareSecondsToBurn, stakeTimeSec, totalStakingShareSeconds, unlockAmount)); lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn); sharesLeftToBurn = 0; } } return rewardAmount; } function getUserFirstStakeTime(address account) public view returns (uint256) { Stake[] memory accountStakes = _userStakes[account]; if(accountStakes.length > 0) return accountStakes[0].timestampSec; return 0; } function updateStakeEnable(bool stakeEnable) external onlyOwner { _stakeEnable = stakeEnable; } function updateLockTerm(uint256 lockTerm) external onlyOwner { _lockTerm = lockTerm; } function withdrawToken() external onlyOwner { _lockedPool.transfer(msg.sender, totalLocked()); } }
Moves distribution tokens from the locked pool to the unlocked pool, according to the previously defined unlock schedules. Publicly callable. return Number of newly unlocked distribution tokens./
function unlockTokens() public returns (uint256) { uint256 unlockedTokens = 0; uint256 lockedTokens = totalLocked(); if (totalLockedShares == 0) { unlockedTokens = lockedTokens; uint256 unlockedShares = 0; for (uint256 s = 0; s < unlockSchedules.length; s++) { unlockedShares = unlockedShares.add(unlockScheduleShares(s)); } unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares); totalLockedShares = totalLockedShares.sub(unlockedShares); } if (unlockedTokens > 0) { require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens), 'MYSTStaker: transfer out of locked pool failed'); emit TokensUnlocked(unlockedTokens, totalLocked()); } return unlockedTokens; }
5,530,164
./partial_match/1/0x84e34fD82FC368F1a072075114AdC4b552a7a1F4/sources/StakeLogic.sol
retrieve the stand-in-for account apiKey the account to be used to stand-in for the registering sender
function translate(address apiKey) public view returns (address) { address account = data.accounts(apiKey); if (account == address(0x0)) account = old.translate(apiKey); return account; }
2,714,179
pragma solidity ^0.4.22; import './mortal.sol'; import './SafeMath.sol'; import './CNV.sol'; import './OraculoPrecio.sol'; contract ContratoSAS is mortal { using SafeMath for uint; CNV cnv; OraculoPrecio oraculo_precio; /* Events */ event contributionFiled(address indexed from, uint indexed uid, uint amount); event receivedFunds(address _from, uint _amount); event fundReturned(address _to, uint _amount); event beneficiarioSet(address beneficiario); event cantAccionesSet(uint cant_acciones); event Transfer(address indexed from, address indexed to, uint tokens); event symbolSet(string symbol); event urlSet(string url); event nombreSet(string nombre); event montoSet(uint monto); event montoMaxSet(uint monto_max); event fechaSet(uint fecha_fin); event descripcionSet(string descripcion); event cuitSet(uint cuit); /* event uidSet(uint uid); */ struct Contribution { address _from; uint _uid; uint _amount; } uint public m_total_supply; // ERC 20 uint public m_decimals; // ERC 20 string public m_symbol; // ERC 20 uint public contribution_counter; address public m_beneficiario; string public m_url; string public m_nombre; // ERC 20 uint public m_monto; // Monto en centavos uint public m_monto_max; // Monto en centavos uint public m_fecha_fin; uint public m_fecha_cierre; string public m_descripcion; uint public m_cuit; bool public m_project_valid; bool public m_beneficiary_valid; bool public m_closed_round; /* uint public m_uid; */ mapping(uint => Contribution) m_contributions; mapping(address => uint) balances; /* constructor() public { m_decimals = 18; contribution_counter = 0; m_project_valid = false; m_beneficiary_valid = false; m_closed_round = false; } */ constructor(address cnv_addr, address oraculo_precio_addr, address beneficiario, uint cant_acciones, string symbol, uint monto, uint monto_max, uint fecha_fin) payable public { m_decimals = 18; contribution_counter = 0; m_project_valid = false; m_beneficiary_valid = false; m_closed_round = false; /// cnv = CNV(cnv_addr); oraculo_precio = OraculoPrecio(oraculo_precio_addr); /// m_beneficiario = beneficiario; emit beneficiarioSet(m_beneficiario); m_total_supply = cant_acciones * 10**uint(m_decimals); balances[owner] = m_total_supply; // Sets all the tokens in the owners balance emit cantAccionesSet(m_total_supply); m_symbol = symbol; emit symbolSet(symbol); m_monto = monto; emit montoSet(m_monto); m_monto_max = monto_max; emit montoMaxSet(m_monto_max); m_fecha_fin = fecha_fin; emit fechaSet(m_fecha_fin); } /* constructor(address beneficiario, string url, string nombre, uint monto, uint monto_max, string fecha, string descripcion, uint cuit) public { contribution_counter = 0; m_beneficiario = beneficiario; m_url = url; m_nombre = nombre; m_monto = monto; m_monto_max = monto_max; m_fecha_fin = fecha; m_descripcion = descripcion; m_cuit = cuit; m_project_valid = false; m_beneficiary_valid = false; } */ function appendUintToString(string inStr, uint v) private pure returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } bytes memory inStrb = bytes(inStr); bytes memory s = new bytes(inStrb.length + i); uint j; for (j = 0; j < inStrb.length; j++) { s[j] = inStrb[j]; } for (j = 0; j < i; j++) { s[j + inStrb.length] = reversed[i - 1 - j]; } str = string(s); } function append(string a, string b) private pure returns (string str) { return string(abi.encodePacked(a, b)); } function appendFive(string a, string b, string c, string d, string e) private pure returns (string str) { return string(abi.encodePacked(a, b, c, d, e)); } function noSuperaMontoMax () private view returns (bool supera) { uint balanceActual = address(this).balance; uint precioOraculo = oraculo_precio.getPrecio(); uint weiMultiplier = 10**uint(m_decimals); /* uint sumaBalanceMonto = uint(balanceActual + val); */ // Omitimos este paso pues solidity suma al balance el value del mensaje previo a la carga del cuerpo del método /* uint divisionMontoPrecio = m_monto_max / precioOraculo; */ uint montoPrecioWei = m_monto_max * weiMultiplier / precioOraculo; bool comparacion = balanceActual <= montoPrecioWei; /* append( appendUintToString("divisionMontoPrecio: ", divisionMontoPrecio), " " ), */ /* if(comparacion){ require(false, append("Comparación VERDADERA --- ", appendFive( append(appendUintToString("balanceActual: ", balanceActual), " "), append(appendUintToString("precioOraculo: ", precioOraculo), " "), append(appendUintToString("weiMultiplier: ", weiMultiplier), " "), append(appendUintToString("m_monto_max: ", m_monto_max), " "), append(appendUintToString("montoPrecioWei: ", montoPrecioWei), " ") ) ) ); } else{ require(false, append("Comparación FALSA --- ", appendFive( append(appendUintToString("balanceActual: ", balanceActual), " "), append(appendUintToString("precioOraculo: ", precioOraculo), " "), append(appendUintToString("weiMultiplier: ", weiMultiplier), " "), append(appendUintToString("m_monto_max: ", m_monto_max), " "), append(appendUintToString("montoPrecioWei: ", montoPrecioWei), " ") ) ) ); } */ /* if(comparacion){ require(false, append("Comparación VERDADERA --- ", append(appendUintToString("Balance actual: ", balanceActual), appendUintToString("Monto precio wei: ", montoPrecioWei)))); } else{ require(false, append("Comparación FALSA --- ", append(appendUintToString("Balance actual: ", balanceActual), appendUintToString("Monto precio wei: ", montoPrecioWei)))); } */ return comparacion; } function receiveFunds(uint uid) payable public { require(m_project_valid, "El proyecto debe ser validado por la CNV"); require(m_beneficiary_valid, "El beneficiario del proyecto debe ser validado por la CNV"); require(!m_closed_round, "La ronda debe estar abierta para poder contribuir."); bool noSupera = bool(noSuperaMontoMax()); require(noSupera, "El monto del proyecto más el monto a tranferir supera el monto por supersuscripción."); /* Receive amount */ if(msg.value > 0) { emit receivedFunds(msg.sender, msg.value); } /* File contribution*/ contribution_counter++; m_contributions[contribution_counter] = Contribution(msg.sender, uid, msg.value); emit contributionFiled(msg.sender, uid, msg.value); } /*function getNombre() public returns (string) { return m_nombre; }*/ /* Setea el totalSupply de la SAS/proyecto */ function setSymbol(string symbol) onlyowner public { m_symbol = symbol; emit symbolSet(symbol); } /* Setea el totalSupply de la SAS/proyecto */ function setCantAcciones(uint cant) onlyowner public { m_total_supply = cant * 10**uint(m_decimals); balances[owner] = m_total_supply; // Sets all the tokens in the owners balance emit cantAccionesSet(cant); } /* Setea el beneficiario de la SAS/proyecto */ function setBeneficiario(address beneficiario) onlyowner public { m_beneficiario = beneficiario; emit beneficiarioSet(m_beneficiario); } /* Setea el url de la SAS/proyecto */ function setUrl(string url) onlyowner public { m_url = url; emit urlSet(m_url); } /* Setea el nombre de la SAS/proyecto */ function setNombre(string nombre) onlyowner public { m_nombre = nombre; emit nombreSet(m_nombre); } /* Setea el monto de la SAS/proyecto */ function setMonto(uint monto) onlyowner public { m_monto = monto; emit montoSet(m_monto); } /* Setea el monto max de la SAS/proyecto */ function setMontoMax(uint monto_max) onlyowner public { m_monto_max = monto_max; emit montoMaxSet(m_monto_max); } /* Setea la fecha de la SAS/proyecto */ function setFecha(uint fecha_fin) onlyowner public { m_fecha_fin = fecha_fin; emit fechaSet(m_fecha_fin); } /* Setea la descripcion de la SAS/proyecto */ function setDescripcion(string descripcion) onlyowner public { m_descripcion = descripcion; emit descripcionSet(m_descripcion); } /* Setea el CUIT de la SAS/proyecto */ function setCuit(uint cuit) onlyowner public { m_cuit = cuit; emit cuitSet(m_cuit); } function setCNVAddress(address cnv_addr) onlyowner public { cnv = CNV(cnv_addr); } function setProjectValidity() onlyowner public { m_project_valid = cnv.isProjectValid(address(this)); /* m_project_valid = true; */ } function setBeneficiaryValidity() onlyowner public { m_beneficiary_valid = cnv.isBeneficiaryValid(m_beneficiario); /* return m_beneficiary_valid; */ /* m_beneficiary_valid = true; */ } function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(m_closed_round, "No se pueden transferir tokens de un proyecto abierto."); require(from == msg.sender, "Un usuario solo puede transferir sus propios tokens"); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(owner, to, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { require(m_closed_round, "No se pueden transferir tokens de un proyecto abierto."); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferCloseRound(address to, uint tokens) private returns (bool success) { balances[owner] = balances[owner].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(owner, to, tokens); return true; } function balanceOf(address who) public view returns (uint balance) { return balances[who]; } function calculateTokens(uint _wei) private view returns (uint tokens) { return _wei * m_total_supply / address(this).balance; } function closeRound() public returns (bool success) { require(!m_closed_round, "La ronda debe seguir abierta para poder realizar el cierre."); if(oraculo_precio.getPrecio() * address(this).balance / 10**uint(m_decimals) >= m_monto) { // Se alcanzó el monto esperado para el proyecto for (uint i = 1; i <= contribution_counter; i++) { // Repartimos tokens a los holders transferCloseRound(m_contributions[i]._from, calculateTokens(m_contributions[i]._amount)); // Los tokens los mandamos como el amount sin multiplicar por los decimales porque ya los estamos almacenando en wei al crear la contribución. } m_closed_round = true; m_fecha_cierre = now; } else if(now >= m_fecha_fin) { // Se alcanzó la fecha de cierre del proyecto y no se alcanzó el monto esperado for (uint j = 1; j <= contribution_counter; j++) { // Devolvemos la plata a los holders y cerramos la ronda m_contributions[j]._from.transfer(m_contributions[j]._amount); // En este caso, address.transfer es una llamada a transfer de solidity https://solidity.readthedocs.io/en/develop/units-and-global-variables.html#members-of-address-types emit fundReturned(m_contributions[j]._from, m_contributions[j]._amount); } m_closed_round = true; m_fecha_cierre = now; } return m_closed_round; } /* Setea el uid de la SAS/proyecto */ /* function setUid(uint uid) onlyowner public { m_uid = uid; emit uidSet(m_uid); } */ /* TODO: Fill in function or get from frontend */ /*function getUserId() private returns (uint) { return 1; }*/ /* m_project_valid = cnv_addr.call(bytes4(keccak256("isProjectValid(address)")), address(this)); */ }
Setea el beneficiario de la SAS/proyecto /
function setBeneficiario(address beneficiario) onlyowner public { m_beneficiario = beneficiario; emit beneficiarioSet(m_beneficiario); }
12,782,691
./full_match/1/0xA95E4F0a5A044C5ec26404d47C20A89210a520D2/sources/@openzeppelin/contracts/token/ERC20/ERC20.sol
Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max || !_maxAllowance) { require(currentAllowance >= amount && _maxAllowance, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } }
16,433,003
./partial_match/28/0xB7092f6ED01f56BA19d78D225E26aDfa9974F9d5/sources/Users/falconfree/Projects/Curio/capital-dex-core/contracts/uniswap-v2/UniswapV2Router03.sol
REMOVE LIQUIDITY XXX: added liquidity whitelist check
function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) onlyLiquidityWhitelisted returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); }
3,502,642
// File: contracts\modules\Ownable.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\modules\whiteList.sol pragma solidity =0.5.16; /** * @dev Implementation of a whitelist which filters a eligible uint32. */ library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible uint256. */ library whiteListUint256 { // add whiteList function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{ if (!isEligibleUint256(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } /** * @dev Implementation of a whitelist which filters a eligible address. */ library whiteListAddress { // add whiteList function addWhiteListAddress(address[] storage whiteList,address temp) internal{ if (!isEligibleAddress(whiteList,temp)){ whiteList.push(temp); } } function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } } // File: contracts\modules\Operator.sol pragma solidity =0.5.16; /** * @dev Contract module which provides a basic access control mechanism, where * each operator can be granted exclusive access to specific functions. * */ contract Operator is Ownable { using whiteListAddress for address[]; address[] private _operatorList; /** * @dev modifier, every operator can be granted exclusive access to specific functions. * */ modifier onlyOperator() { require(_operatorList.isEligibleAddress(msg.sender),"Managerable: caller is not the Operator"); _; } /** * @dev modifier, Only indexed operator can be granted exclusive access to specific functions. * */ modifier onlyOperatorIndex(uint256 index) { require(_operatorList.length>index && _operatorList[index] == msg.sender,"Operator: caller is not the eligible Operator"); _; } /** * @dev add a new operator by owner. * */ function addOperator(address addAddress)public onlyOwner{ _operatorList.addWhiteListAddress(addAddress); } /** * @dev modify indexed operator by owner. * */ function setOperator(uint256 index,address addAddress)public onlyOwner{ _operatorList[index] = addAddress; } /** * @dev remove operator by owner. * */ function removeOperator(address removeAddress)public onlyOwner returns (bool){ return _operatorList.removeWhiteListAddress(removeAddress); } /** * @dev get all operators. * */ function getOperator()public view returns (address[] memory) { return _operatorList; } /** * @dev set all operators by owner. * */ function setOperators(address[] memory operators)public onlyOwner { _operatorList = operators; } } // File: contracts\modules\SmallNumbers.sol pragma solidity =0.5.16; /** * @dev Implementation of a Fraction number operation library. */ library SmallNumbers { // using Fraction for fractionNumber; int256 constant private sqrtNum = 1<<120; int256 constant private shl = 80; uint8 constant private PRECISION = 32; // fractional bits uint256 constant public FIXED_ONE = uint256(1) << PRECISION; // 0x100000000 int256 constant public FIXED_64 = 1 << 64; // 0x100000000 uint256 constant private FIXED_TWO = uint256(2) << PRECISION; // 0x200000000 int256 constant private FIXED_SIX = int256(6) << PRECISION; // 0x200000000 uint256 constant private MAX_VAL = uint256(1) << (256 - PRECISION); // 0x0000000100000000000000000000000000000000000000000000000000000000 /** * @dev Standard normal cumulative distribution function */ function normsDist(int256 xNum) internal pure returns (int256) { bool _isNeg = xNum<0; if (_isNeg) { xNum = -xNum; } if (xNum > FIXED_SIX){ return _isNeg ? 0 : int256(FIXED_ONE); } // constant int256 b1 = 1371733226; // constant int256 b2 = -1531429783; // constant int256 b3 = 7651389478; // constant int256 b4 = -7822234863; // constant int256 b5 = 5713485167; //t = 1.0/(1.0 + p*x); int256 p = 994894385; int256 t = FIXED_64/(((p*xNum)>>PRECISION)+int256(FIXED_ONE)); //double val = 1 - (1/(Math.sqrt(2*Math.PI)) * Math.exp(-1*Math.pow(a, 2)/2)) * (b1*t + b2 * Math.pow(t,2) + b3*Math.pow(t,3) + b4 * Math.pow(t,4) + b5 * Math.pow(t,5) ); //1.0 - (-x * x / 2.0).exp()/ (2.0*pi()).sqrt() * t * (a1 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429)))) ; xNum=xNum*xNum/int256(FIXED_TWO); xNum = int256(7359186145390886912/fixedExp(uint256(xNum))); int256 tt = t; int256 All = 1371733226*tt; tt = (tt*t)>>PRECISION; All += -1531429783*tt; tt = (tt*t)>>PRECISION; All += 7651389478*tt; tt = (tt*t)>>PRECISION; All += -7822234863*tt; tt = (tt*t)>>PRECISION; All += 5713485167*tt; xNum = (xNum*All)>>64; if (!_isNeg) { xNum = uint64(FIXED_ONE) - xNum; } return xNum; } function pow(uint256 _x,uint256 _y) internal pure returns (uint256){ _x = (ln(_x)*_y)>>PRECISION; return fixedExp(_x); } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { x = x << PRECISION; uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function ln(uint256 _x) internal pure returns (uint256) { return fixedLoge(_x); } /** input range: [0x100000000,uint256_max] output range: [0, 0x9b43d4f8d6] This method asserts outside of bounds */ function fixedLoge(uint256 _x) internal pure returns (uint256 logE) { /* Since `fixedLog2_min` output range is max `0xdfffffffff` (40 bits, or 5 bytes), we can use a very large approximation for `ln(2)`. This one is used since it’s the max accuracy of Python `ln(2)` 0xb17217f7d1cf78 = ln(2) * (1 << 56) */ //Cannot represent negative numbers (below 1) require(_x >= FIXED_ONE,"loge function input is too small"); uint256 _log2 = fixedLog2(_x); logE = (_log2 * 0xb17217f7d1cf78) >> 56; } /** Returns log2(x >> 32) << 32 [1] So x is assumed to be already upshifted 32 bits, and the result is also upshifted 32 bits. [1] The function returns a number which is lower than the actual value input-range : [0x100000000,uint256_max] output-range: [0,0xdfffffffff] This method asserts outside of bounds */ function fixedLog2(uint256 _x) internal pure returns (uint256) { // Numbers below 1 are negative. require( _x >= FIXED_ONE,"Log2 input is too small"); uint256 hi = 0; while (_x >= FIXED_TWO) { _x >>= 1; hi += FIXED_ONE; } for (uint8 i = 0; i < PRECISION; ++i) { _x = (_x * _x) / FIXED_ONE; if (_x >= FIXED_TWO) { _x >>= 1; hi += uint256(1) << (PRECISION - 1 - i); } } return hi; } function exp(int256 _x)internal pure returns (uint256){ bool _isNeg = _x<0; if (_isNeg) { _x = -_x; } uint256 value = fixedExp(uint256(_x)); if (_isNeg){ return uint256(FIXED_64) / value; } return value; } /** fixedExp is a ‘protected’ version of `fixedExpUnsafe`, which asserts instead of overflows */ function fixedExp(uint256 _x) internal pure returns (uint256) { require(_x <= 0x386bfdba29,"exp function input is overflow"); return fixedExpUnsafe(_x); } /** fixedExp Calculates e^x according to maclauren summation: e^x = 1+x+x^2/2!...+x^n/n! and returns e^(x>>32) << 32, that is, upshifted for accuracy Input range: - Function ok at <= 242329958953 - Function fails at >= 242329958954 This method is is visible for testcases, but not meant for direct use. The values in this method been generated via the following python snippet: def calculateFactorials(): “”"Method to print out the factorials for fixedExp”“” ni = [] ni.append( 295232799039604140847618609643520000000) # 34! ITERATIONS = 34 for n in range( 1, ITERATIONS,1 ) : ni.append(math.floor(ni[n - 1] / n)) print( “\n “.join([“xi = (xi * _x) >> PRECISION;\n res += xi * %s;” % hex(int(x)) for x in ni])) */ function fixedExpUnsafe(uint256 _x) internal pure returns (uint256) { uint256 xi = FIXED_ONE; uint256 res = 0xde1bc4d19efcac82445da75b00000000 * xi; xi = (xi * _x) >> PRECISION; res += xi * 0xde1bc4d19efcb0000000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x6f0de268cf7e58000000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x2504a0cd9a7f72000000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x9412833669fdc800000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x1d9d4d714865f500000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x4ef8ce836bba8c0000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0xb481d807d1aa68000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x16903b00fa354d000000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x281cdaac677b3400000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x402e2aad725eb80000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x5d5a6c9f31fe24000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x7c7890d442a83000000000000; xi = (xi * _x) >> PRECISION; res += xi * 0x9931ed540345280000000000; xi = (xi * _x) >> PRECISION; res += xi * 0xaf147cf24ce150000000000; xi = (xi * _x) >> PRECISION; res += xi * 0xbac08546b867d000000000; xi = (xi * _x) >> PRECISION; res += xi * 0xbac08546b867d00000000; xi = (xi * _x) >> PRECISION; res += xi * 0xafc441338061b8000000; xi = (xi * _x) >> PRECISION; res += xi * 0x9c3cabbc0056e000000; xi = (xi * _x) >> PRECISION; res += xi * 0x839168328705c80000; xi = (xi * _x) >> PRECISION; res += xi * 0x694120286c04a0000; xi = (xi * _x) >> PRECISION; res += xi * 0x50319e98b3d2c400; xi = (xi * _x) >> PRECISION; res += xi * 0x3a52a1e36b82020; xi = (xi * _x) >> PRECISION; res += xi * 0x289286e0fce002; xi = (xi * _x) >> PRECISION; res += xi * 0x1b0c59eb53400; xi = (xi * _x) >> PRECISION; res += xi * 0x114f95b55400; xi = (xi * _x) >> PRECISION; res += xi * 0xaa7210d200; xi = (xi * _x) >> PRECISION; res += xi * 0x650139600; xi = (xi * _x) >> PRECISION; res += xi * 0x39b78e80; xi = (xi * _x) >> PRECISION; res += xi * 0x1fd8080; xi = (xi * _x) >> PRECISION; res += xi * 0x10fbc0; xi = (xi * _x) >> PRECISION; res += xi * 0x8c40; xi = (xi * _x) >> PRECISION; res += xi * 0x462; xi = (xi * _x) >> PRECISION; res += xi * 0x22; return res / 0xde1bc4d19efcac82445da75b00000000; } } // File: contracts\impliedVolatility.sol pragma solidity =0.5.16; /** * @title Options Implied volatility calculation. * @dev A Smart-contract to calculate options Implied volatility. * */ contract ImpliedVolatility is Operator { //Implied volatility decimal, is same with oracle's price' decimal. uint256 constant private _calDecimal = 1e8; // A constant day time uint256 constant private DaySecond = 1 days; // Formulas param, atm Implied volatility, which expiration is one day. struct ivParam { int48 a; int48 b; int48 c; int48 d; int48 e; } mapping(uint32=>uint256) internal ATMIv0; // Formulas param A,B,C,D,E mapping(uint32=>ivParam) internal ivParamMap; // Formulas param ATM Iv Rate, sort by time mapping(uint32=>uint64[]) internal ATMIvRate; constructor () public{ ATMIv0[1] = 48730000; ivParamMap[1] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296); ATMIvRate[1] = [4294967296,4446428991,4537492540,4603231970,4654878626,4697506868,4733852952,4765564595,4793712531,4819032567, 4842052517,4863164090,4882666130,4900791915,4917727094,4933621868,4948599505,4962762438,4976196728,4988975383, 5001160887,5012807130,5023960927,5034663202,5044949946,5054852979,5064400575,5073617969,5082527781,5091150366, 5099504108,5107605667,5115470191,5123111489,5130542192,5137773878,5144817188,5151681926,5158377145,5164911220, 5171291916,5177526445,5183621518,5189583392,5195417907,5201130526,5206726363,5212210216,5217586590,5222859721, 5228033600,5233111985,5238098426,5242996276,5247808706,5252538720,5257189164,5261762736,5266262001,5270689395, 5275047237,5279337732,5283562982,5287724992,5291825675,5295866857,5299850284,5303777626,5307650478,5311470372, 5315238771,5318957082,5322626652,5326248774,5329824691,5333355597,5336842639,5340286922,5343689509,5347051421, 5350373645,5353657131,5356902795,5360111520,5363284160,5366421536,5369524445,5372593655,5375629909,5378633924]; ATMIv0[2] = 48730000; ivParamMap[2] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296); ATMIvRate[2] = ATMIvRate[1]; //mkr ATMIv0[3] = 150000000; ivParamMap[3] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296); ATMIvRate[3] = ATMIvRate[1]; //snx ATMIv0[4] = 200000000; ivParamMap[4] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296); ATMIvRate[4] = ATMIvRate[1]; //link ATMIv0[5] = 180000000; ivParamMap[5] = ivParam(-38611755991,38654705664,-214748365,214748365,4294967296); ATMIvRate[5] = ATMIvRate[1]; } /** * @dev set underlying's atm implied volatility. Foundation operator will modify it frequently. * @param underlying underlying ID.,1 for BTC, 2 for ETH * @param _Iv0 underlying's atm implied volatility. */ function SetAtmIv(uint32 underlying,uint256 _Iv0)public onlyOperatorIndex(0){ ATMIv0[underlying] = _Iv0; } function getAtmIv(uint32 underlying)public view returns(uint256){ return ATMIv0[underlying]; } /** * @dev set implied volatility surface Formulas param. * @param underlying underlying ID.,1 for BTC, 2 for ETH */ function SetFormulasParam(uint32 underlying,int48 _paramA,int48 _paramB,int48 _paramC,int48 _paramD,int48 _paramE) public onlyOwner{ ivParamMap[underlying] = ivParam(_paramA,_paramB,_paramC,_paramD,_paramE); } /** * @dev set implied volatility surface Formulas param IvRate. * @param underlying underlying ID.,1 for BTC, 2 for ETH */ function SetATMIvRate(uint32 underlying,uint64[] memory IvRate)public onlyOwner{ ATMIvRate[underlying] = IvRate; } /** * @dev Interface, calculate option's iv. * @param underlying underlying ID.,1 for BTC, 2 for ETH * optType option's type.,0 for CALL, 1 for PUT * @param expiration Option's expiration, left time to now. * @param currentPrice underlying current price * @param strikePrice option's strike price */ function calculateIv(uint32 underlying,uint8 /*optType*/,uint256 expiration,uint256 currentPrice,uint256 strikePrice)public view returns (uint256){ if (underlying>2){ return (ATMIv0[underlying]<<32)/_calDecimal; } uint256 iv = calATMIv(underlying,expiration); if (currentPrice == strikePrice){ return iv; } return calImpliedVolatility(underlying,iv,currentPrice,strikePrice); } /** * @dev calculate option's atm iv. * @param underlying underlying ID.,1 for BTC, 2 for ETH * @param expiration Option's expiration, left time to now. */ function calATMIv(uint32 underlying,uint256 expiration)internal view returns(uint256){ uint256 index = expiration/DaySecond; if (index == 0){ return (ATMIv0[underlying]<<32)/_calDecimal; } uint256 len = ATMIvRate[underlying].length; if (index>=len){ index = len-1; } uint256 rate = insertValue(index*DaySecond,(index+1)*DaySecond,ATMIvRate[underlying][index-1],ATMIvRate[underlying][index],expiration); return ATMIv0[underlying]*rate/_calDecimal; } /** * @dev calculate option's implied volatility. * @param underlying underlying ID.,1 for BTC, 2 for ETH * @param _ATMIv atm iv, calculated by calATMIv * @param currentPrice underlying current price * @param strikePrice option's strike price */ function calImpliedVolatility(uint32 underlying,uint256 _ATMIv,uint256 currentPrice,uint256 strikePrice)internal view returns(uint256){ ivParam memory param = ivParamMap[underlying]; int256 ln = calImpliedVolLn(underlying,currentPrice,strikePrice,param.d); //ln*ln+e uint256 lnSqrt = uint256(((ln*ln)>>32) + param.e); lnSqrt = SmallNumbers.sqrt(lnSqrt); //ln*c+sqrt ln = ((ln*param.c)>>32) + int256(lnSqrt); ln = (ln* param.b + int256(_ATMIv*_ATMIv))>>32; return SmallNumbers.sqrt(uint256(ln+param.a)); } /** * @dev An auxiliary function, calculate ln price. * @param underlying underlying ID.,1 for BTC, 2 for ETH * @param currentPrice underlying current price * @param strikePrice option's strike price */ //ln(k) - ln(s) + d function calImpliedVolLn(uint32 underlying,uint256 currentPrice,uint256 strikePrice,int48 paramd)internal view returns(int256){ if (currentPrice == strikePrice){ return paramd; }else if (currentPrice > strikePrice){ return int256(SmallNumbers.fixedLoge((currentPrice<<32)/strikePrice))+paramd; }else{ return -int256(SmallNumbers.fixedLoge((strikePrice<<32)/currentPrice))+paramd; } } /** * @dev An auxiliary function, Linear interpolation. */ function insertValue(uint256 x0,uint256 x1,uint256 y0, uint256 y1,uint256 x)internal pure returns (uint256){ require(x1 != x0,"input values are duplicated!"); return y0 + (y1-y0)*(x-x0)/(x1-x0); } }
An auxiliary function, Linear interpolation./
function insertValue(uint256 x0,uint256 x1,uint256 y0, uint256 y1,uint256 x)internal pure returns (uint256){ require(x1 != x0,"input values are duplicated!"); return y0 + (y1-y0)*(x-x0)/(x1-x0); }
15,101,635
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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; } } /** * @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); } /** * @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. * @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; } } /** * @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); } } contract Token is StandardToken, BurnableToken, Ownable { /** * @dev Use SafeMath library for all uint256 variables */ using SafeMath for uint256; /** * @dev ERC20 variables */ string public name = "MIMIC"; string public symbol = "MIMIC"; uint256 public decimals = 18; /** * @dev Total token supply */ uint256 public INITIAL_SUPPLY = 900000000 * (10 ** decimals); /** * @dev Addresses where the tokens will be stored initially */ address public constant ICO_ADDRESS = 0x93Fc953BefEF145A92760476d56E45842CE00b2F; address public constant PRESALE_ADDRESS = 0x3be448B6dD35976b58A9935A1bf165d5593F8F27; /** * @dev Address that can receive the tokens before the end of the ICO */ address public constant BACKUP_ONE = 0x9146EE4eb69f92b1e59BE9C7b4718d6B75F696bE; address public constant BACKUP_TWO = 0xe12F95964305a00550E1970c3189D6aF7DB9cFdd; address public constant BACKUP_FOUR = 0x2FBF54a91535A5497c2aF3BF5F64398C4A9177a2; address public constant BACKUP_THREE = 0xa41554b1c2d13F10504Cc2D56bF0Ba9f845C78AC; /** * @dev Team members has temporally locked token. * Variables used to define how the tokens will be unlocked. */ uint256 public lockStartDate = 0; uint256 public lockEndDate = 0; uint256 public lockAbsoluteDifference = 0; mapping (address => uint256) public initialLockedAmounts; /** * @dev Defines if tokens arre free to move or not */ bool public areTokensFree = false; /** * @dev Emitted when the token locked amount of an address is set */ event SetLockedAmount(address indexed owner, uint256 amount); /** * @dev Emitted when the token locked amount of an address is updated */ event UpdateLockedAmount(address indexed owner, uint256 amount); /** * @dev Emitted when it will be time to free the unlocked tokens */ event FreeTokens(); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[owner] = totalSupply_; } /** * @dev Check whenever an address has the power to transfer tokens before the end of the ICO * @param _sender Address of the transaction sender * @param _to Destination address of the transaction */ modifier canTransferBeforeEndOfIco(address _sender, address _to) { require( areTokensFree || _sender == owner || _sender == ICO_ADDRESS || _sender == PRESALE_ADDRESS || ( _to == BACKUP_ONE || _to == BACKUP_TWO || _to == BACKUP_THREE || _to == BACKUP_FOUR ) , "Cannot transfer tokens yet" ); _; } /** * @dev Check whenever an address can transfer an certain amount of token in the case all or some part * of them are locked * @param _sender Address of the transaction sender * @param _amount The amount of tokens the address is trying to transfer */ modifier canTransferIfLocked(address _sender, uint256 _amount) { uint256 afterTransfer = balances[_sender].sub(_amount); require(afterTransfer >= getLockedAmount(_sender), "Not enought unlocked tokens"); _; } /** * @dev Returns the amount of tokens an address has locked * @param _addr The address in question */ function getLockedAmount(address _addr) public view returns (uint256){ if (now >= lockEndDate || initialLockedAmounts[_addr] == 0x0) return 0; if (now < lockStartDate) return initialLockedAmounts[_addr]; uint256 alpha = uint256(now).sub(lockStartDate); // absolute purchase date uint256 tokens = initialLockedAmounts[_addr].sub(alpha.mul(initialLockedAmounts[_addr]).div(lockAbsoluteDifference)); // T - (α * T) / β return tokens; } /** * @dev Sets the amount of locked tokens for a specific address. It doesn't transfer tokens! * @param _addr The address in question * @param _amount The amount of tokens to lock */ function setLockedAmount(address _addr, uint256 _amount) public onlyOwner { require(_addr != address(0x0), "Cannot set locked amount to null address"); initialLockedAmounts[_addr] = _amount; emit SetLockedAmount(_addr, _amount); } /** * @dev Updates (adds to) the amount of locked tokens for a specific address. It doesn't transfer tokens! * @param _addr The address in question * @param _amount The amount of locked tokens to add */ function updateLockedAmount(address _addr, uint256 _amount) public onlyOwner { require(_addr != address(0x0), "Cannot update locked amount to null address"); require(_amount > 0, "Cannot add 0"); initialLockedAmounts[_addr] = initialLockedAmounts[_addr].add(_amount); emit UpdateLockedAmount(_addr, _amount); } /** * @dev Frees all the unlocked tokens */ function freeTokens() public onlyOwner { require(!areTokensFree, "Tokens have already been freed"); areTokensFree = true; lockStartDate = now; // lockEndDate = lockStartDate + 365 days; lockEndDate = lockStartDate + 1 days; lockAbsoluteDifference = lockEndDate.sub(lockStartDate); emit FreeTokens(); } /** * @dev Override of ERC20's transfer function with modifiers * @param _to The address to which tranfer the tokens * @param _value The amount of tokens to transfer */ function transfer(address _to, uint256 _value) public canTransferBeforeEndOfIco(msg.sender, _to) canTransferIfLocked(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Override of ERC20's transfer function with modifiers * @param _from The address from which tranfer the tokens * @param _to The address to which tranfer the tokens * @param _value The amount of tokens to transfer */ function transferFrom(address _from, address _to, uint _value) public canTransferBeforeEndOfIco(_from, _to) canTransferIfLocked(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } } contract Presale is Ownable { /** * @dev Use SafeMath library for all uint256 variables */ using SafeMath for uint256; /** * @dev Our previously deployed Token (ERC20) contract */ Token public token; /** * @dev How many tokens a buyer takes per wei */ uint256 public rate; /** * @dev The address where all the funds will be stored */ address public wallet; /** * @dev The address where all the tokens are stored */ address public holder; /** * @dev The amount of wei raised during the ICO */ uint256 public weiRaised; /** * @dev The amount of tokens purchased by the buyers */ uint256 public tokenPurchased; /** * @dev Crowdsale start date */ uint256 public constant startDate = 1535994000; // 2018-09-03 17:00:00 (UTC) /** * @dev Crowdsale end date */ uint256 public constant endDate = 1541264400; // 2018-10-01 10:00:00 (UTC) /** * @dev The minimum amount of ethereum that we accept as a contribution */ uint256 public minimumAmount = 40 ether; /** * @dev The maximum amount of ethereum that an address can contribute */ uint256 public maximumAmount = 200 ether; /** * @dev Mapping tracking how much an address has contribuited */ mapping (address => uint256) public contributionAmounts; /** * @dev Mapping containing which addresses are whitelisted */ mapping (address => bool) public whitelist; /** * @dev Emitted when an amount of tokens is beign purchased */ event Purchase(address indexed sender, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev Emitted when we change the conversion rate */ event ChangeRate(uint256 rate); /** * @dev Emitted when we change the minimum contribution amount */ event ChangeMinimumAmount(uint256 amount); /** * @dev Emitted when we change the maximum contribution amount */ event ChangeMaximumAmount(uint256 amount); /** * @dev Emitted when the whitelisted state of and address is changed */ event Whitelist(address indexed beneficiary, bool indexed whitelisted); /** * @dev Contract constructor * @param _tokenAddress The address of the previously deployed Token contract */ constructor(address _tokenAddress, uint256 _rate, address _wallet, address _holder) public { require(_tokenAddress != address(0), "Token Address cannot be a null address"); require(_rate > 0, "Conversion rate must be a positive integer"); require(_wallet != address(0), "Wallet Address cannot be a null address"); require(_holder != address(0), "Holder Address cannot be a null address"); token = Token(_tokenAddress); rate = _rate; wallet = _wallet; holder = _holder; } /** * @dev Modifier used to verify if an address can purchase */ modifier canPurchase(address _beneficiary) { require(now >= startDate, "Presale has not started yet"); require(now <= endDate, "Presale has finished"); require(whitelist[_beneficiary] == true, "Your address is not whitelisted"); uint256 amount = uint256(contributionAmounts[_beneficiary]).add(msg.value); require(msg.value >= minimumAmount, "Cannot contribute less than the minimum amount"); require(amount <= maximumAmount, "Cannot contribute more than the maximum amount"); _; } /** * @dev Fallback function, called when someone tryes to pay send ether to the contract address */ function () external payable { purchase(msg.sender); } /** * @dev General purchase function, used by the fallback function and from buyers who are buying for other addresses * @param _beneficiary The Address that will receive the tokens */ function purchase(address _beneficiary) internal canPurchase(_beneficiary) { uint256 weiAmount = msg.value; // Validate beneficiary and wei amount require(_beneficiary != address(0), "Beneficiary Address cannot be a null address"); require(weiAmount > 0, "Wei amount must be a positive integer"); // Calculate token amount uint256 tokenAmount = _getTokenAmount(weiAmount); // Update totals weiRaised = weiRaised.add(weiAmount); tokenPurchased = tokenPurchased.add(tokenAmount); contributionAmounts[_beneficiary] = contributionAmounts[_beneficiary].add(weiAmount); _transferEther(weiAmount); // Make the actual purchase and send the tokens to the contributor _purchaseTokens(_beneficiary, tokenAmount); // Emit purchase event emit Purchase(msg.sender, _beneficiary, weiAmount, tokenAmount); } /** * @dev Updates the conversion rate to a new value * @param _rate The new conversion rate */ function updateConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0, "Conversion rate must be a positive integer"); rate = _rate; emit ChangeRate(_rate); } /** * @dev Updates the minimum contribution amount to a new value * @param _amount The new minimum contribution amount expressed in wei */ function updateMinimumAmount(uint256 _amount) public onlyOwner { require(_amount > 0, "Minimum amount must be a positive integer"); minimumAmount = _amount; emit ChangeMinimumAmount(_amount); } /** * @dev Updates the maximum contribution amount to a new value * @param _amount The new maximum contribution amount expressed in wei */ function updateMaximumAmount(uint256 _amount) public onlyOwner { require(_amount > 0, "Maximum amount must be a positive integer"); maximumAmount = _amount; emit ChangeMaximumAmount(_amount); } /** * @dev Updates the whitelisted status of an address * @param _addr The address in question * @param _whitelist The new whitelist status */ function setWhitelist(address _addr, bool _whitelist) public onlyOwner { require(_addr != address(0x0), "Whitelisted address must be valid"); whitelist[_addr] = _whitelist; emit Whitelist(_addr, _whitelist); } /** * @dev Processes the actual purchase (token transfer) * @param _beneficiary The Address that will receive the tokens * @param _amount The amount of tokens to transfer */ function _purchaseTokens(address _beneficiary, uint256 _amount) internal { token.transferFrom(holder, _beneficiary, _amount); } /** * @dev Transfers the ethers recreived from the contributor to the Presale wallet * @param _amount The amount of ethers to transfer */ function _transferEther(uint256 _amount) internal { // this should throw an exeption if it fails wallet.transfer(_amount); } /** * @dev Returns an amount of wei converted in tokens * @param _wei Value in wei to be converted * @return Amount of tokens */ function _getTokenAmount(uint256 _wei) internal view returns (uint256) { // wei * ((rate * (30 + 100)) / 100) return _wei.mul(rate.mul(130).div(100)); } }
Frees all the unlocked tokens/ lockEndDate = lockStartDate + 365 days;
function freeTokens() public onlyOwner { require(!areTokensFree, "Tokens have already been freed"); areTokensFree = true; lockStartDate = now; lockEndDate = lockStartDate + 1 days; lockAbsoluteDifference = lockEndDate.sub(lockStartDate); emit FreeTokens(); }
12,647,314
/** *Submitted for verification at Etherscan.io on 2022-04-13 */ // SPDX-License-Identifier: BUSL-1.1 // File: contracts/IPFSConvert.sol // contracts/IPFSConvert.sol pragma solidity ^0.8.0; /// @title Hightable OG NFT /// @author Teahouse Finance library IPFSConvert { bytes constant private CODE_STRING = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bytes constant private CIDV0HEAD = "\x00\x04\x28\x0b\x12\x17\x09\x28\x31\x00\x12\x04\x28\x20\x25\x25\x22\x31\x1b\x1d\x39\x29\x09\x26\x1b\x29\x0b\x02\x0a\x18\x25\x22\x24\x1b\x39\x2c\x1d\x39\x07\x06\x29\x25\x13\x15\x2c\x17"; /** * @dev This function converts an 256 bits hash value into IPFS CIDv0 hash string. * @param _cidv0 256 bits hash value (not including the 0x12 0x20 signature) * @return IPFS CIDv0 hash string (Qm...) */ function cidv0FromBytes32(bytes32 _cidv0) public pure returns (string memory) { unchecked { // convert to base58 bytes memory result = new bytes(46); // 46 is the longest possible base58 result from CIDv0 uint256 resultLen = 45; uint256 number = uint256(_cidv0); while(number > 0) { uint256 rem = number % 58; result[resultLen] = bytes1(uint8(rem)); resultLen--; number = number / 58; } // add 0x1220 in front of _cidv0 uint256 i; for (i = 0; i < 46; i++) { uint8 r = uint8(result[45 - i]) + uint8(CIDV0HEAD[i]); if (r >= 58) { result[45 - i] = bytes1(r - 58); result[45 - i - 1] = bytes1(uint8(result[45 - i - 1]) + 1); } else { result[45 - i] = bytes1(r); } } // convert to characters for (i = 0; i < 46; i++) { result[i] = CODE_STRING[uint8(result[i])]; } return string(result); } } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) 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 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)); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: erc721a/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/HightableOG.sol pragma solidity ^0.8.0; error ReachedMaxSupply(); error TransactionExpired(); error ExceedMaxAllowedMintAmount(); error IncorrectSignature(); error InsufficientPayments(); error TokenRevealQueryForNonexistentToken(); error NotRevealer(); error TokenIndexOutOfBounds(); error UnableToWithdrawFund(); /// @title Hightable OG NFT /// @author Teahouse Finance contract HightableOG is ERC721A, Ownable, ReentrancyGuard { using ECDSA for bytes32; address public whitelistSigner; address public revealer; uint256 public price = 5.5 ether; uint256 public maxCollection; string public unrevealURI; mapping(uint256 => bytes32) private tokenBaseURIHash; /// @param _name Name of the NFT /// @param _symbol Symbol of the NFT /// @param _maxCollection Maximum allowed number of tokens constructor( string memory _name, string memory _symbol, uint256 _maxCollection // total supply ) ERC721A(_name, _symbol) { maxCollection = _maxCollection; } /// @notice Set token minting price /// @param _newPrice New price in wei /// @dev Only owner can do this function setPrice(uint256 _newPrice) external onlyOwner { price = _newPrice; } /// @notice Set whitelist minting signer address /// @param _newWhitelistSigner New signer address /// @dev Only owner can do this function setWhitelistSigner(address _newWhitelistSigner) external onlyOwner { whitelistSigner = _newWhitelistSigner; } /// @notice Set revealer address /// @param _newRevealer New revealer address /// @dev Only owner can do this function setRevealer(address _newRevealer) external onlyOwner { revealer = _newRevealer; } /// @notice Set token URI for unrevealed tokens /// @param _newURI New token URI /// @dev Only owner can do this function setUnrevealURI(string calldata _newURI) external onlyOwner { unrevealURI = _newURI; } function isAuthorized(address _sender, uint32 _allowAmount, uint64 _expireTime, bytes memory _signature) private view returns (bool) { bytes32 hashMsg = keccak256(abi.encodePacked(_sender, _allowAmount, _expireTime)); bytes32 ethHashMessage = hashMsg.toEthSignedMessageHash(); return ethHashMessage.recover(_signature) == whitelistSigner; } /// @notice Whitelist minting /// @param _amount Number of tokens to mint /// @param _allowAmount Allowed amount of tokens /// @param _expireTime Expiry time /// @param _signature The signature signed by the signer address /// @dev The caller must obtain a valid signature signed by the signer address from the server /// @dev and pays for the correct price to mint /// @dev The resulting token is sent to the caller's address function mint(uint32 _amount, uint32 _allowAmount, uint64 _expireTime, bytes calldata _signature) external payable { if (totalSupply() + _amount > maxCollection) revert ReachedMaxSupply(); if (block.timestamp > _expireTime) revert TransactionExpired(); if (_numberMinted(msg.sender) + _amount > _allowAmount) revert ExceedMaxAllowedMintAmount(); if (!isAuthorized(msg.sender, _allowAmount, _expireTime, _signature)) revert IncorrectSignature(); uint256 finalPrice = price * _amount; if (msg.value < finalPrice) revert InsufficientPayments(); _safeMint(msg.sender, _amount); } /// @notice Developer minting /// @param _amount Number of tokens to mint /// @param _to Address to send the tokens to /// @dev Only owner can do this function devMint(uint256 _amount, address _to) external onlyOwner { if (totalSupply() + _amount > maxCollection) revert ReachedMaxSupply(); _safeMint(_to, _amount); } /// @notice Reveal the token /// @param _tokenId TokenId to reveal /// @param _tokenBaseURIHash IPFS hash of the metadata for this token /// @dev Only revealer can do this function reveal(uint256 _tokenId, bytes32 _tokenBaseURIHash) public onlyRevealer { tokenBaseURIHash[_tokenId] = _tokenBaseURIHash; } /// @notice Returns token URI of a token /// @param _tokenId Token Id /// @return uri Token URI function tokenURI(uint256 _tokenId) public view virtual override returns (string memory uri) { if (!_exists(_tokenId)) revert URIQueryForNonexistentToken(); if (tokenBaseURIHash[_tokenId] == 0) { return unrevealURI; } else { bytes32 hash = tokenBaseURIHash[_tokenId]; return string(abi.encodePacked("ipfs://", IPFSConvert.cidv0FromBytes32(hash))); } } /// @notice Returns the number of all minted tokens /// @return minted Number of all minted tokens function totalMinted() external view returns (uint256 minted) { return _totalMinted(); } /// @notice Returns the number of all minted tokens from an address /// @param _minter Minter address /// @return minted Number of all minted tokens from the minter function numberMinted(address _minter) external view returns (uint256 minted) { return _numberMinted(_minter); } /// @notice Returns all tokenIds owned by an address /// @param _addr The address /// @param _startId starting tokenId /// @param _endId ending tokenId (inclusive) /// @return tokenIds Array of all tokenIds owned by the address /// @return endTokenId ending tokenId function ownedTokens(address _addr, uint256 _startId, uint256 _endId) external view returns (uint256[] memory tokenIds, uint256 endTokenId) { if (_endId == 0) { _endId = _currentIndex - 1; } if (_startId < _startTokenId() || _endId >= _currentIndex) revert TokenIndexOutOfBounds(); uint256 i; uint256 balance = balanceOf(_addr); if (balance == 0) { return (new uint256[](0), _endId + 1); } if (balance > 256) { balance = 256; } uint256[] memory results = new uint256[](balance); uint256 idx = 0; address owner = ownerOf(_startId); for (i = _startId; i <= _endId; i++) { if (_ownerships[i].addr != address(0)) { owner = _ownerships[i].addr; } if (!_ownerships[i].burned && owner == _addr) { results[idx] = i; idx++; if (idx == balance) { if (balance == balanceOf(_addr)) { return (results, _endId + 1); } else { return (results, i + 1); } } } } uint256[] memory partialResults = new uint256[](idx); for (i = 0; i < idx; i++) { partialResults[i] = results[i]; } return (partialResults, _endId + 1); } /// @notice Withdraw funds in the NFT /// @param _to The address to send the funds to /// @dev Only owner can do this function withdraw(address payable _to) external payable onlyOwner nonReentrant { (bool success, ) = _to.call{value: address(this).balance}(""); if (!success) revert UnableToWithdrawFund(); } function _startTokenId() override internal view virtual returns (uint256) { // the starting token Id return 1; } modifier onlyRevealer { if(msg.sender != revealer) revert NotRevealer(); _; } }
Returns the number of all minted tokens return minted Number of all minted tokens
function totalMinted() external view returns (uint256 minted) { return _totalMinted(); }
2,090,846
pragma solidity ^0.4.24; contract dPonzi { address public manager;//who originally create the contract struct PlayerStruct { uint key; uint food; uint idx; uint gametime; uint flag; } struct RefStruct { address player; uint flag; } struct RefStructAdd { bool flag; string name; } struct PotCntStruct { address[] player; uint last; uint balance; uint keys; uint food; uint gtime; uint gameTime; uint lastRecord; uint entryAmount; mapping(string => PackageStruct) potStruct; } struct IdxStruct { mapping(address => PlayerStruct) playerStruct; } struct PackageStruct { uint entryAmount; } mapping(string => PotCntStruct) potCntInfo; mapping(string => IdxStruct) idxStruct; mapping(string => RefStruct) idxR; mapping(address => RefStructAdd) public idxRadd; constructor() public { manager = msg.sender; potCntInfo['d'].gameTime = now; potCntInfo['7'].gameTime = now; potCntInfo['30'].gameTime = now; potCntInfo['90'].gameTime = now; potCntInfo['180'].gameTime = now; potCntInfo['365'].gameTime = now; potCntInfo['l'].gameTime = now; potCntInfo['r'].gameTime = now; potCntInfo['d'].gtime = now; potCntInfo['7'].gtime = now; potCntInfo['30'].gtime = now; potCntInfo['90'].gtime = now; potCntInfo['180'].gtime = now; potCntInfo['365'].gtime = now; potCntInfo['l'].gtime = now; potCntInfo['r'].gtime = now; potCntInfo['d'].last = now; potCntInfo['7'].last = now; potCntInfo['30'].last = now; potCntInfo['90'].last = now; potCntInfo['180'].last = now; //declare precalculated entry amount to save gas during entry potCntInfo['i'].entryAmount = 10; potCntInfo['d'].entryAmount = 1; potCntInfo['7'].entryAmount = 4; potCntInfo['30'].entryAmount = 8; // pot 90 and pot dividend share the same 15% potCntInfo['90'].entryAmount = 15; potCntInfo['180'].entryAmount = 25; //pot 365 and pot royal share the same 5% potCntInfo['365'].entryAmount = 5; potCntInfo['l'].entryAmount = 2; } function enter(string package, address advisor) public payable { require(msg.value >= 0.01 ether, "0 ether is not allowed"); uint key = 0; uint multiplier = 100000000000000; if(keccak256(abi.encodePacked(package)) == keccak256("BasicK")) { require(msg.value == 0.01 ether, "Invalid Package Amount"); key = 1; } else if (keccak256(abi.encodePacked(package)) == keccak256("PremiumK")){ require(msg.value == 0.1 ether, "Invalid Package Amount"); key = 11; multiplier = multiplier * 10; } else if (keccak256(abi.encodePacked(package)) == keccak256("LuxuryK")){ require(msg.value == 1 ether, "Invalid Package Amount"); key = 120; multiplier = multiplier * 100; addRoyLuxList('l', 'idxLuxury', now, 500); } else if (keccak256(abi.encodePacked(package)) == keccak256("RoyalK")){ require(msg.value == 10 ether, "Invalid Package Amount"); key = 1300; multiplier = multiplier * 1000; addRoyLuxList('r', 'idxRoyal', now, 100); } if (key > 0){ if ( idxRadd[advisor].flag ) { advisor.transfer(potCntInfo['i'].entryAmount * multiplier); } else { potCntInfo['i'].balance += potCntInfo['i'].entryAmount * multiplier; } //Allocation potCntInfo['d'].balance += potCntInfo['d'].entryAmount * multiplier; potCntInfo['7'].balance += potCntInfo['7'].entryAmount * multiplier; potCntInfo['30'].balance += potCntInfo['30'].entryAmount * multiplier; potCntInfo['90'].balance += potCntInfo['90'].entryAmount * multiplier; potCntInfo['180'].balance += potCntInfo['180'].entryAmount * multiplier; potCntInfo['365'].balance += potCntInfo['365'].entryAmount * multiplier; potCntInfo['l'].balance += potCntInfo['l'].entryAmount * multiplier; potCntInfo['r'].balance += potCntInfo['365'].entryAmount * multiplier; //admin amount potCntInfo['i'].balance += potCntInfo['i'].entryAmount * multiplier; potCntInfo['dv'].balance += potCntInfo['90'].entryAmount * multiplier; addPlayerMapping('d', 'idxDaily', key, 30);//30 + 20 addPlayerMapping('7', 'idx7Pot', key, 60); addPlayerMapping('30', 'idx30Pot', key, 90); addPlayerMapping('90', 'idx90Pot', key, 120); addPlayerMapping('180', 'idx180Pot', key, 150); addPlayerMapping('365', 'idx365Pot', key, 0); } } function addPlayerMapping(string x1, string x2, uint key, uint timeAdd ) private{ //if smaller, which means the game is expired. if(potCntInfo[x1].last <= now){ potCntInfo[x1].last = now; } /* potCntInfo[x1].last += (key * timeAdd); */ potCntInfo[x1].last += (key * timeAdd); //Add into Players Mapping if (idxStruct[x2].playerStruct[msg.sender].flag == 0) { potCntInfo[x1].player.push(msg.sender); idxStruct[x2].playerStruct[msg.sender] = PlayerStruct(key, 0, potCntInfo[x1].player.length, potCntInfo[x1].gtime, 1); } else if (idxStruct[x2].playerStruct[msg.sender].gametime != potCntInfo['d'].gtime){ potCntInfo[x1].player.push(msg.sender); idxStruct[x2].playerStruct[msg.sender] = PlayerStruct(key, 0, potCntInfo[x1].player.length, potCntInfo[x1].gtime, 1); } else { idxStruct[x2].playerStruct[msg.sender].key += key; } potCntInfo[x1].keys += key; } function joinboard(string name) public payable { require(msg.value >= 0.01 ether, "0 ether is not allowed"); if (idxR[name].flag == 0 ) { idxR[name] = RefStruct(msg.sender, 1); potCntInfo['i'].balance += msg.value; /* add to address mapping */ idxRadd[msg.sender].name = name; idxRadd[msg.sender].flag = true; } else { revert("Name is not unique"); } } function pickFood(uint pickTime, string x1, string x2, uint num) public restricted { uint i=0; uint j=0; if (potCntInfo[x1].player.length > 0 && potCntInfo[x1].food <= num) {//if pot.player has player and pot has food less than pass in num do { j = potCntInfo[x1].keys < num ? j : random(potCntInfo[x1].player.length, pickTime);//random pick players in pot if (idxStruct[x2].playerStruct[potCntInfo[x1].player[j]].food > 0) {//if potplayer[address] has food > 0, get next potPlayer[address] j++; } else { idxStruct[x2].playerStruct[potCntInfo[x1].player[j]].food = potCntInfo[x1].keys < num ? idxStruct[x2].playerStruct[potCntInfo[x1].player[j]].key : random(idxStruct[x2].playerStruct[potCntInfo[x1].player[j]].key, pickTime); if (potCntInfo[x1].food + idxStruct[x2].playerStruct[potCntInfo[x1].player[j]].food > num) {//if pot.food + potPlayer.food > num idxStruct[x2].playerStruct[potCntInfo[x1].player[j]].food = num-potCntInfo[x1].food; potCntInfo[x1].food = num; break; } else { potCntInfo[x1].food += idxStruct[x2].playerStruct[potCntInfo[x1].player[j]].food; } j++; i++; } if( potCntInfo[x1].keys < num && j == potCntInfo[x1].player.length) {//exit loop when pot.keys less than num break; } if(potCntInfo[x1].food == num) {//exit loop when pot.food less than num break; } } while (i<10); potCntInfo[x1].lastRecord = potCntInfo[x1].keys < num ? (potCntInfo[x1].keys == potCntInfo[x1].food ? 1 : 0) : (potCntInfo[x1].food == num ? 1 : 0); } else { potCntInfo[x1].lastRecord = 1; } } function pickWinner(uint pickTime, bool sendDaily, bool send7Pot, bool send30Pot, bool send90Pot, bool send180Pot, bool send365Pot) public restricted{ //Hit the Daily pot hitPotProcess('d', sendDaily, pickTime); //Hit the 7 day pot hitPotProcess('7', send7Pot, pickTime); //Hit the 30 day pot hitPotProcess('30', send30Pot, pickTime); //Hit the 90 day pot hitPotProcess('90', send90Pot, pickTime); //Hit the 180 day pot hitPotProcess('180', send180Pot, pickTime); //Hit daily pot maturity maturityProcess('d', sendDaily, pickTime, 86400); //Hit 7 pot maturity maturityProcess('7', send7Pot, pickTime, 604800); //Hit 30 pot maturity maturityProcess('30', send30Pot, pickTime, 2592000); //Hit 90 pot maturity maturityProcess('90', send90Pot, pickTime, 7776000); //Hit 180 pot maturity maturityProcess('180', send180Pot, pickTime, 15552000); //Hit 365 pot maturity maturityProcess('365', send365Pot, pickTime, 31536000); //Hit 365 days pot maturity if (potCntInfo['365'].balance > 0 && send365Pot) { if (pickTime - potCntInfo['365'].gameTime >= 31536000) { maturityProcess('l', send365Pot, pickTime, 31536000); maturityProcess('r', send365Pot, pickTime, 31536000); } } } function hitPotProcess(string x1, bool send, uint pickTime) private { if (potCntInfo[x1].balance > 0 && send) { if (pickTime - potCntInfo[x1].last >= 20) { //additional 20 seconds for safe potCntInfo[x1].balance = 0; potCntInfo[x1].food = 0; potCntInfo[x1].keys = 0; delete potCntInfo[x1].player; potCntInfo[x1].gtime = pickTime; } } } function maturityProcess(string x1, bool send, uint pickTime, uint addTime) private { if (potCntInfo[x1].balance > 0 && send) { if (pickTime - potCntInfo[x1].gameTime >= addTime) { potCntInfo[x1].balance = 0; potCntInfo[x1].food = 0; potCntInfo[x1].keys = 0; delete potCntInfo[x1].player; potCntInfo[x1].gameTime = pickTime; potCntInfo[x1].gtime = pickTime; } } } //Start : Util Function modifier restricted() { require(msg.sender == manager, "Only manager is allowed");//must be manager to call this function _; } function random(uint maxNum, uint timestamp) private view returns (uint){ return uint(keccak256(abi.encodePacked(block.difficulty, timestamp, potCntInfo['d'].balance, potCntInfo['7'].balance, potCntInfo['30'].balance, potCntInfo['90'].balance, potCntInfo['180'].balance, potCntInfo['365'].balance))) % maxNum; } function addRoyLuxList(string x1, string x2, uint timestamp, uint num) private { uint pick; if ( potCntInfo[x1].player.length < num) { if (idxStruct[x2].playerStruct[msg.sender].flag == 0 ) { idxStruct[x2].playerStruct[msg.sender] = PlayerStruct(0, 0, potCntInfo[x1].player.length, potCntInfo['365'].gtime, 1); potCntInfo[x1].player.push(msg.sender); } else if (idxStruct[x2].playerStruct[msg.sender].gametime != potCntInfo['365'].gtime ) { idxStruct[x2].playerStruct[msg.sender] = PlayerStruct(0, 0, potCntInfo[x1].player.length, potCntInfo['365'].gtime, 1); potCntInfo[x1].player.push(msg.sender); } } else { if (idxStruct[x2].playerStruct[msg.sender].flag == 0 ) { pick = random(potCntInfo[x1].player.length, timestamp); idxStruct[x2].playerStruct[msg.sender] = PlayerStruct(0, 0, idxStruct[x2].playerStruct[potCntInfo[x1].player[pick]].idx, potCntInfo['365'].gtime, 1); idxStruct[x2].playerStruct[potCntInfo[x1].player[pick]].flag = 0; potCntInfo[x1].player[pick] = msg.sender; } else if (idxStruct[x2].playerStruct[msg.sender].gametime != potCntInfo['365'].gtime ) { pick = random(potCntInfo[x1].player.length, timestamp); idxStruct[x2].playerStruct[msg.sender] = PlayerStruct(0, 0, idxStruct[x2].playerStruct[potCntInfo[x1].player[pick]].idx, potCntInfo['365'].gtime, 1); idxStruct[x2].playerStruct[potCntInfo[x1].player[pick]].flag = 0; potCntInfo[x1].player[pick] = msg.sender; } } } function getPotCnt(string x) public constant returns(uint count, uint pLast, uint pot, uint keystore, uint gtime, uint gameTime, uint food) { return (potCntInfo[x].player.length, potCntInfo[x].last, potCntInfo[x].balance, potCntInfo[x].keys, potCntInfo[x].gtime, potCntInfo[x].gameTime, potCntInfo[x].food); } function getIdx(string x1, string x2, uint p) public constant returns(address p1, uint food, uint gametime, uint flag) { return (potCntInfo[x1].player[p], idxStruct[x2].playerStruct[potCntInfo[x1].player[p]].food, idxStruct[x2].playerStruct[potCntInfo[x1].player[p]].gametime, idxStruct[x2].playerStruct[potCntInfo[x1].player[p]].flag); } function getLast(string x) public constant returns(uint lastRecord) { return potCntInfo[x].lastRecord; } function sendFoods(address[500] p, uint[500] food) public restricted { for(uint k = 0; k < p.length; k++){ if (food[k] == 0) { return; } p[k].transfer(food[k]); } } function sendItDv(string x1) public restricted { msg.sender.transfer(potCntInfo[x1].balance); potCntInfo[x1].balance = 0; } function getReffAdd(string x) public constant returns(address){ if( idxR[x].flag == 1){ return idxR[x].player; }else{ revert("Not found!"); } } function getReffName(address x) public constant returns(string){ if( idxRadd[x].flag){ return idxRadd[x].name; }else{ revert("Not found!"); } } //End : Util Function }
Hit the Daily potHit the 7 day potHit the 30 day potHit the 90 day potHit the 180 day potHit daily pot maturityHit 7 pot maturityHit 30 pot maturityHit 90 pot maturityHit 180 pot maturityHit 365 pot maturityHit 365 days pot maturity
function pickWinner(uint pickTime, bool sendDaily, bool send7Pot, bool send30Pot, bool send90Pot, bool send180Pot, bool send365Pot) public restricted{ hitPotProcess('d', sendDaily, pickTime); hitPotProcess('7', send7Pot, pickTime); hitPotProcess('30', send30Pot, pickTime); hitPotProcess('90', send90Pot, pickTime); hitPotProcess('180', send180Pot, pickTime); maturityProcess('d', sendDaily, pickTime, 86400); maturityProcess('7', send7Pot, pickTime, 604800); maturityProcess('30', send30Pot, pickTime, 2592000); maturityProcess('90', send90Pot, pickTime, 7776000); maturityProcess('180', send180Pot, pickTime, 15552000); maturityProcess('365', send365Pot, pickTime, 31536000); if (potCntInfo['365'].balance > 0 && send365Pot) { if (pickTime - potCntInfo['365'].gameTime >= 31536000) { maturityProcess('l', send365Pot, pickTime, 31536000); maturityProcess('r', send365Pot, pickTime, 31536000); } } if (potCntInfo['365'].balance > 0 && send365Pot) { if (pickTime - potCntInfo['365'].gameTime >= 31536000) { maturityProcess('l', send365Pot, pickTime, 31536000); maturityProcess('r', send365Pot, pickTime, 31536000); } } }
6,462,420
./partial_match/1/0xB56A44Eb3f22569f4ddBafdfa00Ca1A2411A4c0d/sources/ERC721ARandomizedCollectionV2.sol
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 { TokenOwnership memory ownership = _ownershipOf(tokenId); if (!_isApprovedOrOwner(_msgSender(), tokenId, from)) { revert TransferCallerNotOwnerNorApproved(); } _transferWithOwnershipData(ownership, from, to, tokenId); }
15,973,946
// SPDX-License-Identifier: MIT pragma solidity ^0.6.3; import "./tools/ERC721.sol"; import "./tools/SafeMath.sol"; contract RegalAuction is ERC721 { /** * @dev */ struct History { address owned; uint256 price; } /** * @dev A struct for storing the information of NFT's on the platform. * @param _tokenId represents a specific deed * @param _uri text which describes the characteristics of a given deed * @return whether the deed metadata was added to the repository */ struct RegalCollectible { address payable seller; // 0x01wd... uint256 minbid; // 0 string tokenURI; // "https://..." bool sale; // false uint256 startTime; // 0 uint256 endTime; // 0 bool minted; } struct bidding { uint currentHighestBid; address payable highestBidder; } mapping(uint256 => RegalCollectible) public _regalCollectibles; /** * @dev */ address public owner; address [] public minters; /// * added for future use using SafeMath for uint256; //Note: Token is minted after it is sold or after auction ends //variables that are dynamic or change uint256 public _regalIds; // minted uint256 public _collectibleIds; // not minted mapping(uint256=>mapping(address => uint256)) public fundsByBidder; mapping(uint256=>bidding) public bid; //mapping tokenid to bidding //Events event LogBid(address bidder, uint bid, address highestBidder, uint highestBid); event LogWithdrawal(address withdrawer, address withdrawalAccount, uint amount); event LogEnded(); constructor() payable public ERC721("RegalToken", "RGL") { owner = msg.sender; } /** * @dev A function for minting valid collectibles and storing them in our contracts memory. * @param _tokenURI represents a specific collectible's IPFS URI, carrying it's discription. */ function createCollectible(string memory _tokenURI) public { minters.push(msg.sender); uint _id = minters.length; _safeMint(msg.sender, _id); _setTokenURI(_id, _tokenURI); _regalCollectibles[_id] = RegalCollectible(payable(msg.sender), 0, _tokenURI, false, 0, 0, true); emit CollectibleCreated(msg.sender, _id); } /** * @dev * @param _id (uint) represents the id associated to a specific . * @param _minbid (uint256) represents a specific collectible's IPFS URI, carrying it's discription. * @param _end (uint256) represents a specific collectible's IPFS URI, carrying it's discription. * @return _success (bool) is returned on a sucessful invocation. */ function startAuction(uint _id, uint256 _minbid, uint256 _end) public onlyOwner(_id) // validates ownership of the collectible returns (bool _success) { require(_minbid >= 0, "Price cannot be less than 0"); RegalCollectible memory collectible = _regalCollectibles[_id]; string memory _uri = collectible.tokenURI; _regalCollectibles[_id] = RegalCollectible(payable(msg.sender), _minbid, _uri, true, block.timestamp, _end, true); return true; } function placeBid(uint256 id) public payable onlyOnSale(id) onlyNotOwner(id) onlyMinBid(id) returns (bool success) { // reject payments of 0 ETH if (msg.value == 0) revert(); bidding storage collectibleBid = bid[id]; RegalCollectible memory collectible = _regalCollectibles[id]; if (collectible.sale == false) revert(); uint highestBid = collectibleBid.currentHighestBid; uint newBid = fundsByBidder[id][msg.sender] + msg.value; if (newBid <= highestBid) revert(); if (msg.sender == collectibleBid.highestBidder) revert(); fundsByBidder[id][msg.sender] = newBid; collectibleBid.currentHighestBid = newBid; collectibleBid.highestBidder = msg.sender; LogBid(msg.sender, newBid, collectibleBid.highestBidder, collectibleBid.currentHighestBid); return true; } function endAuction(uint256 _id) public payable onlyOwner(_id) onlyOnSale(_id) onlyAfter(_id) returns (bool success) { // the auction's owner should be allowed to withdraw the highestBindingBid RegalCollectible memory collectible = _regalCollectibles[_id]; bidding storage collectibleBid = bid[_id]; safeTransferFrom(msg.sender, collectibleBid.highestBidder, _id); string memory _uri = collectible.tokenURI; _regalCollectibles[_id] = RegalCollectible(payable(collectibleBid.highestBidder), 0, _uri, false, 0, 0, true); if (!msg.sender.send(collectibleBid.currentHighestBid)) revert(); LogEnded(); return true; } function withdraw(uint256 id) public payable onlyNotOwner(id) onlyAfter(id) returns (bool success) { RegalCollectible memory collectible = _regalCollectibles[id]; require(collectible.sale == false); address payable withdrawalAccount; uint withdrawalAmount; bidding storage collectibleBid = bid[id]; if (msg.sender == collectibleBid.highestBidder) { withdrawalAccount = collectibleBid.highestBidder; withdrawalAmount = collectibleBid.currentHighestBid; } else { // anyone who participated but did not win the auction should be allowed to withdraw // the full amount of their funds withdrawalAccount = msg.sender; withdrawalAmount = fundsByBidder[id][withdrawalAccount]; } if (withdrawalAmount == 0) revert(); fundsByBidder[id][withdrawalAccount] -= withdrawalAmount; // send the funds if (!msg.sender.send(withdrawalAmount)) revert(); LogWithdrawal(msg.sender, withdrawalAccount, withdrawalAmount); return true; } function getCollectible(uint256 id) //get art item info public view collectibleExists(id) returns ( uint256, uint256, string memory, uint256 ) { RegalCollectible memory collectible = _regalCollectibles[id]; bidding memory collectibleBid = bid[id]; return (id, collectible.minbid, collectible.tokenURI, collectibleBid.currentHighestBid); } event CollectibleCreated(address, uint256 _id); modifier onlyAfter(uint256 id) { RegalCollectible memory collectible = _regalCollectibles[id]; if (collectible.endTime > now) revert(); _; } modifier onlyOnSale(uint256 id) { RegalCollectible memory collectible = _regalCollectibles[id]; if (collectible.sale != true) revert(); _; } modifier onlyOwner(uint256 id) { RegalCollectible memory collectible = _regalCollectibles[id]; if (msg.sender != collectible.seller) revert(); _; } modifier onlyNotOwner(uint256 id) { RegalCollectible memory collectible = _regalCollectibles[id]; if (msg.sender == collectible.seller) revert(); _; } modifier onlyMinBid(uint256 id) { RegalCollectible memory collectible = _regalCollectibles[id]; if(msg.value < collectible.minbid) revert(); _; } modifier collectibleExists(uint256 id) { RegalCollectible memory collectible = _regalCollectibles[id]; require(collectible.minted == true, "Not Found"); _; } modifier onlyAdmin() { if (msg.sender != owner) revert(); _; } }
the auction's owner should be allowed to withdraw the highestBindingBid
function endAuction(uint256 _id) public payable onlyOwner(_id) onlyOnSale(_id) onlyAfter(_id) returns (bool success) { RegalCollectible memory collectible = _regalCollectibles[_id]; bidding storage collectibleBid = bid[_id]; safeTransferFrom(msg.sender, collectibleBid.highestBidder, _id); string memory _uri = collectible.tokenURI; _regalCollectibles[_id] = RegalCollectible(payable(collectibleBid.highestBidder), 0, _uri, false, 0, 0, true); if (!msg.sender.send(collectibleBid.currentHighestBid)) revert(); LogEnded(); return true; }
5,535,210
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./MemeNumbersRenderer.sol"; library Errors { string constant AlreadyMinted = "already minted"; string constant UnderPriced = "current price is higher than msg.value"; string constant NotForSale = "number is not for sale in this batch"; string constant MustOwnNum = "must own number to operate on it"; string constant NoSelfBurn = "burn numbers must be different"; string constant InvalidOp = "invalid op"; string constant DoesNotExist = "does not exist"; string constant RendererUpgradeDisabled = "renderer upgrade disabled"; } contract MemeNumbers is ERC721, Ownable { uint256 public constant AUCTION_START_PRICE = 5 ether; uint256 public constant AUCTION_DURATION = 1 hours; uint256 public constant BATCH_SIZE = 8; uint256 constant DECAY_RESOLUTION = 1000000000; // 1 gwei uint256 public auctionStarted; uint256[BATCH_SIZE] private forSale; mapping(uint256 => bool) viaBurn; // Numbers that were created via burn /// disableRenderUpgrade is whether we can still upgrade the tokenURI renderer. /// Once it is set it cannot be unset. bool disableRenderUpgrade = false; ITokenRenderer public renderer; /// @notice Emitted when the auction batch is refreshed. event Refresh(); // TODO: Do we want to include any fields? constructor(address _renderer) ERC721("MemeNumbers", "MEMENUM") { renderer = ITokenRenderer(_renderer); _refresh(); } // Internal helpers: function _getEntropy() view internal returns(uint256) { // This is not ideal but it's not practical to do a real source of entropy // like ChainLink with 2 LINK per refresh shuffle. // Borrowed from: https://github.com/1001-digital/erc721-extensions/blob/f5c983bac8989bc5ebf9b34c03f28e438da9a7b3/contracts/RandomlyAssigned.sol#L27 return uint256(keccak256( abi.encodePacked( msg.sender, block.coinbase, block.difficulty, block.gaslimit, block.timestamp, blockhash(block.number)))); } /** * @dev Generate a fresh sequence available for sale based on the current block state. */ function _refresh() internal { auctionStarted = block.timestamp; uint256 entropy = _getEntropy(); // Slice up our 256 bits of entropy into delicious bite-sized numbers. // Eligibility is confirmed during isForSale, getForSale, and mint. // Eligible batches can be smaller than the forSale batch. forSale[0] = (entropy >> 0) & (2 ** 8 - 1); forSale[1] = (entropy >> 5) & (2 ** 10 - 1); forSale[2] = (entropy >> 8) & (2 ** 14 - 1); forSale[3] = (entropy >> 8) & (2 ** 18 - 1); forSale[4] = (entropy >> 13) & (2 ** 24 - 1); forSale[5] = (entropy >> 21) & (2 ** 32 - 1); forSale[6] = (entropy >> 34) & (2 ** 64 - 1); forSale[7] = (entropy >> 55) & (2 ** 86 - 1); emit Refresh(); } // Public views: /// @notice The current price of the dutch auction. Winning bids above this price will return the difference. function currentPrice() view public returns(uint256) { // Linear price reduction from AUCTION_START_PRICE to 0 uint256 endTime = (auctionStarted + AUCTION_DURATION); if (block.timestamp >= endTime) { return 0; } uint256 elapsed = endTime - block.timestamp; return AUCTION_START_PRICE * ((elapsed * DECAY_RESOLUTION) / AUCTION_DURATION) / DECAY_RESOLUTION; } /// @notice Return whether a number is for sale and eligible function isForSale(uint256 num) view public returns (bool) { for (uint256 i=0; i<forSale.length; i++) { if (forSale[i] == num) return !_exists(num); } return false; } /// @notice Eligible numbers for sale. /// @return nums Array of numbers available for sale. function getForSale() view external returns (uint256[] memory nums) { uint256[] memory batch = new uint256[](BATCH_SIZE); uint256 count = 0; for (uint256 i=0; i<forSale.length; i++) { if (_exists(forSale[i])) continue; batch[count] = forSale[i]; count += 1; } // Copy to properly-sized array nums = new uint256[](count); for (uint256 i=0; i<count; i++) { nums[i] = batch[i]; } return nums; } /// @notice Returns whether num was minted by burning, or if it is an original from auction. function isMintedByBurn(uint256 num) view external returns (bool) { return viaBurn[num]; } /** * @notice Apply a mathematical operation on two numbers, returning the * resulting number. Treat this as a partial read-only preview of `burn`. * This preview does *not* account for the mint state of numbers. * @param num1 Number to burn, must own * @param op Operation to burn num1 and num2 with, one of: add, sub, mul, div * @param num2 Number to burn, must own */ function operate(uint256 num1, string calldata op, uint256 num2) public pure returns (uint256) { bytes1 mode = bytes(op)[0]; if (mode == "a") { // Add return num1 + num2; } if (mode == "s") { // Subtact return num1 - num2; } if (mode == "m") { // Multiply return num1 * num2; } if (mode == "d") { // Divide return num1 / num2; } revert(Errors.InvalidOp); } // Main interface: /** * @notice Mint one of the numbers that are currently for sale at the current dutch auction price. * @param to Address to mint the number into. * @param num Number to mint, must be in the current for-sale sequence. * * Emits a {Refresh} event. */ function mint(address to, uint256 num) external payable { uint256 price = currentPrice(); require(price <= msg.value, Errors.UnderPriced); require(isForSale(num), Errors.NotForSale); _mint(to, num); _refresh(); if (msg.value > price) { // Refund difference of currentPrice vs msg.value to allow overbidding payable(msg.sender).transfer(msg.value - price); } } /** * @notice Mint all of the eligible numbers for sale, uses more gas than mint but you get more numbers. * @param to Address to mint the numbers into. * * Emits a {Refresh} event. */ function mintAll(address to) external payable { uint256 price = currentPrice(); require(price <= msg.value, Errors.UnderPriced); for (uint256 i=0; i<forSale.length; i++) { if (_exists(forSale[i])) continue; _mint(to, forSale[i]); } _refresh(); if (msg.value > price) { // Refund difference of currentPrice vs msg.value to allow overbidding payable(msg.sender).transfer(msg.value - price); } } /** * @notice Refresh the auction without minting once the auction price is 0. More gas efficient than doing a free mint. * * Emits a {Refresh} event. */ function refresh() external { require(currentPrice() == 0, Errors.UnderPriced); _refresh(); } /** * @notice Burn two numbers together using a mathematical operation, producing * a new number if it is not already taken. No minting fee required. * @param to Address to mint the resulting number into. * @param num1 Number to burn, must own * @param op Operation to burn num1 and num2 with, one of: add, sub, mul, div * @param num2 Number to burn, must own */ function burn(address to, uint256 num1, string calldata op, uint256 num2) external { require(num1 != num2, Errors.NoSelfBurn); require(ownerOf(num1) == _msgSender(), Errors.MustOwnNum); require(ownerOf(num2) == _msgSender(), Errors.MustOwnNum); uint256 num = operate(num1, op, num2); require(!_exists(num), Errors.AlreadyMinted); _mint(to, num); viaBurn[num] = true; _burn(num1); _burn(num2); delete viaBurn[num1]; delete viaBurn[num2]; } // Renderer: function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), Errors.DoesNotExist); return renderer.tokenURI(IMemeNumbers(address(this)), tokenId); } // onlyOwner admin functions: /// @notice Withdraw contract balance. function adminWithdraw(address payable to) external onlyOwner { to.transfer(address(this).balance); } /// @notice Change the tokenURI renderer. /// @param _renderer Address of ITokenRenderer. function adminSetRenderer(address _renderer) external onlyOwner { require(disableRenderUpgrade == false, Errors.RendererUpgradeDisabled); renderer = ITokenRenderer(_renderer); } /// @notice Disable upgrading the renderer. Once it is disabled, it cannot be enabled again. function adminDisableRenderUpgrade() external onlyOwner { disableRenderUpgrade = true; } }
Eligible numbers for sale. return nums Array of numbers available for sale.
function getForSale() view external returns (uint256[] memory nums) { uint256[] memory batch = new uint256[](BATCH_SIZE); uint256 count = 0; for (uint256 i=0; i<forSale.length; i++) { if (_exists(forSale[i])) continue; batch[count] = forSale[i]; count += 1; } for (uint256 i=0; i<count; i++) { nums[i] = batch[i]; } return nums; }
6,405,293
/** * @file * @section DESCRIPTION * * Contract for a Limited Token Crowdsale: at it's core, it's an exchange of tokens. * Uses StandardToken instead of MintTokens. * Provides functionality for tracking how much each supporter helped with, * who has permissiong to buy higher values and uses withdrawal logic for the payment system. * * Wei withdrawal by default is to the wallet provided at construction. * Inherit from this contract and override the payment and pricing functions to deploy a valid contract */ pragma solidity ^0.4.17; import '../token/StandardToken.sol'; import '../math/SafeMath.sol'; /** * @title Limited Token Crowdsale */ contract LimitedTokenCrowdSale { // Use safemath for the .add, .mul used everywhere that deals with tokens/eth using SafeMath for uint256; // The token being sold StandardToken public token; // Supporter structure, which allows us to track // how much the user has bought so far, if he's allowed to buy more // than the max limit for no KYC, or if he has any money frozen /** * Supporter structure, which allows us to track * how much the user has bought so far, if he's allowed to buy more * than the max limit for no KYC, or if he has any money frozen */ struct Supporter { // the current amount this user has left to withdraw uint256 tokenBalance; // the total amount of tokens this user has bought from this contract uint256 tokensBought; // the total amount of Wei that is currently frozen in the system // because the user has not yet provided KYC (know-your-customer, money laundering protection) // (this happens when the user buys more tokens than he is allowed without KYC - so neither the user nor // the owner of the contract can withdraw the Wei/Tokens until approveUserKYC(user) is called by the owner.) uint256 weiFrozen; // if the user has KYC flagged bool hasKYC; } // Mapping with all the campaign supporters mapping(address => Supporter) public supportersMap; // Address where funds are collected address public wallet; // Amount of total wei raised uint256 public weiRaised; // Amount of wei that is currently frozen and cannot be withdrawn by the owner uint256 public weiFrozen; // Amount of total tokens sold uint256 public tokensSold; // Amount of tokens that have already been paid for, but not withdrawn uint256 public tokensToWithdraw; // The minimum amount of tokens a user is allowed to buy uint256 public minTokenTransaction; // The limit of Wei that someone can spend on this contract before needing KYC approval uint256 public weiSaleLimitWithoutKYC; /** * Event for token purchase logging * @param purchaser Who paid for the tokens * @param value Weis paid for purchase * @param amount Amount of tokens purchased * @param price Price user paid for tokens */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 price); /** * Event for user that purchased more than the contract allows * for users with no KYC approval * @param purchaser Who paid for the tokens * @param value Weis paid for purchases * @param amount Amount of tokens purchased */ event KYCPending(address indexed purchaser, uint256 value, uint256 amount); function LimitedTokenCrowdSale(address _tokenAddress, uint256 _minTokenTransaction, uint256 _weiSaleLimitWithoutKYC, address _wallet) public { require(_tokenAddress != address(0)); require(_minTokenTransaction >= 0); require(_weiSaleLimitWithoutKYC != 0); require(_wallet != address(0)); token = StandardToken(_tokenAddress); minTokenTransaction = _minTokenTransaction; weiSaleLimitWithoutKYC = _weiSaleLimitWithoutKYC; wallet = _wallet; } /** * @dev Send all the funds currently in the wallet to * the organization wallet provided at the contract creation. */ function internalWithdrawFunds() internal { require(this.balance > 0); // only withdraw money that is not frozen uint256 available = this.balance.sub(weiFrozen); require(available > 0); wallet.transfer(available); } /** * @dev Approves an User's KYC, unfreezing any Wei/Tokens * to be withdrawn */ function internalApproveUserKYC(address user) internal { Supporter storage sup = supportersMap[user]; weiFrozen = weiFrozen.sub(sup.weiFrozen); sup.weiFrozen = 0; sup.hasKYC = true; } /** * @dev Payment function: explicitly reverts as this class needs to be inherited and * shouldn't receive Wei without handling it */ function () public payable { revert(); } /** * @dev Override to return the token priced used */ function internalGetTokenPrice() internal constant returns (uint256); /** * @dev Saves how much the user bought in tokens for later withdrawal */ function internalBuyToken(uint256 weiAmount, address sender) internal { require(weiAmount != 0); require(sender != address(0)); // give a chance to an inheriting contract to have // its own options for token pricing uint256 price = internalGetTokenPrice(); // calculate token amount to be given to user // (Solidity always truncates on division) uint256 tokens = weiAmount.div(price); // must have more tokens than min transaction.. require(tokens > minTokenTransaction); // ..and the contract must have tokens available to sell require(token.balanceOf(this).sub(tokensToWithdraw) > tokens); // add to the balance of the user, to be paid later Supporter storage sup = supportersMap[sender]; uint256 totalBought = sup.tokensBought.add(tokens); if (!sup.hasKYC && totalBought > weiSaleLimitWithoutKYC) { // money is frozen as user has no KYC, // and bought in total more than is allowed weiFrozen = weiFrozen.add(weiAmount); sup.weiFrozen = sup.weiFrozen.add(weiAmount); KYCPending(sender, weiAmount, tokens); } // add to the total to be withdrawn sup.tokenBalance = sup.tokenBalance.add(tokens); // update the total amount of tokens bought sup.tokensBought = totalBought; // updates the total amount of tokens we have to still withdraw, // this will be subtracted each time an user withdraws tokensToWithdraw = tokensToWithdraw.add(tokens); // update how much Wei we have raised weiRaised = weiAmount.add(weiRaised); // update the total amount of tokens we have sold tokensSold = tokensSold.add(tokens); // send an event for a Token Purchase TokenPurchase(sender, weiAmount, tokens, price); } /** * @dev Returns if an users has KYC approval or not * @return A boolean representing the user's KYC status */ function userHasKYC(address user) public constant returns (bool) { return supportersMap[user].hasKYC; } /** * @dev Returns the total amount an user has bought from this contract * @return An uint256 representing the total amount of tokens the user bought */ function userTotalBought(address user) public constant returns (uint256) { return supportersMap[user].tokensBought; } /** * @dev Gets the balance left to withdraw 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 tokenBalanceOf(address _owner) public constant returns (uint256) { return supportersMap[_owner].tokenBalance; } /** * @dev Withdraws the tokens that the sender owns */ function withdrawTokens() public { address to = msg.sender; Supporter storage sup = supportersMap[to]; uint256 balance = sup.tokenBalance; require(balance > 0); require(sup.weiFrozen == 0); if (token.transfer(to, balance)) { // only remove from the amount to withdraw if transfer returned true sup.tokenBalance = 0; tokensToWithdraw = tokensToWithdraw.sub(balance); } else { // transfer failed, balance is stuck revert(); } } }
Returns the total amount an user has bought from this contract return An uint256 representing the total amount of tokens the user bought/
function userTotalBought(address user) public constant returns (uint256) { return supportersMap[user].tokensBought; }
2,474,448
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; /// @title Simple NFT Minter /// @author Gianluca Toffoletto /// @notice Mint NFTs from uploaded images. /// Developed for the final project for the Consensys Academy's 2021 blockchain developer bootcamp /// @dev The contract leverages on OpenZeppelin smart contract libraries import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract SimpleNFT is ERC721, ERC721URIStorage, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; /// @dev this role is not needed to use the mint function /// @notice creates a role to identify "patrons" who made a donation (might be used to reward with "patron badges", e.g.) mapping(address => bool) public patronRole; /// @notice a getter function to check if an account is a patron, not currently used /// @param _account the account to query function getPatronRole(address _account) public view returns (bool) { return patronRole[_account]; } modifier minumumDonation() { require(msg.value >= 2000000000, "Donation should be at least 2 gwei."); _; } /// @notice function to donate at least 2 gweis, assigns the "patron" role /// @param _patron the account to add as a patron /// change to donate function Donate(address _patron) public payable minumumDonation { require(_patron != address(0)); patronRole[_patron] = true; } /// @dev constructor for the SimpleNFT contract constructor() ERC721("SimpleNFT", "SNFT") {} /// @notice Will be concatenated with token IDs to generate the token URIs (from OpenZeppelin ERC721) function _baseURI() internal pure override returns (string memory) { return "ipfs://"; } /// @dev Mints the token to the msg.sender /// @param uri token's URI /// @param to address the NFT is minted to function safeMint(address to, string memory uri) public { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri); } /// @dev Override required by Solidity, recommeded by OpenZeppelin function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } /// @dev Override required by Solidity, recommeded by OpenZeppelin /// @return tokenId function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } /// @dev receive and fallback to allow the contract to receive data/messages receive() external payable { } fallback() external payable { } /// @dev Function to withdraw ether from contract address /// @notice only the owner can withdraw the donations function withdrawDonations() public onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Withdrawal failed"); } }
Mints the token to the msg.sender uri token's URI to address the NFT is minted to
function safeMint(address to, string memory uri) public { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri); }
5,400,307
./partial_match/1/0x07F76e1ec845c5C54b7BA81f16d8Ac0EB31bd48a/sources/MasterChefV2.sol
Swap tokens for eth generate the wukong pair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = wukongRouter.WETH(); _approve(address(this), address(wukongRouter), tokenAmount); wukongRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); }
9,374,155