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 // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol 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"); } /** * @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); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _governance; event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _governance = msgSender; emit GovernanceTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function governance() public view returns (address) { return _governance; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGovernance() { require(_governance == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGovernance(address newOwner) internal virtual onlyGovernance { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit GovernanceTransferred(_governance, newOwner); _governance = newOwner; } } // File: contracts/strategies/StabilizeStrategyXUSDArb.sol pragma solidity =0.6.6; // This is a strategy that takes advantage of arb opportunities for these emerging stablecoins // Users deposit various tokens into the strategy and the strategy will sell into the lowest priced token // Selling will occur via Curve and buying WETH via Sushiswap // Half the profit earned from the sell and interest will be used to buy WETH and split it among the treasury, stakers and executor // It will sell on withdrawals only when a non-contract calls it and certain requirements are met // Anyone can be an executors and profit a percentage on a trade // Gas cost is reimbursed, up to a percentage of the total WETH profit / stipend // Added feature to trade for maximum profit interface StabilizeStakingPool { function notifyRewardAmount(uint256) external; } interface CurvePool { function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate function exchange(int128, int128, uint256, uint256) external; // Exchange tokens } interface TradeRouter { function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory); function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory); function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out } interface AggregatorV3Interface { function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound); } interface SafetyERC20 { function transfer(address recipient, uint256 amount) external; } contract StabilizeStrategyXUSDArb is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; address public treasuryAddress; // Address of the treasury address public stakingAddress; // Address to the STBZ staking pool address public zsTokenAddress; // The address of the controlling zs-Token uint256 constant DIVISION_FACTOR = 100000; uint256 public lastTradeTime; uint256 public lastActionBalance; // Balance before last deposit, withdraw or trade uint256 public percentTradeTrigger = 500; // 0.5% change in value will trigger a trade uint256 public percentSell = 100000; // 100% of the tokens are sold to the cheapest token uint256 public maxAmountSell = 200000; // The maximum amount of tokens that can be sold at once uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor uint256 public percentStakers = 50000; // 50% of non-executor WETH goes to stakers, can be changed, rest goes to treasury uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit uint256 public minTradeSplit = 20000; // If the balance of ETH is less than or equal to this, it trades the entire balance uint256 constant minGain = 1e13; // Minimum amount of eth gain (0.00001) before buying WETH and splitting it bool public safetyMode; // Due to the novelty of the tokens in this pool, one or more of them may decide to fail, // Make sure strategy can still transfer in case that happens // Also locks withdraws/deposits/swaps until new strategy is deployed // Token information // This strategy accepts multiple stablecoins // USDN, MUSD, PAX, DUSD, GUSD, BUSD // All the pools go through USDC to trade between each other struct TokenInfo { IERC20 token; // Reference of token uint256 decimals; // Decimals of token int128 tokenCurveID; // ID on curve int128 usdcCurveID; // ID for intermediary token USDC address curvePoolAddress; bool useUnderlying; bool active; } TokenInfo[] private tokenList; // An array of tokens accepted as deposits // Strategy specific variables address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant SUSHISWAP_ROUTER = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //Address of Sushiswap address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle address constant USDC_ADDRESS = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); constructor( address _treasury, address _staking, address _zsToken ) public { treasuryAddress = _treasury; stakingAddress = _staking; zsTokenAddress = _zsToken; setupWithdrawTokens(); } // Initialization functions function setupWithdrawTokens() internal { // USDN, MUSD, PAX, DUSD, GUSD, BUSD // Start with USDN (by Neutrino) IERC20 _token = IERC20(address(0x674C6Ad92Fd080e4004b2312b45f796a192D27a0)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: address(0x0f9cb53Ebe405d49A0bbdBD291A65Ff571bC83e1), tokenCurveID: 0, usdcCurveID: 2, useUnderlying: true, active: true }) ); // MUSD from MStable _token = IERC20(address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: address(0x8474DdbE98F5aA3179B3B3F5942D724aFcdec9f6), tokenCurveID: 0, usdcCurveID: 2, useUnderlying: true, active: true }) ); // PAX _token = IERC20(address(0x8E870D67F660D95d5be530380D0eC0bd388289E1)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: address(0x06364f10B501e868329afBc005b3492902d6C763), tokenCurveID: 3, usdcCurveID: 1, useUnderlying: true, active: true }) ); // DUSD by DefiDollar _token = IERC20(address(0x5BC25f649fc4e26069dDF4cF4010F9f706c23831)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: address(0x8038C01A0390a8c547446a0b2c18fc9aEFEcc10c), tokenCurveID: 0, usdcCurveID: 2, useUnderlying: true, active: true }) ); // GUSD by Gemini _token = IERC20(address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: address(0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956), tokenCurveID: 0, usdcCurveID: 2, useUnderlying: true, active: true }) ); // BUSD by Binance _token = IERC20(address(0x4Fabb145d64652a948d72533023f6E7A623C7C53)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27), tokenCurveID: 3, usdcCurveID: 1, useUnderlying: true, active: true }) ); // USDP by Unit _token = IERC20(address(0x1456688345527bE1f37E9e627DA0837D6f08C925)); tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: address(0x42d7025938bEc20B69cBae5A77421082407f053A), tokenCurveID: 0, usdcCurveID: 2, useUnderlying: true, active: true }) ); } // Modifier modifier onlyZSToken() { require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token"); _; } // Read functions function rewardTokensCount() external view returns (uint256) { return tokenList.length; } function rewardTokenAddress(uint256 _pos) external view returns (address) { require(_pos < tokenList.length,"No token at that position"); return address(tokenList[_pos].token); } function rewardTokenActive(uint256 _pos) external view returns (bool) { require(_pos < tokenList.length,"No token at that position"); return tokenList[_pos].active; } function balance() public view returns (uint256) { return getNormalizedTotalBalance(address(this)); } function getNormalizedTotalBalance(address _address) public view returns (uint256) { // Get the balance of the atokens+tokens at this address uint256 _balance = 0; uint256 _length = tokenList.length; for(uint256 i = 0; i < _length; i++){ uint256 _bal = tokenList[i].token.balanceOf(_address); _bal = _bal.mul(1e18).div(10**tokenList[i].decimals); _balance = _balance.add(_bal); // This has been normalized to 1e18 decimals } return _balance; } function withdrawTokenReserves() public view returns (address, uint256) { (uint256 targetID, uint256 _bal) = withdrawTokenReservesID(); if(_bal == 0){ return (address(0), _bal); }else{ return (address(tokenList[targetID].token), _bal); } } function withdrawTokenReservesID() internal view returns (uint256, uint256) { // This function will return the address and amount of the token with the highest balance uint256 length = tokenList.length; uint256 targetID = 0; uint256 targetNormBalance = 0; for(uint256 i = 0; i < length; i++){ uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals); if(_normBal > 0){ if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i; } } } if(targetNormBalance > 0){ return (targetID, tokenList[targetID].token.balanceOf(address(this))); }else{ return (0, 0); // No balance } } // Write functions function enter() external onlyZSToken { deposit(false); } function exit() external onlyZSToken { // The ZS token vault is removing all tokens from this strategy if(safetyMode == true){return;} // Skip withdraw if safety mode is on withdraw(_msgSender(),1,1, false); } function deposit(bool nonContract) public onlyZSToken { // Only the ZS token can call the function require(safetyMode == false, "Safety Mode enabled, wait for new strategy deployment"); // No trading is performed on deposit if(nonContract == true){} lastActionBalance = balance(); // This action balance represents pool post stablecoin deposit } function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) { require(balance() > 0, "There are no tokens in this strategy"); require(safetyMode == false, "Safety Mode enabled, wait for new strategy deployment"); if(nonContract == true){ if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){ uint256 buyID = getCheapestCurveToken(); (uint256 sellID, ) = withdrawTokenReservesID(); // These may often be the same tokens checkAndSwapTokens(address(0), sellID, buyID); } } uint256 withdrawAmount = 0; uint256 _balance = balance(); if(_share < _total){ uint256 _myBalance = _balance.mul(_share).div(_total); withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance withdrawAmount = _myBalance; }else{ // We are all shares, transfer all withdrawPerBalance(_depositor, _balance, true); withdrawAmount = _balance; } lastActionBalance = balance(); return withdrawAmount; } // This will withdraw the tokens from the contract based on their balance, from highest balance to lowest function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal { uint256 length = tokenList.length; if(_takeAll == true){ // Send the entire balance for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ tokenList[i].token.safeTransfer(_receiver, _bal); } } return; } bool[4] memory done; uint256 targetID = 0; uint256 targetNormBalance = 0; for(uint256 i = 0; i < length; i++){ targetNormBalance = 0; // Reset the target balance // Find the highest balanced token to withdraw for(uint256 i2 = 0; i2 < length; i2++){ if(done[i2] == false){ uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals); if(targetNormBalance == 0 || _normBal >= targetNormBalance){ targetNormBalance = _normBal; targetID = i2; } } } done[targetID] = true; // Determine the balance left uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals); if(_normalizedBalance <= _withdrawAmount){ // Withdraw the entire balance of this token if(_normalizedBalance > 0){ _withdrawAmount = _withdrawAmount.sub(_normalizedBalance); tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this))); } }else{ // Withdraw a partial amount of this token if(_withdrawAmount > 0){ // Convert the withdraw amount to the token's decimal amount uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18); _withdrawAmount = 0; tokenList[targetID].token.safeTransfer(_receiver, _balance); } break; // Nothing more to withdraw } } } function simulateExchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal view returns (uint256) { CurvePool pool = CurvePool(tokenList[_idIn].curvePoolAddress); if(_idOut == tokenList.length){ // This is special code that says we want WETH out // Simple Sushiswap route // Convert to USDC if(tokenList[_idIn].useUnderlying == true){ _amount = pool.get_dy_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount); }else{ _amount = pool.get_dy(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount); } // Then sell for WETH on Sushiswap TradeRouter router = TradeRouter(SUSHISWAP_ROUTER); address[] memory path = new address[](2); path[0] = USDC_ADDRESS; path[1] = WETH_ADDRESS; uint256[] memory estimates = router.getAmountsOut(_amount, path); _amount = estimates[estimates.length - 1]; return _amount; }else{ // We will use 2 curve pools to find the prices // First get USDC if(tokenList[_idIn].useUnderlying == true){ _amount = pool.get_dy_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount); }else{ _amount = pool.get_dy(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount); } // Then convert to target token pool = CurvePool(tokenList[_idOut].curvePoolAddress); if(tokenList[_idOut].useUnderlying == true){ _amount = pool.get_dy_underlying(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount); }else{ _amount = pool.get_dy(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount); } return _amount; } } function exchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal { CurvePool pool = CurvePool(tokenList[_idIn].curvePoolAddress); tokenList[_idIn].token.safeApprove(address(pool), 0); tokenList[_idIn].token.safeApprove(address(pool), _amount); if(_idOut == tokenList.length){ // This is special code that says we want WETH out // Simple Sushiswap route // Convert to USDC uint256 _before = IERC20(USDC_ADDRESS).balanceOf(address(this)); if(tokenList[_idIn].useUnderlying == true){ pool.exchange_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1); }else{ pool.exchange(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1); } _amount = IERC20(USDC_ADDRESS).balanceOf(address(this)).sub(_before); // Get USDC amount // Then sell for WETH on Sushiswap TradeRouter router = TradeRouter(SUSHISWAP_ROUTER); address[] memory path = new address[](2); path[0] = USDC_ADDRESS; path[1] = WETH_ADDRESS; IERC20(USDC_ADDRESS).safeApprove(SUSHISWAP_ROUTER, 0); IERC20(USDC_ADDRESS).safeApprove(SUSHISWAP_ROUTER, _amount); router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token return; }else{ // We will use 2 curve pools to find the prices // First get USDC uint256 _before = IERC20(USDC_ADDRESS).balanceOf(address(this)); if(tokenList[_idIn].useUnderlying == true){ pool.exchange_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1); }else{ pool.exchange(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1); } _amount = IERC20(USDC_ADDRESS).balanceOf(address(this)).sub(_before); // Get USDC amount // Then convert to target token pool = CurvePool(tokenList[_idOut].curvePoolAddress); IERC20(USDC_ADDRESS).safeApprove(address(pool), 0); IERC20(USDC_ADDRESS).safeApprove(address(pool), _amount); if(tokenList[_idOut].useUnderlying == true){ pool.exchange_underlying(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount, 1); }else{ pool.exchange(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount, 1); } return; } } function getCheapestCurveToken() internal view returns (uint256) { // This will give us the ID of the cheapest token in the pool // We will estimate the return for trading 1000 USDN // The higher the return, the lower the price of the other token uint256 targetID = 0; uint256 usdnAmount = uint256(10).mul(10**tokenList[0].decimals); uint256 highAmount = usdnAmount; uint256 length = tokenList.length; for(uint256 i = 1; i < length; i++){ if(tokenList[i].active == false){ continue; } // Cannot sell an inactive token uint256 estimate = simulateExchange(0, i, usdnAmount); // Normalize the estimate into usdn decimals estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals); if(estimate > highAmount){ // This token is worth less than the usdn highAmount = estimate; targetID = i; } } return targetID; } function getFastGasPrice() internal view returns (uint256) { AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS); ( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer return uint256(intGasPrice); } function estimateSellAtMaximumProfit(uint256 originID, uint256 targetID, uint256 _tokenBalance) internal view returns (uint256) { // This will estimate the amount that can be sold for the maximum profit possible // We discover the price then compare it to the actual return // The return must be positive to return a positive amount // Discover the price with near 0 slip uint256 _minAmount = _tokenBalance.mul(percentSell.div(1000)).div(DIVISION_FACTOR); if(_minAmount == 0){ return 0; } // Nothing to sell, can't calculate uint256 _minReturn = _minAmount.mul(10**tokenList[targetID].decimals).div(10**tokenList[originID].decimals); // Convert decimals uint256 _return = simulateExchange(originID, targetID, _minAmount); if(_return <= _minReturn){ return 0; // We are not going to gain from this trade } _return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals uint256 _startPrice = _return.mul(1e18).div(_minAmount); // Now get the price at a higher amount, expected to be lower due to slippage uint256 _bigAmount = _tokenBalance.mul(percentSell).div(DIVISION_FACTOR); _return = simulateExchange(originID, targetID, _bigAmount); _return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals uint256 _endPrice = _return.mul(1e18).div(_bigAmount); if(_endPrice >= _startPrice){ // Really good liquidity return _bigAmount; } // Else calculate amount at max profit uint256 scaleFactor = uint256(1).mul(10**tokenList[originID].decimals); uint256 _targetAmount = _startPrice.sub(1e18).mul(scaleFactor).div(_startPrice.sub(_endPrice).mul(scaleFactor).div(_bigAmount.sub(_minAmount))).div(2); if(_targetAmount > _bigAmount){ // Cannot create an estimate larger than what we want to sell return _bigAmount; } return _targetAmount; } function checkAndSwapTokens(address _executor, uint256 _sellID, uint256 _buyID) internal { if(_sellID == _buyID){return;} require(_sellID < tokenList.length && _buyID < tokenList.length, "Token ID not found"); require(safetyMode == false, "Unable to swap while in safety mode"); require(tokenList[_sellID].active == true && tokenList[_buyID].active == true, "Token IDs not both active"); // Since this is a gas heavy function, we can reduce the gas by asking executors to select the tokens to swap // This will likely be the token that is the highest quantity in the strat lastTradeTime = now; // Now find our target token to sell into // Now sell all the other tokens into this token uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase bool _expectIncrease = false; if(_sellID != _buyID){ uint256 sellBalance = 0; uint256 _tokenBalance = tokenList[_sellID].token.balanceOf(address(this)); uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[_sellID].decimals); if(_tokenBalance <= _minTradeTarget){ // If balance is too small,sell all tokens at once sellBalance = _tokenBalance; }else{ sellBalance = estimateSellAtMaximumProfit(_sellID, _buyID, _tokenBalance); } uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[_sellID].decimals); if(sellBalance > _maxTradeTarget){ sellBalance = _maxTradeTarget; } if(sellBalance > 0){ uint256 minReceiveBalance = sellBalance.mul(10**tokenList[_buyID].decimals).div(10**tokenList[_sellID].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(_sellID, _buyID, sellBalance); if(estimate > minReceiveBalance){ _expectIncrease = true; // We are getting a greater number of tokens, complete the exchange exchange(_sellID, _buyID, sellBalance); } } } uint256 _newBalance = balance(); if(_expectIncrease == true){ // There may be rare scenarios where we don't gain any by calling this function require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens"); } uint256 gain = _newBalance.sub(_totalBalance); IERC20 weth = IERC20(WETH_ADDRESS); uint256 _wethBalance = weth.balanceOf(address(this)); if(gain >= minGain || _wethBalance > 0){ // Minimum gain required to buy WETH is about 0.01 tokens if(gain >= minGain){ // Buy WETH from Sushiswap with tokens uint256 sellBalance = gain.mul(10**tokenList[_buyID].decimals).div(1e18); // Convert to target decimals sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR); if(sellBalance <= tokenList[_buyID].token.balanceOf(address(this))){ // Sell some of our gained token for WETH exchange(_buyID, tokenList.length, sellBalance); _wethBalance = weth.balanceOf(address(this)); } } if(_wethBalance > 0){ // Split the rest between the stakers and such // This is pure profit, figure out allocation // Split the amount sent to the treasury, stakers and executor if one exists if(_executor != address(0)){ // Executors will get a gas reimbursement in WETH and a percent of the remaining uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested if(gasFee > maxGasFee){ gasFee = maxGasFee; // Gas fee cannot be greater than the maximum } uint256 executorAmount = gasFee; if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){ executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point }else{ // Add the executor percent on top of gas fee executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); } if(executorAmount > 0){ weth.safeTransfer(_executor, executorAmount); _wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract } } if(_wethBalance > 0){ uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR); uint256 treasuryAmount = _wethBalance.sub(stakersAmount); if(treasuryAmount > 0){ weth.safeTransfer(treasuryAddress, treasuryAmount); } if(stakersAmount > 0){ if(stakingAddress != address(0)){ weth.safeTransfer(stakingAddress, stakersAmount); StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount); }else{ // No staking pool selected, just send to the treasury weth.safeTransfer(treasuryAddress, stakersAmount); } } } } } } function expectedProfit(bool inWETHForExecutor) external view returns (uint256, uint256, uint256) { // This view will return the expected profit in wei units that a trading activity will have on the pool // It will also return the highest profit token ID to sell for the lowest token that that will be bought for that profit // Now find our target token to sell into uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap uint256 length = tokenList.length; uint256 sellID = 0; uint256 largestGain = 0; // Now sell all the other tokens into this token //uint256 _normalizedGain = 0; for(uint256 i = 0; i < length; i++){ if(i != targetID){ if(tokenList[i].active == false){continue;} // Cannot sell an inactive token uint256 sellBalance = 0; uint256 _tokenBalance = tokenList[i].token.balanceOf(address(this)); uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals); if(_tokenBalance <= _minTradeTarget){ // If balance is too small,sell all tokens at once sellBalance = _tokenBalance; }else{ sellBalance = estimateSellAtMaximumProfit(i, targetID, _tokenBalance); } uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); if(sellBalance > _maxTradeTarget){ sellBalance = _maxTradeTarget; } if(sellBalance > 0){ uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination uint256 estimate = simulateExchange(i, targetID, sellBalance); if(estimate > minReceiveBalance){ uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain //_normalizedGain = _normalizedGain.add(_gain); if(_gain > largestGain){ // We are only selling 1 token for another 1 token largestGain = _gain; sellID = i; } } } } } if(inWETHForExecutor == false){ //return (_normalizedGain, targetID); return (largestGain, sellID, targetID); }else{ // Calculate WETH profit if(largestGain == 0){ return (0, 0, 0); } // Calculate how much WETH the executor would make as profit uint256 estimate = 0; uint256 sellBalance = largestGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR); // Estimate output if(sellBalance > 0){ estimate = simulateExchange(targetID, tokenList.length, sellBalance); } // Now calculate the amount going to the executor uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total return (estimate.mul(maxPercentStipend).div(DIVISION_FACTOR), sellID, targetID); // The executor will get max percent of total }else{ estimate = estimate.sub(gasFee); // Subtract fee from remaining balance return (estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee), sellID, targetID); // Executor amount with fee added } } } function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, uint256 _sellID, uint256 _buyID) external { // Function designed to promote trading with incentive. Users get percentage of WETH from profitable trades require(now.sub(lastTradeTime) >= _minSecSinceLastTrade, "The last trade was too recent"); require(_msgSender() == tx.origin, "Contracts cannot interact with this function"); checkAndSwapTokens(_executor, _sellID, _buyID); } // Governance functions function governanceSwapTokens(uint256 _sellID, uint256 _buyID) external onlyGovernance { // This is function that force trade tokens at anytime. It can only be called by governance checkAndSwapTokens(_msgSender(), _sellID, _buyID); } function activateSafetyMode() external onlyGovernance { require(safetyMode == false, "Safety mode already active"); // This function will attempt to transfer tokens to itself and if that fails it will go into safety mode uint256 length = tokenList.length; for(uint256 i = 0; i < length; i++){ uint256 _bal = tokenList[i].token.balanceOf(address(this)); if(_bal > 0){ try SafetyERC20(address(tokenList[i].token)).transfer(address(this), _bal) {} catch { safetyMode = true; return; } } } } // Timelock variables uint256 private _timelockStart; // The start of the timelock to change governance variables uint256 private _timelockType; // The function that needs to be changed uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours // Reusable timelock variables address private _timelock_address; address private _timelock_address_2; uint256[6] private _timelock_data; modifier timelockConditionsMet(uint256 _type) { require(_timelockType == _type, "Timelock not acquired for this function"); _timelockType = 0; // Reset the type once the timelock is used if(balance() > 0){ // Timelock only applies when balance exists require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met"); } _; } // Change the owner of the token contract // -------------------- function startGovernanceChange(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 1; _timelock_address = _address; } function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) { transferGovernance(_timelock_address); } // -------------------- // Change the treasury address // -------------------- function startChangeTreasury(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 2; _timelock_address = _address; } function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) { treasuryAddress = _timelock_address; } // -------------------- // Change the staking address // -------------------- function startChangeStakingPool(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 3; _timelock_address = _address; } function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) { stakingAddress = _timelock_address; } // -------------------- // Change the zsToken address // -------------------- function startChangeZSToken(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 4; _timelock_address = _address; } function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) { zsTokenAddress = _timelock_address; } // -------------------- // Change the trading conditions used by the strategy // -------------------- function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend, uint256 _maxSell) external onlyGovernance { // Changes a lot of trading parameters in one call require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,"Percent cannot be greater than 100%"); _timelockStart = now; _timelockType = 5; _timelock_data[0] = _pTradeTrigger; _timelock_data[1] = _pSellPercent; _timelock_data[2] = _minSplit; _timelock_data[3] = _maxStipend; _timelock_data[4] = _pMaxStipend; _timelock_data[5] = _maxSell; } function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(5) { percentTradeTrigger = _timelock_data[0]; percentSell = _timelock_data[1]; minTradeSplit = _timelock_data[2]; gasStipend = _timelock_data[3]; maxPercentStipend = _timelock_data[4]; maxAmountSell = _timelock_data[5]; } // -------------------- // Change the strategy allocations between the parties // -------------------- function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance { // Changes strategy allocations in one call require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%"); _timelockStart = now; _timelockType = 6; _timelock_data[0] = _pDepositors; _timelock_data[1] = _pExecutor; _timelock_data[2] = _pStakers; } function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(6) { percentDepositor = _timelock_data[0]; percentExecutor = _timelock_data[1]; percentStakers = _timelock_data[2]; } // -------------------- // Recover trapped tokens // -------------------- function startRecoverStuckTokens(address _token, uint256 _amount) external onlyGovernance { require(safetyMode == true, "Cannot execute this function unless safety mode active"); _timelockStart = now; _timelockType = 7; _timelock_address = _token; _timelock_data[0] = _amount; } function finishRecoverStuckTokens() external onlyGovernance timelockConditionsMet(7) { IERC20(_timelock_address).safeTransfer(governance(), _timelock_data[0]); } // Add a new token to the strategy // -------------------- function startAddNewStableToken(address _tokenAddress, address _curvePool, uint256 _curveID, uint256 _usdcID, uint256 _underlying) external onlyGovernance { _timelockStart = now; _timelockType = 8; _timelock_address = _tokenAddress; _timelock_address_2 = _curvePool; _timelock_data[0] = _curveID; _timelock_data[1] = _usdcID; _timelock_data[2] = _underlying; } function finishAddNewStableToken() external onlyGovernance timelockConditionsMet(8) { IERC20 _token = IERC20(address(_timelock_address)); bool underlying = true; if(_timelock_data[2] == 0){ underlying = false; } tokenList.push( TokenInfo({ token: _token, decimals: _token.decimals(), curvePoolAddress: _timelock_address_2, tokenCurveID: int128(_timelock_data[0]), usdcCurveID: int128(_timelock_data[1]), active: true, useUnderlying: underlying }) ); uint256 id = tokenList.length - 1; // Verify the new token will work simulateExchange(id, 0, uint256(1).mul(10**tokenList[id].decimals)); } // Deactivate a token from trading // -------------------- function startDeactivateToken(uint256 _id) external onlyGovernance { _timelockStart = now; _timelockType = 9; _timelock_data[0] = _id; } function finishDeactivateToken() external onlyGovernance timelockConditionsMet(9) { tokenList[_timelock_data[0]].active = false; } }
Since this is a gas heavy function, we can reduce the gas by asking executors to select the tokens to swap This will likely be the token that is the highest quantity in the strat Now find our target token to sell into Now sell all the other tokens into this token If balance is too small,sell all tokens at once We are getting a greater number of tokens, complete the exchange There may be rare scenarios where we don't gain any by calling this function Minimum gain required to buy WETH is about 0.01 tokens Buy WETH from Sushiswap with tokens Sell some of our gained token for WETH Split the rest between the stakers and such This is pure profit, figure out allocation Split the amount sent to the treasury, stakers and executor if one exists Executors will get a gas reimbursement in WETH and a percent of the remaining Add the executor percent on top of gas fee No staking pool selected, just send to the treasury
function checkAndSwapTokens(address _executor, uint256 _sellID, uint256 _buyID) internal { require(_sellID < tokenList.length && _buyID < tokenList.length, "Token ID not found"); require(safetyMode == false, "Unable to swap while in safety mode"); require(tokenList[_sellID].active == true && tokenList[_buyID].active == true, "Token IDs not both active"); lastTradeTime = now; bool _expectIncrease = false; if(_sellID != _buyID){ uint256 sellBalance = 0; uint256 _tokenBalance = tokenList[_sellID].token.balanceOf(address(this)); uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[_sellID].decimals); if(_tokenBalance <= _minTradeTarget){ sellBalance = _tokenBalance; sellBalance = estimateSellAtMaximumProfit(_sellID, _buyID, _tokenBalance); } uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[_sellID].decimals); if(sellBalance > _maxTradeTarget){ sellBalance = _maxTradeTarget; } if(sellBalance > 0){ uint256 estimate = simulateExchange(_sellID, _buyID, sellBalance); if(estimate > minReceiveBalance){ _expectIncrease = true; exchange(_sellID, _buyID, sellBalance); } } } uint256 _newBalance = balance(); if(_expectIncrease == true){ require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens"); } uint256 gain = _newBalance.sub(_totalBalance); IERC20 weth = IERC20(WETH_ADDRESS); uint256 _wethBalance = weth.balanceOf(address(this)); if(gain >= minGain || _wethBalance > 0){ if(gain >= minGain){ sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR); if(sellBalance <= tokenList[_buyID].token.balanceOf(address(this))){ exchange(_buyID, tokenList.length, sellBalance); _wethBalance = weth.balanceOf(address(this)); } } if(_wethBalance > 0){ if(_executor != address(0)){ if(gasFee > maxGasFee){ } uint256 executorAmount = gasFee; if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){ executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); } if(executorAmount > 0){ weth.safeTransfer(_executor, executorAmount); } } if(_wethBalance > 0){ uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR); uint256 treasuryAmount = _wethBalance.sub(stakersAmount); if(treasuryAmount > 0){ weth.safeTransfer(treasuryAddress, treasuryAmount); } if(stakersAmount > 0){ if(stakingAddress != address(0)){ weth.safeTransfer(stakingAddress, stakersAmount); StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount); weth.safeTransfer(treasuryAddress, stakersAmount); } } } } } }
6,170,904
pragma solidity 0.4.24; /** * CryptoCanvas Terms of Use * * 1. Intro * * CryptoCanvas is a set of collectible artworks (“Canvas”) created by the CryptoCanvas community with proof of ownership stored on the Ethereum blockchain. * * This agreement does a few things. First, it passes copyright ownership of a Canvas from the Canvas Authors to the first Canvas Owner. The first Canvas Owner is then obligated to pass on the copyright ownership along with the Canvas to the next owner, and so on forever, such that each owner of a Canvas is also the copyright owner. Second, it requires each Canvas Owner to allow certain uses of their Canvas image. Third, it limits the rights of Canvas owners to sue The Mindhouse and the prior owners of the Canvas. * * Canvases of CryptoCanvas are not an investment. They are experimental digital art. * * PLEASE READ THESE TERMS CAREFULLY BEFORE USING THE APP, THE SMART CONTRACTS, OR THE SITE. BY USING THE APP, THE SMART CONTRACTS, THE SITE, OR ANY PART OF THEM YOU ARE CONFIRMING THAT YOU UNDERSTAND AND AGREE TO BE BOUND BY ALL OF THESE TERMS. IF YOU ARE ACCEPTING THESE TERMS ON BEHALF OF A COMPANY OR OTHER LEGAL ENTITY, YOU REPRESENT THAT YOU HAVE THE LEGAL AUTHORITY TO ACCEPT THESE TERMS ON THAT ENTITY’S BEHALF, IN WHICH CASE “YOU” WILL MEAN THAT ENTITY. IF YOU DO NOT HAVE SUCH AUTHORITY, OR IF YOU DO NOT ACCEPT ALL OF THESE TERMS, THEN WE ARE UNWILLING TO MAKE THE APP, THE SMART CONTRACTS, OR THE SITE AVAILABLE TO YOU. IF YOU DO NOT AGREE TO THESE TERMS, YOU MAY NOT ACCESS OR USE THE APP, THE SMART CONTRACTS, OR THE SITE. * * 2. Definitions * * “Smart Contract” refers to this smart contract. * * “Canvas” means a collectible artwork created by the CryptoCanvas community with information about the color and author of each pixel of the Canvas, and proof of ownership stored in the Smart Contract. The Canvas is considered finished when all the pixels of the Canvas have their color set. Specifically, the Canvas is considered finished when its “state” field in the Smart Contract equals to STATE_INITIAL_BIDDING or STATE_OWNED constant. * * “Canvas Author” means the person who painted at least one final pixel of the finished Canvas by sending a transaction to the Smart Contract. Specifically, Canvas Author means the person with the private key for at least one address in the “painter” field of the “pixels” field of the applicable Canvas in the Smart Contract. * * “Canvas Owner” means the person that can cryptographically prove ownership of the applicable Canvas. Specifically, Canvas Owner means the person with the private key for the address in the “owner” field of the applicable Canvas in the Smart Contract. The person is the Canvas Owner only after the Initial Bidding phase is finished, that is when the field “state” of the applicable Canvas equals to the STATE_OWNED constant. * * “Initial Bidding” means the state of the Canvas when each of its pixels has been set by Canvas Authors but it does not have the Canvas Owner yet. In this phase any user can claim the ownership of the Canvas by sending a transaction to the Smart Contract (a “Bid”). Other users have 48 hours from the time of making the first Bid on the Canvas to submit their own Bids. After that time, the user who sent the highest Bid becomes the sole Canvas Owner of the applicable Canvas. Users who placed Bids with lower amounts are able to withdraw their Bid amount from their Account Balance. * * “Account Balance” means the value stored in the Smart Contract assigned to an address. The Account Balance can be withdrawn by the person with the private key for the applicable address by sending a transaction to the Smart Contract. Account Balance consists of Rewards for painting, Bids from Initial Bidding which have been overbid, cancelled offers to buy a Canvas and profits from selling a Canvas. * * “The Mindhouse”, “we” or “us” is the group of developers who created and published the CryptoCanvas Smart Contract. * * “The App” means collectively the Smart Contract and the website created by The Mindhouse to interact with the Smart Contract. * * 3. Intellectual Property * * A. First Assignment * The Canvas Authors of the applicable Canvas hereby assign all copyright ownership in the Canvas to the Canvas Owner. In exchange for this copyright ownership, the Canvas Owner agrees to the terms below. * * B. Later Assignments * When the Canvas Owner transfers the Canvas to a new owner, the Canvas Owner hereby agrees to assign all copyright ownership in the Canvas to the new owner of the Canvas. In exchange for these rights, the new owner shall agree to become the Canvas Owner, and shall agree to be subject to this Terms of Use. * * C. No Other Assignments. * The Canvas Owner shall not assign or license the copyright except as set forth in the “Later Assignments” section above. * * D. Third Party Permissions. * The Canvas Owner agrees to allow CryptoCanvas fans to make non-commercial Use of images of the Canvas to discuss CryptoCanvas, digital collectibles and related matters. “Use” means to reproduce, display, transmit, and distribute images of the Canvas. This permission excludes the right to print the Canvas onto physical copies (including, for example, shirts and posters). * * 4. Fees and Payment * * A. If you choose to paint, make a bid or trade any Canvas of CryptoCanvas any financial transactions that you engage in will be conducted solely through the Ethereum network via MetaMask. We will have no insight into or control over these payments or transactions, nor do we have the ability to reverse any transactions. With that in mind, we will have no liability to you or to any third party for any claims or damages that may arise as a result of any transactions that you engage in via the App, or using the Smart Contracts, or any other transactions that you conduct via the Ethereum network or MetaMask. * * B. Ethereum requires the payment of a transaction fee (a “Gas Fee”) for every transaction that occurs on the Ethereum network. The Gas Fee funds the network of computers that run the decentralized Ethereum network. This means that you will need to pay a Gas Fee for each transaction that occurs via the App. * * C. In addition to the Gas Fee, each time you sell a Canvas to another user of the App, you authorize us to collect a fee of 10% of the total value of that transaction. That fee consists of: 1) 3.9% of the total value of that transaction (a “Commission”). You acknowledge and agree that the Commission will be transferred to us through the Ethereum network as a part of the payment. 2) 6.1% of the total value of that transaction (a “Reward”). You acknowledge and agree that the Reward will be transferred evenly to all painters of the sold canvas through the Ethereum network as a part of the payment. * * D. If you are the Canvas Author you are eligible to receive a reward for painting a Canvas (a “Reward”). A Reward is distributed in these scenarios: 1) After the Initial Bidding phase is completed. You acknowledge and agree that the Reward for the Canvas Author will be calculated by dividing the value of the winning Bid, decreased by our commission of 3.9% of the total value of the Bid, by the total number of pixels of the Canvas and multiplied by the number of pixels of the Canvas that have been painted by applicable Canvas Author. 2) Each time the Canvas is sold. You acknowledge and agree that the Reward for the Canvas Author will be calculated by dividing 6.1% of the total transaction value by the total number of pixels of the Canvas and multiplied by the number of pixels of the Canvas that have been painted by the applicable Canvas Author. You acknowledge and agree that in order to withdraw the Reward you first need to add the Reward to your Account Balance by sending a transaction to the Smart Contract. * * 5. Disclaimers * * A. YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR ACCESS TO AND USE OF THE APP IS AT YOUR SOLE RISK, AND THAT THE APP IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED. TO THE FULLEST EXTENT PERMISSIBLE PURSUANT TO APPLICABLE LAW, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS MAKE NO EXPRESS WARRANTIES AND HEREBY DISCLAIM ALL IMPLIED WARRANTIES REGARDING THE APP AND ANY PART OF IT (INCLUDING, WITHOUT LIMITATION, THE SITE, ANY SMART CONTRACT, OR ANY EXTERNAL WEBSITES), INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, CORRECTNESS, ACCURACY, OR RELIABILITY. WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS DO NOT REPRESENT OR WARRANT TO YOU THAT: (I) YOUR ACCESS TO OR USE OF THE APP WILL MEET YOUR REQUIREMENTS, (II) YOUR ACCESS TO OR USE OF THE APP WILL BE UNINTERRUPTED, TIMELY, SECURE OR FREE FROM ERROR, (III) USAGE DATA PROVIDED THROUGH THE APP WILL BE ACCURATE, (III) THE APP OR ANY CONTENT, SERVICES, OR FEATURES MADE AVAILABLE ON OR THROUGH THE APP ARE FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR (IV) THAT ANY DATA THAT YOU DISCLOSE WHEN YOU USE THE APP WILL BE SECURE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES IN CONTRACTS WITH CONSUMERS, SO SOME OR ALL OF THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU. * * B. YOU ACCEPT THE INHERENT SECURITY RISKS OF PROVIDING INFORMATION AND DEALING ONLINE OVER THE INTERNET, AND AGREE THAT WE HAVE NO LIABILITY OR RESPONSIBILITY FOR ANY BREACH OF SECURITY UNLESS IT IS DUE TO OUR GROSS NEGLIGENCE. * * C. WE WILL NOT BE RESPONSIBLE OR LIABLE TO YOU FOR ANY LOSSES YOU INCUR AS THE RESULT OF YOUR USE OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO ANY LOSSES, DAMAGES OR CLAIMS ARISING FROM: (A) USER ERROR, SUCH AS FORGOTTEN PASSWORDS OR INCORRECTLY CONSTRUED SMART CONTRACTS OR OTHER TRANSACTIONS; (B) SERVER FAILURE OR DATA LOSS; (C) CORRUPTED WALLET FILES; (D) UNAUTHORIZED ACCESS OR ACTIVITIES BY THIRD PARTIES, INCLUDING BUT NOT LIMITED TO THE USE OF VIRUSES, PHISHING, BRUTEFORCING OR OTHER MEANS OF ATTACK AGAINST THE APP, ETHEREUM NETWORK, OR THE METAMASK ELECTRONIC WALLET. * * D. THE CANVASES OF CRYPTOCANVAS ARE INTANGIBLE DIGITAL ASSETS THAT EXIST ONLY BY VIRTUE OF THE OWNERSHIP RECORD MAINTAINED IN THE ETHEREUM NETWORK. ALL SMART CONTRACTS ARE CONDUCTED AND OCCUR ON THE DECENTRALIZED LEDGER WITHIN THE ETHEREUM PLATFORM. WE HAVE NO CONTROL OVER AND MAKE NO GUARANTEES OR PROMISES WITH RESPECT TO SMART CONTRACTS. * * E. THE MINDHOUSE IS NOT RESPONSIBLE FOR LOSSES DUE TO BLOCKCHAINS OR ANY OTHER FEATURES OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO LATE REPORT BY DEVELOPERS OR REPRESENTATIVES (OR NO REPORT AT ALL) OF ANY ISSUES WITH THE BLOCKCHAIN SUPPORTING THE ETHEREUM NETWORK, INCLUDING FORKS, TECHNICAL NODE ISSUES, OR ANY OTHER ISSUES HAVING FUND LOSSES AS A RESULT. * * 6. Limitation of Liability * YOU UNDERSTAND AND AGREE THAT WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS WILL NOT BE LIABLE TO YOU OR TO ANY THIRD PARTY FOR ANY CONSEQUENTIAL, INCIDENTAL, INDIRECT, EXEMPLARY, SPECIAL, PUNITIVE, OR ENHANCED DAMAGES, OR FOR ANY LOSS OF ACTUAL OR ANTICIPATED PROFITS (REGARDLESS OF HOW THESE ARE CLASSIFIED AS DAMAGES), WHETHER ARISING OUT OF BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, REGARDLESS OF WHETHER SUCH DAMAGE WAS FORESEEABLE AND WHETHER EITHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @dev Contract that is aware of time. Useful for tests - like this * we can mock time. */ contract TimeAware is Ownable { /** * @dev Returns current time. */ function getTime() public view returns (uint) { return now; } } /** * @dev Contract that holds pending withdrawals. Responsible for withdrawals. */ contract Withdrawable { mapping(address => uint) private pendingWithdrawals; event Withdrawal(address indexed receiver, uint amount); event BalanceChanged(address indexed _address, uint oldBalance, uint newBalance); /** * Returns amount of wei that given address is able to withdraw. */ function getPendingWithdrawal(address _address) public view returns (uint) { return pendingWithdrawals[_address]; } /** * Add pending withdrawal for an address. */ function addPendingWithdrawal(address _address, uint _amount) internal { require(_address != 0x0); uint oldBalance = pendingWithdrawals[_address]; pendingWithdrawals[_address] += _amount; emit BalanceChanged(_address, oldBalance, oldBalance + _amount); } /** * Withdraws all pending withdrawals. */ function withdraw() external { uint amount = getPendingWithdrawal(msg.sender); require(amount > 0); pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); emit Withdrawal(msg.sender, amount); emit BalanceChanged(msg.sender, amount, 0); } } /** * @dev This contract takes care of painting on canvases, returning artworks and creating ones. */ contract CanvasFactory is TimeAware, Withdrawable { //@dev It means canvas is not finished yet, and bidding is not possible. uint8 public constant STATE_NOT_FINISHED = 0; //@dev there is ongoing bidding and anybody can bid. If there canvas can have // assigned owner, but it can change if someone will over-bid him. uint8 public constant STATE_INITIAL_BIDDING = 1; //@dev canvas has been sold, and has the owner uint8 public constant STATE_OWNED = 2; uint8 public constant WIDTH = 48; uint8 public constant HEIGHT = 48; uint32 public constant PIXEL_COUNT = 2304; //WIDTH * HEIGHT doesn't work for some reason uint32 public constant MAX_CANVAS_COUNT = 1000; uint8 public constant MAX_ACTIVE_CANVAS = 12; uint8 public constant MAX_CANVAS_NAME_LENGTH = 24; Canvas[] canvases; uint32 public activeCanvasCount = 0; event PixelPainted(uint32 indexed canvasId, uint32 index, uint8 color, address indexed painter); event CanvasFinished(uint32 indexed canvasId); event CanvasCreated(uint indexed canvasId, address indexed bookedFor); event CanvasNameSet(uint indexed canvasId, string name); modifier notFinished(uint32 _canvasId) { require(!isCanvasFinished(_canvasId)); _; } modifier finished(uint32 _canvasId) { require(isCanvasFinished(_canvasId)); _; } modifier validPixelIndex(uint32 _pixelIndex) { require(_pixelIndex < PIXEL_COUNT); _; } /** * @notice Creates new canvas. There can't be more canvases then MAX_CANVAS_COUNT. * There can't be more unfinished canvases than MAX_ACTIVE_CANVAS. */ function createCanvas() external returns (uint canvasId) { return _createCanvasInternal(0x0); } /** * @notice Similar to createCanvas(). Books it for given address. If address is 0x0 everybody will * be allowed to paint on a canvas. */ function createAndBookCanvas(address _bookFor) external onlyOwner returns (uint canvasId) { return _createCanvasInternal(_bookFor); } /** * @notice Changes canvas.bookFor variable. Only for the owner of the contract. */ function bookCanvasFor(uint32 _canvasId, address _bookFor) external onlyOwner { Canvas storage _canvas = _getCanvas(_canvasId); _canvas.bookedFor = _bookFor; } /** * @notice Sets pixel. Given canvas can't be yet finished. */ function setPixel(uint32 _canvasId, uint32 _index, uint8 _color) external { Canvas storage _canvas = _getCanvas(_canvasId); _setPixelInternal(_canvas, _canvasId, _index, _color); _finishCanvasIfNeeded(_canvas, _canvasId); } /** * Set many pixels with one tx. Be careful though - sending a lot of pixels * to set may cause out of gas error. * * Throws when none of the pixels has been set. * */ function setPixels(uint32 _canvasId, uint32[] _indexes, uint8[] _colors) external { require(_indexes.length == _colors.length); Canvas storage _canvas = _getCanvas(_canvasId); bool anySet = false; for (uint32 i = 0; i < _indexes.length; i++) { Pixel storage _pixel = _canvas.pixels[_indexes[i]]; if (_pixel.painter == 0x0) { //only allow when pixel is not set _setPixelInternal(_canvas, _canvasId, _indexes[i], _colors[i]); anySet = true; } } if (!anySet) { //If didn't set any pixels - revert to show that transaction failed revert(); } _finishCanvasIfNeeded(_canvas, _canvasId); } /** * @notice Returns full bitmap for given canvas. */ function getCanvasBitmap(uint32 _canvasId) external view returns (uint8[]) { Canvas storage canvas = _getCanvas(_canvasId); uint8[] memory result = new uint8[](PIXEL_COUNT); for (uint32 i = 0; i < PIXEL_COUNT; i++) { result[i] = canvas.pixels[i].color; } return result; } /** * @notice Returns how many pixels has been already set. */ function getCanvasPaintedPixelsCount(uint32 _canvasId) public view returns (uint32) { return _getCanvas(_canvasId).paintedPixelsCount; } function getPixelCount() external pure returns (uint) { return PIXEL_COUNT; } /** * @notice Returns amount of created canvases. */ function getCanvasCount() public view returns (uint) { return canvases.length; } /** * @notice Returns true if the canvas has been already finished. */ function isCanvasFinished(uint32 _canvasId) public view returns (bool) { return _isCanvasFinished(_getCanvas(_canvasId)); } /** * @notice Returns the author of given pixel. */ function getPixelAuthor(uint32 _canvasId, uint32 _pixelIndex) public view validPixelIndex(_pixelIndex) returns (address) { return _getCanvas(_canvasId).pixels[_pixelIndex].painter; } /** * @notice Returns number of pixels set by given address. */ function getPaintedPixelsCountByAddress(address _address, uint32 _canvasId) public view returns (uint32) { Canvas storage canvas = _getCanvas(_canvasId); return canvas.addressToCount[_address]; } function _isCanvasFinished(Canvas canvas) internal pure returns (bool) { return canvas.paintedPixelsCount == PIXEL_COUNT; } function _getCanvas(uint32 _canvasId) internal view returns (Canvas storage) { require(_canvasId < canvases.length); return canvases[_canvasId]; } function _createCanvasInternal(address _bookedFor) private returns (uint canvasId) { require(canvases.length < MAX_CANVAS_COUNT); require(activeCanvasCount < MAX_ACTIVE_CANVAS); uint id = canvases.push(Canvas(STATE_NOT_FINISHED, 0x0, _bookedFor, "", 0, 0, false)) - 1; emit CanvasCreated(id, _bookedFor); activeCanvasCount++; _onCanvasCreated(id); return id; } function _onCanvasCreated(uint /* _canvasId */) internal {} /** * Sets the pixel. */ function _setPixelInternal(Canvas storage _canvas, uint32 _canvasId, uint32 _index, uint8 _color) private notFinished(_canvasId) validPixelIndex(_index) { require(_color > 0); require(_canvas.bookedFor == 0x0 || _canvas.bookedFor == msg.sender); if (_canvas.pixels[_index].painter != 0x0) { //it means this pixel has been already set! revert(); } _canvas.paintedPixelsCount++; _canvas.addressToCount[msg.sender]++; _canvas.pixels[_index] = Pixel(_color, msg.sender); emit PixelPainted(_canvasId, _index, _color, msg.sender); } /** * Marks canvas as finished if all the pixels has been already set. * Starts initial bidding session. */ function _finishCanvasIfNeeded(Canvas storage _canvas, uint32 _canvasId) private { if (_isCanvasFinished(_canvas)) { activeCanvasCount--; _canvas.state = STATE_INITIAL_BIDDING; emit CanvasFinished(_canvasId); } } struct Pixel { uint8 color; address painter; } struct Canvas { /** * Map of all pixels. */ mapping(uint32 => Pixel) pixels; uint8 state; /** * Owner of canvas. Canvas doesn't have an owner until initial bidding ends. */ address owner; /** * Booked by this address. It means that only that address can draw on the canvas. * 0x0 if everybody can paint on the canvas. */ address bookedFor; string name; /** * Numbers of pixels set. Canvas will be considered finished when all pixels will be set. * Technically it means that setPixelsCount == PIXEL_COUNT */ uint32 paintedPixelsCount; mapping(address => uint32) addressToCount; /** * Initial bidding finish time. */ uint initialBiddingFinishTime; /** * If commission from initial bidding has been paid. */ bool isCommissionPaid; /** * @dev if address has been paid a reward for drawing. */ mapping(address => bool) isAddressPaid; } } /** * @notice Useful methods to manage canvas' state. */ contract CanvasState is CanvasFactory { modifier stateBidding(uint32 _canvasId) { require(getCanvasState(_canvasId) == STATE_INITIAL_BIDDING); _; } modifier stateOwned(uint32 _canvasId) { require(getCanvasState(_canvasId) == STATE_OWNED); _; } /** * Ensures that canvas's saved state is STATE_OWNED. * * Because initial bidding is based on current time, we had to find a way to * trigger saving new canvas state. Every transaction (not a call) that * requires state owned should use it modifier as a last one. * * Thank's to that, we can make sure, that canvas state gets updated. */ modifier forceOwned(uint32 _canvasId) { Canvas storage canvas = _getCanvas(_canvasId); if (canvas.state != STATE_OWNED) { canvas.state = STATE_OWNED; } _; } /** * @notice Returns current canvas state. */ function getCanvasState(uint32 _canvasId) public view returns (uint8) { Canvas storage canvas = _getCanvas(_canvasId); if (canvas.state != STATE_INITIAL_BIDDING) { //if state is set to owned, or not finished //it means it doesn't depend on current time - //we don't have to double check return canvas.state; } //state initial bidding - as that state depends on //current time, we have to double check if initial bidding //hasn't finish yet uint finishTime = canvas.initialBiddingFinishTime; if (finishTime == 0 || finishTime > getTime()) { return STATE_INITIAL_BIDDING; } else { return STATE_OWNED; } } /** * @notice Returns all canvas' id for a given state. */ function getCanvasByState(uint8 _state) external view returns (uint32[]) { uint size; if (_state == STATE_NOT_FINISHED) { size = activeCanvasCount; } else { size = getCanvasCount() - activeCanvasCount; } uint32[] memory result = new uint32[](size); uint currentIndex = 0; for (uint32 i = 0; i < canvases.length; i++) { if (getCanvasState(i) == _state) { result[currentIndex] = i; currentIndex++; } } return _slice(result, 0, currentIndex); } /** * Sets canvas name. Only for the owner of the canvas. Name can be an empty * string which is the same as lack of the name. */ function setCanvasName(uint32 _canvasId, string _name) external stateOwned(_canvasId) forceOwned(_canvasId) { bytes memory _strBytes = bytes(_name); require(_strBytes.length <= MAX_CANVAS_NAME_LENGTH); Canvas storage _canvas = _getCanvas(_canvasId); require(msg.sender == _canvas.owner); _canvas.name = _name; emit CanvasNameSet(_canvasId, _name); } /** * @dev Slices array from start (inclusive) to end (exclusive). * Doesn't modify input array. */ function _slice(uint32[] memory _array, uint _start, uint _end) internal pure returns (uint32[]) { require(_start <= _end); if (_start == 0 && _end == _array.length) { return _array; } uint size = _end - _start; uint32[] memory sliced = new uint32[](size); for (uint i = 0; i < size; i++) { sliced[i] = _array[i + _start]; } return sliced; } } /** * @notice Keeps track of all rewards and commissions. * Commission - fee that we charge for using CryptoCanvas. * Reward - painters cut. */ contract RewardableCanvas is CanvasState { /** * As it's hard to operate on floating numbers, each fee will be calculated like this: * PRICE * COMMISSION / COMMISSION_DIVIDER. It's impossible to keep float number here. * * ufixed COMMISSION = 0.039; may seem useful, but it's not possible to multiply ufixed * uint. */ uint public constant COMMISSION = 39; uint public constant TRADE_REWARD = 61; uint public constant PERCENT_DIVIDER = 1000; event RewardAddedToWithdrawals(uint32 indexed canvasId, address indexed toAddress, uint amount); event CommissionAddedToWithdrawals(uint32 indexed canvasId, uint amount); event FeesUpdated(uint32 indexed canvasId, uint totalCommissions, uint totalReward); mapping(uint => FeeHistory) private canvasToFeeHistory; /** * @notice Adds all unpaid commission to the owner's pending withdrawals. * Ethers to withdraw has to be greater that 0, otherwise transaction * will be rejected. * Can be called only by the owner. */ function addCommissionToPendingWithdrawals(uint32 _canvasId) public onlyOwner stateOwned(_canvasId) forceOwned(_canvasId) { FeeHistory storage _history = _getFeeHistory(_canvasId); uint _toWithdraw = calculateCommissionToWithdraw(_canvasId); uint _lastIndex = _history.commissionCumulative.length - 1; require(_toWithdraw > 0); _history.paidCommissionIndex = _lastIndex; addPendingWithdrawal(owner, _toWithdraw); emit CommissionAddedToWithdrawals(_canvasId, _toWithdraw); } /** * @notice Adds all unpaid rewards of the caller to his pending withdrawals. * Ethers to withdraw has to be greater that 0, otherwise transaction * will be rejected. */ function addRewardToPendingWithdrawals(uint32 _canvasId) public stateOwned(_canvasId) forceOwned(_canvasId) { FeeHistory storage _history = _getFeeHistory(_canvasId); uint _toWithdraw; (_toWithdraw,) = calculateRewardToWithdraw(_canvasId, msg.sender); uint _lastIndex = _history.rewardsCumulative.length - 1; require(_toWithdraw > 0); _history.addressToPaidRewardIndex[msg.sender] = _lastIndex; addPendingWithdrawal(msg.sender, _toWithdraw); emit RewardAddedToWithdrawals(_canvasId, msg.sender, _toWithdraw); } /** * @notice Calculates how much of commission there is to be paid. */ function calculateCommissionToWithdraw(uint32 _canvasId) public view stateOwned(_canvasId) returns (uint) { FeeHistory storage _history = _getFeeHistory(_canvasId); uint _lastIndex = _history.commissionCumulative.length - 1; uint _lastPaidIndex = _history.paidCommissionIndex; if (_lastIndex < 0) { //means that FeeHistory hasn't been created yet return 0; } uint _commissionSum = _history.commissionCumulative[_lastIndex]; uint _lastWithdrawn = _history.commissionCumulative[_lastPaidIndex]; uint _toWithdraw = _commissionSum - _lastWithdrawn; require(_toWithdraw <= _commissionSum); return _toWithdraw; } /** * @notice Calculates unpaid rewards of a given address. Returns amount to withdraw * and amount of pixels owned. */ function calculateRewardToWithdraw(uint32 _canvasId, address _address) public view stateOwned(_canvasId) returns ( uint reward, uint pixelsOwned ) { FeeHistory storage _history = _getFeeHistory(_canvasId); uint _lastIndex = _history.rewardsCumulative.length - 1; uint _lastPaidIndex = _history.addressToPaidRewardIndex[_address]; uint _pixelsOwned = getPaintedPixelsCountByAddress(_address, _canvasId); if (_lastIndex < 0) { //means that FeeHistory hasn't been created yet return (0, _pixelsOwned); } uint _rewardsSum = _history.rewardsCumulative[_lastIndex]; uint _lastWithdrawn = _history.rewardsCumulative[_lastPaidIndex]; // Our data structure guarantees that _commissionSum is greater or equal to _lastWithdrawn uint _toWithdraw = ((_rewardsSum - _lastWithdrawn) / PIXEL_COUNT) * _pixelsOwned; return (_toWithdraw, _pixelsOwned); } /** * @notice Returns total amount of commission charged for a given canvas. * It is not a commission to be withdrawn! */ function getTotalCommission(uint32 _canvasId) external view returns (uint) { require(_canvasId < canvases.length); FeeHistory storage _history = canvasToFeeHistory[_canvasId]; uint _lastIndex = _history.commissionCumulative.length - 1; if (_lastIndex < 0) { //means that FeeHistory hasn't been created yet return 0; } return _history.commissionCumulative[_lastIndex]; } /** * @notice Returns total amount of commission that has been already * paid (added to pending withdrawals). */ function getCommissionWithdrawn(uint32 _canvasId) external view returns (uint) { require(_canvasId < canvases.length); FeeHistory storage _history = canvasToFeeHistory[_canvasId]; uint _index = _history.paidCommissionIndex; return _history.commissionCumulative[_index]; } /** * @notice Returns all rewards charged for the given canvas. */ function getTotalRewards(uint32 _canvasId) external view returns (uint) { require(_canvasId < canvases.length); FeeHistory storage _history = canvasToFeeHistory[_canvasId]; uint _lastIndex = _history.rewardsCumulative.length - 1; if (_lastIndex < 0) { //means that FeeHistory hasn't been created yet return 0; } return _history.rewardsCumulative[_lastIndex]; } /** * @notice Returns total amount of rewards that has been already * paid (added to pending withdrawals) by a given address. */ function getRewardsWithdrawn(uint32 _canvasId, address _address) external view returns (uint) { require(_canvasId < canvases.length); FeeHistory storage _history = canvasToFeeHistory[_canvasId]; uint _index = _history.addressToPaidRewardIndex[_address]; uint _pixelsOwned = getPaintedPixelsCountByAddress(_address, _canvasId); if (_history.rewardsCumulative.length == 0 || _index == 0) { return 0; } return (_history.rewardsCumulative[_index] / PIXEL_COUNT) * _pixelsOwned; } /** * @notice Calculates how the initial bidding money will be split. * * @return Commission and sum of all painter rewards. */ function splitBid(uint _amount) public pure returns ( uint commission, uint paintersRewards ){ uint _rewardPerPixel = ((_amount - _calculatePercent(_amount, COMMISSION))) / PIXEL_COUNT; // Rewards is divisible by PIXEL_COUNT uint _rewards = _rewardPerPixel * PIXEL_COUNT; return (_amount - _rewards, _rewards); } /** * @notice Calculates how the money from selling canvas will be split. * * @return Commission, sum of painters' rewards and a seller's profit. */ function splitTrade(uint _amount) public pure returns ( uint commission, uint paintersRewards, uint sellerProfit ){ uint _commission = _calculatePercent(_amount, COMMISSION); // We make sure that painters reward is divisible by PIXEL_COUNT. // It is important to split reward across all the painters equally. uint _rewardPerPixel = _calculatePercent(_amount, TRADE_REWARD) / PIXEL_COUNT; uint _paintersReward = _rewardPerPixel * PIXEL_COUNT; uint _sellerProfit = _amount - _commission - _paintersReward; //check for the underflow require(_sellerProfit < _amount); return (_commission, _paintersReward, _sellerProfit); } /** * @notice Adds a bid to fee history. Doesn't perform any checks if the bid is valid! * @return Returns how the bid was split. Same value as _splitBid function. */ function _registerBid(uint32 _canvasId, uint _amount) internal stateBidding(_canvasId) returns ( uint commission, uint paintersRewards ){ uint _commission; uint _rewards; (_commission, _rewards) = splitBid(_amount); FeeHistory storage _history = _getFeeHistory(_canvasId); // We have to save the difference between new bid and a previous one. // Because we save data as cumulative sum, it's enough to save // only the new value. _history.commissionCumulative.push(_commission); _history.rewardsCumulative.push(_rewards); return (_commission, _rewards); } /** * @notice Adds a bid to fee history. Doesn't perform any checks if the bid is valid! * @return Returns how the trade ethers were split. Same value as splitTrade function. */ function _registerTrade(uint32 _canvasId, uint _amount) internal stateOwned(_canvasId) forceOwned(_canvasId) returns ( uint commission, uint paintersRewards, uint sellerProfit ){ uint _commission; uint _rewards; uint _sellerProfit; (_commission, _rewards, _sellerProfit) = splitTrade(_amount); FeeHistory storage _history = _getFeeHistory(_canvasId); _pushCumulative(_history.commissionCumulative, _commission); _pushCumulative(_history.rewardsCumulative, _rewards); return (_commission, _rewards, _sellerProfit); } function _onCanvasCreated(uint _canvasId) internal { //we create a fee entrance on the moment canvas is created canvasToFeeHistory[_canvasId] = FeeHistory(new uint[](1), new uint[](1), 0); } /** * @notice Gets a fee history of a canvas. */ function _getFeeHistory(uint32 _canvasId) private view returns (FeeHistory storage) { require(_canvasId < canvases.length); //fee history entry is created in onCanvasCreated() method. FeeHistory storage _history = canvasToFeeHistory[_canvasId]; return _history; } function _pushCumulative(uint[] storage _array, uint _value) private returns (uint) { uint _lastValue = _array[_array.length - 1]; uint _newValue = _lastValue + _value; //overflow protection require(_newValue >= _lastValue); return _array.push(_newValue); } /** * @param _percent - percent value mapped to scale [0-1000] */ function _calculatePercent(uint _amount, uint _percent) private pure returns (uint) { return (_amount * _percent) / PERCENT_DIVIDER; } struct FeeHistory { /** * @notice Cumulative sum of all charged commissions. */ uint[] commissionCumulative; /** * @notice Cumulative sum of all charged rewards. */ uint[] rewardsCumulative; /** * Index of last paid commission (from commissionCumulative array) */ uint paidCommissionIndex; /** * Mapping showing what rewards has been already paid. */ mapping(address => uint) addressToPaidRewardIndex; } } /** * @dev This contract takes care of initial bidding. */ contract BiddableCanvas is RewardableCanvas { uint public constant BIDDING_DURATION = 48 hours; mapping(uint32 => Bid) bids; mapping(address => uint32) addressToCount; uint public minimumBidAmount = 0.1 ether; event BidPosted(uint32 indexed canvasId, address indexed bidder, uint amount, uint finishTime); /** * Places bid for canvas that is in the state STATE_INITIAL_BIDDING. * If somebody is outbid his pending withdrawals will be to topped up. */ function makeBid(uint32 _canvasId) external payable stateBidding(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); Bid storage oldBid = bids[_canvasId]; if (msg.value < minimumBidAmount || msg.value <= oldBid.amount) { revert(); } if (oldBid.bidder != 0x0 && oldBid.amount > 0) { //return old bidder his money addPendingWithdrawal(oldBid.bidder, oldBid.amount); } uint finishTime = canvas.initialBiddingFinishTime; if (finishTime == 0) { canvas.initialBiddingFinishTime = getTime() + BIDDING_DURATION; } bids[_canvasId] = Bid(msg.sender, msg.value); if (canvas.owner != 0x0) { addressToCount[canvas.owner]--; } canvas.owner = msg.sender; addressToCount[msg.sender]++; _registerBid(_canvasId, msg.value); emit BidPosted(_canvasId, msg.sender, msg.value, canvas.initialBiddingFinishTime); } /** * @notice Returns last bid for canvas. If the initial bidding has been * already finished that will be winning offer. */ function getLastBidForCanvas(uint32 _canvasId) external view returns ( uint32 canvasId, address bidder, uint amount, uint finishTime ) { Bid storage bid = bids[_canvasId]; Canvas storage canvas = _getCanvas(_canvasId); return (_canvasId, bid.bidder, bid.amount, canvas.initialBiddingFinishTime); } /** * @notice Returns number of canvases owned by the given address. */ function balanceOf(address _owner) external view returns (uint) { return addressToCount[_owner]; } /** * @notice Only for the owner of the contract. Sets minimum bid amount. */ function setMinimumBidAmount(uint _amount) external onlyOwner { minimumBidAmount = _amount; } struct Bid { address bidder; uint amount; } } /** * @dev This contract takes trading our artworks. Trading can happen * if artwork has been initially bought. */ contract CanvasMarket is BiddableCanvas { mapping(uint32 => SellOffer) canvasForSale; mapping(uint32 => BuyOffer) buyOffers; event CanvasOfferedForSale(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to); event SellOfferCancelled(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to); event CanvasSold(uint32 indexed canvasId, uint amount, address indexed from, address indexed to); event BuyOfferMade(uint32 indexed canvasId, address indexed buyer, uint amount); event BuyOfferCancelled(uint32 indexed canvasId, address indexed buyer, uint amount); struct SellOffer { bool isForSale; address seller; uint minPrice; address onlySellTo; // specify to sell only to a specific address } struct BuyOffer { bool hasOffer; address buyer; uint amount; } /** * @notice Buy artwork. Artwork has to be put on sale. If buyer has bid before for * that artwork, that bid will be canceled. */ function acceptSellOffer(uint32 _canvasId) external payable stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); SellOffer memory sellOffer = canvasForSale[_canvasId]; require(msg.sender != canvas.owner); //don't sell for the owner require(sellOffer.isForSale); require(msg.value >= sellOffer.minPrice); require(sellOffer.seller == canvas.owner); //seller is no longer owner require(sellOffer.onlySellTo == 0x0 || sellOffer.onlySellTo == msg.sender); //protect from selling to unintended address uint toTransfer; (, ,toTransfer) = _registerTrade(_canvasId, msg.value); addPendingWithdrawal(sellOffer.seller, toTransfer); addressToCount[canvas.owner]--; addressToCount[msg.sender]++; canvas.owner = msg.sender; _cancelSellOfferInternal(_canvasId, false); emit CanvasSold(_canvasId, msg.value, sellOffer.seller, msg.sender); //If the buyer have placed buy offer, refund it BuyOffer memory offer = buyOffers[_canvasId]; if (offer.buyer == msg.sender) { buyOffers[_canvasId] = BuyOffer(false, 0x0, 0); if (offer.amount > 0) { //refund offer addPendingWithdrawal(offer.buyer, offer.amount); } } } /** * @notice Offer canvas for sale for a minimal price. * Anybody can buy it for an amount grater or equal to min price. */ function offerCanvasForSale(uint32 _canvasId, uint _minPrice) external { _offerCanvasForSaleInternal(_canvasId, _minPrice, 0x0); } /** * @notice Offer canvas for sale to a given address. Only that address * is allowed to buy canvas for an amount grater or equal * to minimal price. */ function offerCanvasForSaleToAddress(uint32 _canvasId, uint _minPrice, address _receiver) external { _offerCanvasForSaleInternal(_canvasId, _minPrice, _receiver); } /** * @notice Cancels previously made sell offer. Caller has to be an owner * of the canvas. Function will fail if there is no sell offer * for the canvas. */ function cancelSellOffer(uint32 _canvasId) external { _cancelSellOfferInternal(_canvasId, true); } /** * @notice Places buy offer for the canvas. It cannot be called by the owner of the canvas. * New offer has to be bigger than existing offer. Returns ethers to the previous * bidder, if any. */ function makeBuyOffer(uint32 _canvasId) external payable stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); BuyOffer storage existing = buyOffers[_canvasId]; require(canvas.owner != msg.sender); require(canvas.owner != 0x0); require(msg.value > existing.amount); if (existing.amount > 0) { //refund previous buy offer. addPendingWithdrawal(existing.buyer, existing.amount); } buyOffers[_canvasId] = BuyOffer(true, msg.sender, msg.value); emit BuyOfferMade(_canvasId, msg.sender, msg.value); } /** * @notice Cancels previously made buy offer. Caller has to be an author * of the offer. */ function cancelBuyOffer(uint32 _canvasId) external stateOwned(_canvasId) forceOwned(_canvasId) { BuyOffer memory offer = buyOffers[_canvasId]; require(offer.buyer == msg.sender); buyOffers[_canvasId] = BuyOffer(false, 0x0, 0); if (offer.amount > 0) { //refund offer addPendingWithdrawal(offer.buyer, offer.amount); } emit BuyOfferCancelled(_canvasId, offer.buyer, offer.amount); } /** * @notice Accepts buy offer for the canvas. Caller has to be the owner * of the canvas. You can specify minimal price, which is the * protection against accidental calls. */ function acceptBuyOffer(uint32 _canvasId, uint _minPrice) external stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); require(canvas.owner == msg.sender); BuyOffer memory offer = buyOffers[_canvasId]; require(offer.hasOffer); require(offer.amount > 0); require(offer.buyer != 0x0); require(offer.amount >= _minPrice); uint toTransfer; (, ,toTransfer) = _registerTrade(_canvasId, offer.amount); addressToCount[canvas.owner]--; addressToCount[offer.buyer]++; canvas.owner = offer.buyer; addPendingWithdrawal(msg.sender, toTransfer); buyOffers[_canvasId] = BuyOffer(false, 0x0, 0); canvasForSale[_canvasId] = SellOffer(false, 0x0, 0, 0x0); emit CanvasSold(_canvasId, offer.amount, msg.sender, offer.buyer); } /** * @notice Returns current buy offer for the canvas. */ function getCurrentBuyOffer(uint32 _canvasId) external view returns (bool hasOffer, address buyer, uint amount) { BuyOffer storage offer = buyOffers[_canvasId]; return (offer.hasOffer, offer.buyer, offer.amount); } /** * @notice Returns current sell offer for the canvas. */ function getCurrentSellOffer(uint32 _canvasId) external view returns (bool isForSale, address seller, uint minPrice, address onlySellTo) { SellOffer storage offer = canvasForSale[_canvasId]; return (offer.isForSale, offer.seller, offer.minPrice, offer.onlySellTo); } function _offerCanvasForSaleInternal(uint32 _canvasId, uint _minPrice, address _receiver) private stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); require(canvas.owner == msg.sender); require(_receiver != canvas.owner); canvasForSale[_canvasId] = SellOffer(true, msg.sender, _minPrice, _receiver); emit CanvasOfferedForSale(_canvasId, _minPrice, msg.sender, _receiver); } function _cancelSellOfferInternal(uint32 _canvasId, bool emitEvent) private stateOwned(_canvasId) forceOwned(_canvasId) { Canvas storage canvas = _getCanvas(_canvasId); SellOffer memory oldOffer = canvasForSale[_canvasId]; require(canvas.owner == msg.sender); require(oldOffer.isForSale); //don't allow to cancel if there is no offer canvasForSale[_canvasId] = SellOffer(false, msg.sender, 0, 0x0); if (emitEvent) { emit SellOfferCancelled(_canvasId, oldOffer.minPrice, oldOffer.seller, oldOffer.onlySellTo); } } } contract CryptoArt is CanvasMarket { function getCanvasInfo(uint32 _canvasId) external view returns ( uint32 id, string name, uint32 paintedPixels, uint8 canvasState, uint initialBiddingFinishTime, address owner, address bookedFor ) { Canvas storage canvas = _getCanvas(_canvasId); return (_canvasId, canvas.name, canvas.paintedPixelsCount, getCanvasState(_canvasId), canvas.initialBiddingFinishTime, canvas.owner, canvas.bookedFor); } function getCanvasByOwner(address _owner) external view returns (uint32[]) { uint32[] memory result = new uint32[](canvases.length); uint currentIndex = 0; for (uint32 i = 0; i < canvases.length; i++) { if (getCanvasState(i) == STATE_OWNED) { Canvas storage canvas = _getCanvas(i); if (canvas.owner == _owner) { result[currentIndex] = i; currentIndex++; } } } return _slice(result, 0, currentIndex); } /** * @notice Returns array of canvas's ids. Returned canvases have sell offer. * If includePrivateOffers is true, includes offers that are targeted * only to one specified address. */ function getCanvasesWithSellOffer(bool includePrivateOffers) external view returns (uint32[]) { uint32[] memory result = new uint32[](canvases.length); uint currentIndex = 0; for (uint32 i = 0; i < canvases.length; i++) { SellOffer storage offer = canvasForSale[i]; if (offer.isForSale && (includePrivateOffers || offer.onlySellTo == 0x0)) { result[currentIndex] = i; currentIndex++; } } return _slice(result, 0, currentIndex); } /** * @notice Returns array of all the owners of all of pixels. If some pixel hasn't * been painted yet, 0x0 address will be returned. */ function getCanvasPainters(uint32 _canvasId) external view returns (address[]) { Canvas storage canvas = _getCanvas(_canvasId); address[] memory result = new address[](PIXEL_COUNT); for (uint32 i = 0; i < PIXEL_COUNT; i++) { result[i] = canvas.pixels[i].painter; } return result; } }
Adds a bid to fee history. Doesn't perform any checks if the bid is valid! return Returns how the trade ethers were split. Same value as splitTrade function./
function _registerTrade(uint32 _canvasId, uint _amount) internal stateOwned(_canvasId) forceOwned(_canvasId) returns ( uint commission, uint paintersRewards, uint sellerProfit ){ uint _commission; uint _rewards; uint _sellerProfit; (_commission, _rewards, _sellerProfit) = splitTrade(_amount); FeeHistory storage _history = _getFeeHistory(_canvasId); _pushCumulative(_history.commissionCumulative, _commission); _pushCumulative(_history.rewardsCumulative, _rewards); return (_commission, _rewards, _sellerProfit); }
5,907,396
./partial_match/1/0x12A73E14ef40DbD995baE85377961A1D2F1596be/sources/contracts/SphinxManager.sol
Approve a deployment. Only callable by the owner of this contract. _actionRoot Root of the Merkle tree containing the actions for the deployment. This may be `bytes32(0)` if there are no actions in the deployment. _targetRoot Root of the Merkle tree containing the targets for the deployment. This may be `bytes32(0)` if there are no targets in the deployment. _numInitialActions Number of `DEPLOY_CONTRACT` and `CALL` actions in the deployment. _numTargets Number of targets in the deployment. _configUri URI pointing to the config file for the deployment. _remoteExecution Whether or not to allow remote execution of the deployment./
function approve( bytes32 _actionRoot, bytes32 _targetRoot, uint256 _numInitialActions, uint256 _numSetStorageActions, uint256 _numTargets, string memory _configUri, bool _remoteExecution ) public onlyOwner { if (activeDeploymentId != bytes32(0)) { revert DeploymentInProgress(); } abi.encode( _actionRoot, _targetRoot, _numInitialActions, _numSetStorageActions, _numTargets, _configUri ) ); DeploymentState storage deployment = _deployments[deploymentId]; DeploymentStatus status = deployment.status; if ( status != DeploymentStatus.EMPTY && status != DeploymentStatus.COMPLETED && status != DeploymentStatus.CANCELLED ) { revert DeploymentStateIsNotApprovable(); } activeDeploymentId = deploymentId; deployment.status = DeploymentStatus.APPROVED; deployment.actionRoot = _actionRoot; deployment.targetRoot = _targetRoot; deployment.numInitialActions = _numInitialActions; deployment.numSetStorageActions = _numSetStorageActions; deployment.targets = _numTargets; deployment.remoteExecution = _remoteExecution; deployment.configUri = _configUri; emit SphinxDeploymentApproved( deploymentId, _actionRoot, _targetRoot, _numInitialActions, _numSetStorageActions, _numTargets, _configUri, _remoteExecution, msg.sender ); registry.announceWithData("SphinxDeploymentApproved", abi.encodePacked(msg.sender)); } initial `DEPLOY_CONTRACT` and `CALL` actions have been executed.
9,336,507
./full_match/43113/0x581019416412183f28125896Bf80a7E2e78C49f7/sources/@elkdex/v3-core/contracts/interfaces/pool/IElkDexV3PoolImmutables.sol
Pool state that never changes These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IElkDexV3PoolImmutables { function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function fee() external view returns (uint24); function tickSpacing() external view returns (int24); function maxLiquidityPerTick() external view returns (uint128); pragma solidity >=0.5.0; }
13,145,379
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./DirectLoanBaseMinimal.sol"; import "../../../utils/ContractKeys.sol"; /** * @title DirectLoanFixed * @author NFTfi * @notice Main contract for NFTfi Direct Loans Fixed Type. This contract manages the ability to create NFT-backed * peer-to-peer loans of type Fixed (agreed to be a fixed-repayment loan) where the borrower pays the * maximumRepaymentAmount regardless of whether they repay early or not. * * There are two ways to commence an NFT-backed loan: * * a. The borrower accepts a lender's offer by calling `acceptOffer`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the lender signs an off-chain message, proposing its offer terms. * 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in * the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an * NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the * underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt * (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * b. The lender accepts a borrowe's binding terms by calling `acceptListing`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the borrower signs an off-chain message, proposing its binding terms. * 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is * stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender * receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, * or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation * receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that * transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that * they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim. * * The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that * transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral * back. * * * A loan may end in one of two ways: * - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they * receive their NFT back in the same transaction. * - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call * NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the * principal-plus-interest, which the borrower now keeps. */ contract DirectLoanFixedOffer is DirectLoanBaseMinimal { /* ********** */ /* DATA TYPES */ /* ********** */ bytes32 public constant LOAN_TYPE = bytes32("DIRECT_LOAN_FIXED_OFFER"); /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @dev Sets `hub` and permitted erc20-s * * @param _admin - Initial admin of this contract. * @param _nftfiHub - NFTfiHub address * @param _permittedErc20s - list of permitted ERC20 token contract addresses */ constructor( address _admin, address _nftfiHub, address[] memory _permittedErc20s ) DirectLoanBaseMinimal( _admin, _nftfiHub, ContractKeys.getIdFromStringKey("DIRECT_LOAN_COORDINATOR"), _permittedErc20s ) { // solhint-disable-previous-line no-empty-blocks } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @notice This function is called by the borrower when accepting a lender's offer to begin a loan. * * @param _offer - The offer made by the lender. * @param _signature - The components of the lender's signature. * @param _borrowerSettings - Some extra parameters that the borrower needs to set when accepting an offer. */ function acceptOffer( Offer memory _offer, Signature memory _signature, BorrowerSettings memory _borrowerSettings ) external whenNotPaused nonReentrant { address nftWrapper = _getWrapper(_offer.nftCollateralContract); _loanSanityChecks(_offer, nftWrapper); _loanSanityChecksOffer(_offer); _acceptOffer( LOAN_TYPE, _setupLoanTerms(_offer, nftWrapper), _setupLoanExtras(_borrowerSettings.revenueSharePartner, _borrowerSettings.referralFeeInBasisPoints), _offer, _signature ); } /* ******************* */ /* READ-ONLY FUNCTIONS */ /* ******************* */ /** * @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan * required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * * @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit * of the specified ERC20 currency. */ function getPayoffAmount(uint32 _loanId) external view override returns (uint256) { LoanTerms storage loan = loanIdToLoan[_loanId]; return loan.maximumRepaymentAmount; } /* ****************** */ /* INTERNAL FUNCTIONS */ /* ****************** */ /** * @notice This function is called by the borrower when accepting a lender's offer to begin a loan. * * @param _loanType - The loan type being created. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanExtras - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoanExtras. * @param _offer - The offer made by the lender. * @param _signature - The components of the lender's signature. */ function _acceptOffer( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, Offer memory _offer, Signature memory _signature ) internal { // Check loan nonces. These are different from Ethereum account nonces. // Here, these are uint256 numbers that should uniquely identify // each signature for each user (i.e. each user should only create one // off-chain signature for each nonce, with a nonce being any arbitrary // uint256 value that they have not used yet for an off-chain NFTfi // signature). require(!_nonceHasBeenUsedForUser[_signature.signer][_signature.nonce], "Lender nonce invalid"); _nonceHasBeenUsedForUser[_signature.signer][_signature.nonce] = true; require(NFTfiSigningUtils.isValidLenderSignature(_offer, _signature), "Lender signature is invalid"); address bundle = hub.getContract(ContractKeys.NFTFI_BUNDLER); require(_loanTerms.nftCollateralContract != bundle, "Collateral cannot be bundle"); uint32 loanId = _createLoan(_loanType, _loanTerms, _loanExtras, msg.sender, _signature.signer, _offer.referrer); // Emit an event with all relevant details from this transaction. emit LoanStarted(loanId, msg.sender, _signature.signer, _loanTerms, _loanExtras); } /** * @dev Creates a `LoanTerms` struct using data sent as the lender's `_offer` on `acceptOffer`. * This is needed in order to avoid stack too deep issues. * Since this is a Fixed loan type loanInterestRateForDurationInBasisPoints is ignored. */ function _setupLoanTerms(Offer memory _offer, address _nftWrapper) internal view returns (LoanTerms memory) { return LoanTerms({ loanERC20Denomination: _offer.loanERC20Denomination, loanPrincipalAmount: _offer.loanPrincipalAmount, maximumRepaymentAmount: _offer.maximumRepaymentAmount, nftCollateralContract: _offer.nftCollateralContract, nftCollateralWrapper: _nftWrapper, nftCollateralId: _offer.nftCollateralId, loanStartTime: uint64(block.timestamp), loanDuration: _offer.loanDuration, loanInterestRateForDurationInBasisPoints: uint16(0), loanAdminFeeInBasisPoints: _offer.loanAdminFeeInBasisPoints, borrower: msg.sender }); } /** * @dev Calculates the payoff amount and admin fee * * @param _loanTerms - Struct containing all the loan's parameters */ function _payoffAndFee(LoanTerms memory _loanTerms) internal pure override returns (uint256 adminFee, uint256 payoffAmount) { // Calculate amounts to send to lender and admins uint256 interestDue = _loanTerms.maximumRepaymentAmount - _loanTerms.loanPrincipalAmount; adminFee = LoanChecksAndCalculations.computeAdminFee( interestDue, uint256(_loanTerms.loanAdminFeeInBasisPoints) ); payoffAmount = _loanTerms.maximumRepaymentAmount - adminFee; } /** * @dev Function that performs some validation checks over loan parameters when accepting an offer * */ function _loanSanityChecksOffer(LoanData.Offer memory _offer) internal pure { require( _offer.maximumRepaymentAmount >= _offer.loanPrincipalAmount, "Negative interest rate loans are not allowed." ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "./LoanChecksAndCalculations.sol"; import "./LoanAirdropUtils.sol"; import "../../BaseLoan.sol"; import "../../../utils/NftReceiver.sol"; import "../../../utils/NFTfiSigningUtils.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../interfaces/INftWrapper.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "../../../interfaces/IPermittedNFTs.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title DirectLoanBase * @author NFTfi * @notice Main contract for NFTfi Direct Loans Type. This contract manages the ability to create NFT-backed * peer-to-peer loans. * * There are two ways to commence an NFT-backed loan: * * a. The borrower accepts a lender's offer by calling `acceptOffer`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the lender signs an off-chain message, proposing its offer terms. * 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in * the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an * NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the * underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt * (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * b. The lender accepts a borrowe's binding terms by calling `acceptListing`. * 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their * be1alf. * 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their * behalf. * 3. the borrower signs an off-chain message, proposing its binding terms. * 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is * stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender * receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, * or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation * receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back. * * The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that * transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that * they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim. * * The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that * transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral * back. * * A loan may end in one of two ways: * - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they * receive their NFT back in the same transaction. * - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call * NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the * principal-plus-interest, which the borrower now keeps. * * * If the loan was created as a ProRated type loan (pro-rata interest loan), then the user only pays the principal plus * pro-rata interest if repaid early. * However, if the loan was was created as a Fixed type loan (agreed to be a fixed-repayment loan), then the borrower * pays the maximumRepaymentAmount regardless of whether they repay early or not. * */ abstract contract DirectLoanBaseMinimal is IDirectLoanBase, IPermittedERC20s, BaseLoan, NftReceiver, LoanData { using SafeERC20 for IERC20; /* ******* */ /* STORAGE */ /* ******* */ uint16 public constant HUNDRED_PERCENT = 10000; bytes32 public immutable override LOAN_COORDINATOR; /** * @notice The maximum duration of any loan started for this loan type, measured in seconds. This is both a * sanity-check for borrowers and an upper limit on how long admins will have to support v1 of this contract if they * eventually deprecate it, as well as a check to ensure that the loan duration never exceeds the space alotted for * it in the loan struct. */ uint256 public override maximumLoanDuration = 53 weeks; /** * @notice The percentage of interest earned by lenders on this platform that is taken by the contract admin's as a * fee, measured in basis points (hundreths of a percent). The max allowed value is 10000. */ uint16 public override adminFeeInBasisPoints = 25; /** * @notice A mapping from a loan's identifier to the loan's details, represted by the loan struct. */ mapping(uint32 => LoanTerms) public override loanIdToLoan; mapping(uint32 => LoanExtras) public loanIdToLoanExtras; /** * @notice A mapping tracking whether a loan has either been repaid or liquidated. This prevents an attacker trying * to repay or liquidate the same loan twice. */ mapping(uint32 => bool) public override loanRepaidOrLiquidated; /** * @dev keeps track of tokens being held as loan collateral, so we dont allow these * to be transferred with the aridrop draining functions */ mapping(address => mapping(uint256 => uint256)) private _escrowTokens; /** * @notice A mapping that takes both a user's address and a loan nonce that was first used when signing an off-chain * order and checks whether that nonce has previously either been used for a loan, or has been pre-emptively * cancelled. The nonce referred to here is not the same as an Ethereum account's nonce. We are referring instead to * nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi orders. * * These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. Each * nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the borrower * in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would submit a * user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. */ mapping(address => mapping(uint256 => bool)) internal _nonceHasBeenUsedForUser; /** * @notice A mapping from an ERC20 currency address to whether that currency * is permitted to be used by this contract. */ mapping(address => bool) private erc20Permits; INftfiHub public immutable hub; /* ****** */ /* EVENTS */ /* ****** */ /** * @notice This event is fired whenever the admins change the percent of interest rates earned that they charge as a * fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points. * * @param newAdminFee - The new admin fee measured in basis points. This is a percent of the interest paid upon a * loan's completion that go to the contract admins. */ event AdminFeeUpdated(uint16 newAdminFee); /** * @notice This event is fired whenever the admins change the maximum duration of any loan started for this loan * type. * * @param newMaximumLoanDuration - The new maximum duration. */ event MaximumLoanDurationUpdated(uint256 newMaximumLoanDuration); /** * @notice This event is fired whenever a borrower begins a loan by calling NFTfi.beginLoan(), which can only occur * after both the lender and borrower have approved their ERC721 and ERC20 contracts to use NFTfi, and when they * both have signed off-chain messages that agree on the terms of the loan. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. */ event LoanStarted( uint32 indexed loanId, address indexed borrower, address indexed lender, LoanTerms loanTerms, LoanExtras loanExtras ); /** * @notice This event is fired whenever a borrower successfully repays their loan, paying * principal-plus-interest-minus-fee to the lender in loanERC20Denomination, paying fee to owner in * loanERC20Denomination, and receiving their NFT collateral back. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param amountPaidToLender The amount of ERC20 that the borrower paid to the lender, measured in the smalled * units of loanERC20Denomination. * @param adminFee The amount of interest paid to the contract admins, measured in the smalled units of * loanERC20Denomination and determined by adminFeeInBasisPoints. This amount never exceeds the amount of interest * earned. * @param revenueShare The amount taken from admin fee amount shared with the partner. * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param nftCollateralContract - The ERC721 contract of the NFT collateral * @param loanERC20Denomination - The ERC20 contract of the currency being used as principal/interest for this * loan. */ event LoanRepaid( uint32 indexed loanId, address indexed borrower, address indexed lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 amountPaidToLender, uint256 adminFee, uint256 revenueShare, address revenueSharePartner, address nftCollateralContract, address loanERC20Denomination ); /** * @notice This event is fired whenever a lender liquidates an outstanding loan that is owned to them that has * exceeded its duration. The lender receives the underlying NFT collateral, and the borrower no longer needs to * repay the loan principal-plus-interest. * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721 * token that they received when the loan began. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param loanMaturityDate - The unix time (measured in seconds) that the loan became due and was eligible for * liquidation. * @param loanLiquidationDate - The unix time (measured in seconds) that liquidation occurred. * @param nftCollateralContract - The ERC721 contract of the NFT collateral */ event LoanLiquidated( uint32 indexed loanId, address indexed borrower, address indexed lender, uint256 loanPrincipalAmount, uint256 nftCollateralId, uint256 loanMaturityDate, uint256 loanLiquidationDate, address nftCollateralContract ); /** * @notice This event is fired when some of the terms of a loan are being renegotiated. * * @param loanId - The unique identifier for the loan to be renegotiated * @param newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender for the * renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, uses transfer from, * frontend will have to propmt an erc20 approve for this from the borrower to the lender * @param renegotiationAdminFee renegotiationFee admin portion based on determined by adminFeeInBasisPoints */ event LoanRenegotiated( uint32 indexed loanId, address indexed borrower, address indexed lender, uint32 newLoanDuration, uint256 newMaximumRepaymentAmount, uint256 renegotiationFee, uint256 renegotiationAdminFee ); /** * @notice This event is fired whenever the admin sets a ERC20 permit. * * @param erc20Contract - Address of the ERC20 contract. * @param isPermitted - Signals ERC20 permit. */ event ERC20Permit(address indexed erc20Contract, bool isPermitted); /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @dev Sets `hub` * * @param _admin - Initial admin of this contract. * @param _nftfiHub - NFTfiHub address * @param _loanCoordinatorKey - * @param _permittedErc20s - */ constructor( address _admin, address _nftfiHub, bytes32 _loanCoordinatorKey, address[] memory _permittedErc20s ) BaseLoan(_admin) { hub = INftfiHub(_nftfiHub); LOAN_COORDINATOR = _loanCoordinatorKey; for (uint256 i = 0; i < _permittedErc20s.length; i++) { _setERC20Permit(_permittedErc20s[i], true); } } /* *************** */ /* ADMIN FUNCTIONS */ /* *************** */ /** * @notice This function can be called by admins to change the maximumLoanDuration. Note that they can never change * maximumLoanDuration to be greater than UINT32_MAX, since that's the maximum space alotted for the duration in the * loan struct. * * @param _newMaximumLoanDuration - The new maximum loan duration, measured in seconds. */ function updateMaximumLoanDuration(uint256 _newMaximumLoanDuration) external onlyOwner { require(_newMaximumLoanDuration <= uint256(type(uint32).max), "Loan duration overflow"); maximumLoanDuration = _newMaximumLoanDuration; emit MaximumLoanDurationUpdated(_newMaximumLoanDuration); } /** * @notice This function can be called by admins to change the percent of interest rates earned that they charge as * a fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points. * * @param _newAdminFeeInBasisPoints - The new admin fee measured in basis points. This is a percent of the interest * paid upon a loan's completion that go to the contract admins. */ function updateAdminFee(uint16 _newAdminFeeInBasisPoints) external onlyOwner { require(_newAdminFeeInBasisPoints <= HUNDRED_PERCENT, "basis points > 10000"); adminFeeInBasisPoints = _newAdminFeeInBasisPoints; emit AdminFeeUpdated(_newAdminFeeInBasisPoints); } /** * @notice used by the owner account to be able to drain ERC20 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _receiver - receiver of the token */ function drainERC20Airdrop(address _tokenAddress, address _receiver) external onlyOwner { IERC20 tokenContract = IERC20(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this)); require(amount > 0, "no tokens owned"); tokenContract.safeTransfer(_receiver, amount); } /** * @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes * both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20 - The address of the ERC20 currency whose permit list status changed. * @param _permit - The new status of whether the currency is permitted or not. */ function setERC20Permit(address _erc20, bool _permit) external onlyOwner { _setERC20Permit(_erc20, _permit); } /** * @notice This function can be called by admins to change the permitted status of a batch of ERC20 currency. This * includes both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20s - The addresses of the ERC20 currencies whose permit list status changed. * @param _permits - The new statuses of whether the currency is permitted or not. */ function setERC20Permits(address[] memory _erc20s, bool[] memory _permits) external onlyOwner { require(_erc20s.length == _permits.length, "setERC20Permits function information arity mismatch"); for (uint256 i = 0; i < _erc20s.length; i++) { _setERC20Permit(_erc20s[i], _permits[i]); } } /** * @notice used by the owner account to be able to drain ERC721 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _tokenId - id token to be sent out * @param _receiver - receiver of the token */ function drainERC721Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver ) external onlyOwner { IERC721 tokenContract = IERC721(_tokenAddress); require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral"); require(tokenContract.ownerOf(_tokenId) == address(this), "nft not owned"); tokenContract.safeTransferFrom(address(this), _receiver, _tokenId); } /** * @notice used by the owner account to be able to drain ERC1155 tokens received as airdrops * for the locked collateral NFT-s * @param _tokenAddress - address of the token contract for the token to be sent out * @param _tokenId - id token to be sent out * @param _receiver - receiver of the token */ function drainERC1155Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver ) external onlyOwner { IERC1155 tokenContract = IERC1155(_tokenAddress); uint256 amount = tokenContract.balanceOf(address(this), _tokenId); require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral"); require(amount > 0, "no nfts owned"); tokenContract.safeTransferFrom(address(this), _receiver, _tokenId, amount, ""); } function mintObligationReceipt(uint32 _loanId) external nonReentrant { address borrower = loanIdToLoan[_loanId].borrower; require(msg.sender == borrower, "sender has to be borrower"); IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); loanCoordinator.mintObligationReceipt(_loanId, borrower); delete loanIdToLoan[_loanId].borrower; } /** * @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if * loan was expired but not liquidated. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param _expiry - The date when the renegotiation offer expires * @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _expiry * - address of this contract * - chainId */ function renegotiateLoan( uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, uint256 _lenderNonce, uint256 _expiry, bytes memory _lenderSignature ) external whenNotPaused nonReentrant { _renegotiateLoan( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _lenderNonce, _expiry, _lenderSignature ); } /** * @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has * begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off * early and the loan is pro-rated type, but the complete repayment amount if it is fixed type. * The the borrower (current owner of the obligation note) will get the collaterl NFT back. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the * contract and hold hostage the NFT's that are still within it. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function payBackLoan(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.payBackChecks(_loanId, hub); ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) = _getPartiesAndData(_loanId); _payBackLoan(_loanId, borrower, lender, loan); _resolveLoan(_loanId, borrower, loan, loanCoordinator); // Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of // storage on Ethereum nodes, since we will never access this loan's details again, and the details are still // available through event data. delete loanIdToLoan[_loanId]; delete loanIdToLoanExtras[_loanId]; } /** * @notice This function is called by a lender once a loan has finished its duration and the borrower still has not * repaid. The lender can call this function to seize the underlying NFT collateral, although the lender gives up * all rights to the principal-plus-collateral by doing so. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause * the contract and hold hostage the NFT's that are still within it. * * We intentionally allow anybody to call this function, although only the lender will end up receiving the seized * collateral. We are exploring the possbility of incentivizing users to call this function by using some of the * admin funds. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function liquidateOverdueLoan(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); // Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId. // Depending on how the rest of the code turns out, this check may be unnecessary. require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) = _getPartiesAndData(_loanId); // Ensure that the loan is indeed overdue, since we can only liquidate overdue loans. uint256 loanMaturityDate = uint256(loan.loanStartTime) + uint256(loan.loanDuration); require(block.timestamp > loanMaturityDate, "Loan is not overdue yet"); require(msg.sender == lender, "Only lender can liquidate"); _resolveLoan(_loanId, lender, loan, loanCoordinator); // Emit an event with all relevant details from this transaction. emit LoanLiquidated( _loanId, borrower, lender, loan.loanPrincipalAmount, loan.nftCollateralId, loanMaturityDate, block.timestamp, loan.nftCollateralContract ); // Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of // storage on Ethereum nodes, since we will never access this loan's details again, and the details are still // available through event data. delete loanIdToLoan[_loanId]; delete loanIdToLoanExtras[_loanId]; } /** * @notice this function initiates a flashloan to pull an airdrop from a tartget contract * * @param _loanId - * @param _target - address of the airdropping contract * @param _data - function selector to be called on the airdropping contract * @param _nftAirdrop - address of the used claiming nft in the drop * @param _nftAirdropId - id of the used claiming nft in the drop * @param _is1155 - * @param _nftAirdropAmount - amount in case of 1155 */ function pullAirdrop( uint32 _loanId, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount ) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); LoanTerms memory loan = loanIdToLoan[_loanId]; LoanAirdropUtils.pullAirdrop( _loanId, loan, _target, _data, _nftAirdrop, _nftAirdropId, _is1155, _nftAirdropAmount, hub ); } /** * @notice this function creates a proxy contract wrapping the collateral to be able to catch an expected airdrop * * @param _loanId - */ function wrapCollateral(uint32 _loanId) external nonReentrant { LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub); require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated"); LoanTerms storage loan = loanIdToLoan[_loanId]; _escrowTokens[loan.nftCollateralContract][loan.nftCollateralId] -= 1; (address instance, uint256 receiverId) = LoanAirdropUtils.wrapCollateral(_loanId, loan, hub); _escrowTokens[instance][receiverId] += 1; } /** * @notice This function can be called by either a lender or a borrower to cancel all off-chain orders that they * have signed that contain this nonce. If the off-chain orders were created correctly, there should only be one * off-chain order that contains this nonce at all. * * The nonce referred to here is not the same as an Ethereum account's nonce. We are referring * instead to nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi * orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. * Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the * borrower in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would * submit a user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * * @param _nonce - User nonce */ function cancelLoanCommitmentBeforeLoanHasBegun(uint256 _nonce) external { require(!_nonceHasBeenUsedForUser[msg.sender][_nonce], "Invalid nonce"); _nonceHasBeenUsedForUser[msg.sender][_nonce] = true; } /* ******************* */ /* READ-ONLY FUNCTIONS */ /* ******************* */ /** * @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan * required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * * @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit * of the specified ERC20 currency. */ function getPayoffAmount(uint32 _loanId) external view virtual returns (uint256); /** * @notice This function can be used to view whether a particular nonce for a particular user has already been used, * either from a successful loan or a cancelled off-chain order. * * @param _user - The address of the user. This function works for both lenders and borrowers alike. * @param _nonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are referring * instead to nonces that are used by both the lender and the borrower when they are first signing off-chain * NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain * order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or * the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * * @return A bool representing whether or not this nonce has been used for this user. */ function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view override returns (bool) { return _nonceHasBeenUsedForUser[_user][_nonce]; } /** * @notice This function can be called by anyone to get the permit associated with the erc20 contract. * * @param _erc20 - The address of the erc20 contract. * * @return Returns whether the erc20 is permitted */ function getERC20Permit(address _erc20) public view override returns (bool) { return erc20Permits[_erc20]; } /* ****************** */ /* INTERNAL FUNCTIONS */ /* ****************** */ /** * @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if * loan was expired but not liquidated. IMPORTANT: Frontend will have to propt the caller to do an ERC20 approve for * the fee amount from themselves (borrower/obligation reciept holder) to the lender (promissory note holder) * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender and * the admin for the renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, * uses transfer from, frontend will have to propmt an erc20 approve for this from the borrower to the lender, * admin fee is calculated by the loan's loanAdminFeeInBasisPoints value * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param _expiry - The date when the renegotiation offer expires * @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _expiry * - address of this contract * - chainId */ function _renegotiateLoan( uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, uint256 _lenderNonce, uint256 _expiry, bytes memory _lenderSignature ) internal { LoanTerms storage loan = loanIdToLoan[_loanId]; (address borrower, address lender) = LoanChecksAndCalculations.renegotiationChecks( loan, _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _lenderNonce, hub ); _nonceHasBeenUsedForUser[lender][_lenderNonce] = true; require( NFTfiSigningUtils.isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, Signature({signer: lender, nonce: _lenderNonce, expiry: _expiry, signature: _lenderSignature}) ), "Renegotiation signature is invalid" ); uint256 renegotiationAdminFee; /** * @notice Transfers fee to the lender immediately * @dev implements Checks-Effects-Interactions pattern by modifying state only after * the transfer happened successfully, we also add the nonReentrant modifier to * the pbulic versions */ if (_renegotiationFee > 0) { renegotiationAdminFee = LoanChecksAndCalculations.computeAdminFee( _renegotiationFee, loan.loanAdminFeeInBasisPoints ); // Transfer principal-plus-interest-minus-fees from the caller (always has to be borrower) to lender IERC20(loan.loanERC20Denomination).safeTransferFrom( borrower, lender, _renegotiationFee - renegotiationAdminFee ); // Transfer fees from the caller (always has to be borrower) to admins IERC20(loan.loanERC20Denomination).safeTransferFrom(borrower, owner(), renegotiationAdminFee); } loan.loanDuration = _newLoanDuration; loan.maximumRepaymentAmount = _newMaximumRepaymentAmount; emit LoanRenegotiated( _loanId, borrower, lender, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, renegotiationAdminFee ); } /** * @dev Transfer collateral NFT from borrower to this contract and principal from lender to the borrower and * registers the new loan through the loan coordinator. * * @param _loanType - The type of loan it is being created * @param _loanTerms - Struct containing the loan's settings * @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep * @param _lender - The address of the lender. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. */ function _createLoan( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, address _borrower, address _lender, address _referrer ) internal returns (uint32) { // Transfer collateral from borrower to this contract to be held until // loan completion. _transferNFT(_loanTerms, _borrower, address(this)); return _createLoanNoNftTransfer(_loanType, _loanTerms, _loanExtras, _borrower, _lender, _referrer); } /** * @dev Transfer principal from lender to the borrower and * registers the new loan through the loan coordinator. * * @param _loanType - The type of loan it is being created * @param _loanTerms - Struct containing the loan's settings * @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep * @param _lender - The address of the lender. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. */ function _createLoanNoNftTransfer( bytes32 _loanType, LoanTerms memory _loanTerms, LoanExtras memory _loanExtras, address _borrower, address _lender, address _referrer ) internal returns (uint32 loanId) { _escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] += 1; uint256 referralfee = LoanChecksAndCalculations.computeReferralFee( _loanTerms.loanPrincipalAmount, _loanExtras.referralFeeInBasisPoints, _referrer ); uint256 principalAmount = _loanTerms.loanPrincipalAmount - referralfee; if (referralfee > 0) { // Transfer the referral fee from lender to referrer. IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _referrer, referralfee); } // Transfer principal from lender to borrower. IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _borrower, principalAmount); // Issue an ERC721 promissory note to the lender that gives them the // right to either the principal-plus-interest or the collateral, // and an obligation note to the borrower that gives them the // right to pay back the loan and get the collateral back. IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); loanId = loanCoordinator.registerLoan(_lender, _loanType); // Add the loan to storage before moving collateral/principal to follow // the Checks-Effects-Interactions pattern. loanIdToLoan[loanId] = _loanTerms; loanIdToLoanExtras[loanId] = _loanExtras; return loanId; } /** * @dev Transfers several types of NFTs using a wrapper that knows how to handle each case. * * @param _loanTerms - Struct containing all the loan's parameters * @param _sender - Current owner of the NFT * @param _recipient - Recipient of the transfer */ function _transferNFT( LoanTerms memory _loanTerms, address _sender, address _recipient ) internal { Address.functionDelegateCall( _loanTerms.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loanTerms.nftCollateralWrapper).transferNFT.selector, _sender, _recipient, _loanTerms.nftCollateralContract, _loanTerms.nftCollateralId ), "NFT not successfully transferred" ); } /** * @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has * begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off * early and the loan is pro-rated type, but the complete repayment amount if it is fixed type. * The the borrower (current owner of the obligation note) will get the collaterl NFT back. * * This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the * contract and hold hostage the NFT's that are still within it. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. */ function _payBackLoan( uint32 _loanId, address _borrower, address _lender, LoanTerms memory _loan ) internal { // Fetch loan details from storage, but store them in memory for the sake of saving gas. LoanExtras memory loanExtras = loanIdToLoanExtras[_loanId]; (uint256 adminFee, uint256 payoffAmount) = _payoffAndFee(_loan); // Transfer principal-plus-interest-minus-fees from the caller to lender IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, _lender, payoffAmount); uint256 revenueShare = LoanChecksAndCalculations.computeRevenueShare( adminFee, loanExtras.revenueShareInBasisPoints ); // PermittedPartners contract doesn't allow to set a revenueShareInBasisPoints for address zero so revenuShare // > 0 implies that revenueSharePartner ~= address(0), BUT revenueShare can be zero for a partener when the // adminFee is low if (revenueShare > 0 && loanExtras.revenueSharePartner != address(0)) { adminFee -= revenueShare; // Transfer revenue share from the caller to permitted partner IERC20(_loan.loanERC20Denomination).safeTransferFrom( msg.sender, loanExtras.revenueSharePartner, revenueShare ); } // Transfer fees from the caller to admins IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, owner(), adminFee); // Emit an event with all relevant details from this transaction. emit LoanRepaid( _loanId, _borrower, _lender, _loan.loanPrincipalAmount, _loan.nftCollateralId, payoffAmount, adminFee, revenueShare, loanExtras.revenueSharePartner, // this could be a non address zero even if revenueShare is 0 _loan.nftCollateralContract, _loan.loanERC20Denomination ); } /** * @notice A convenience function with shared functionality between `payBackLoan` and `liquidateOverdueLoan`. * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param _nftReceiver - The receiver of the collateral nft. The borrower when `payBackLoan` or the lender when * `liquidateOverdueLoan`. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanCoordinator - The loan coordinator used when creating the loan. */ function _resolveLoan( uint32 _loanId, address _nftReceiver, LoanTerms memory _loanTerms, IDirectLoanCoordinator _loanCoordinator ) internal { _resolveLoanNoNftTransfer(_loanId, _loanTerms, _loanCoordinator); // Transfer collateral from this contract to the lender, since the lender is seizing collateral for an overdue // loan _transferNFT(_loanTerms, address(this), _nftReceiver); } /** * @notice Resolving the loan without trasferring the nft to provide a base for the bundle * break up of the bundled loans * * @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. * @param _loanCoordinator - The loan coordinator used when creating the loan. */ function _resolveLoanNoNftTransfer( uint32 _loanId, LoanTerms memory _loanTerms, IDirectLoanCoordinator _loanCoordinator ) internal { // Mark loan as liquidated before doing any external transfers to follow the Checks-Effects-Interactions design // pattern loanRepaidOrLiquidated[_loanId] = true; _escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] -= 1; // Destroy the lender's promissory note for this loan and borrower obligation receipt _loanCoordinator.resolveLoan(_loanId); } /** * @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes * both adding an ERC20 currency to the permitted list and removing it. * * @param _erc20 - The address of the ERC20 currency whose permit list status changed. * @param _permit - The new status of whether the currency is permitted or not. */ function _setERC20Permit(address _erc20, bool _permit) internal { require(_erc20 != address(0), "erc20 is zero address"); erc20Permits[_erc20] = _permit; emit ERC20Permit(_erc20, _permit); } /** * @dev Performs some validation checks over loan parameters * */ function _loanSanityChecks(LoanData.Offer memory _offer, address _nftWrapper) internal view { require(getERC20Permit(_offer.loanERC20Denomination), "Currency denomination is not permitted"); require(_nftWrapper != address(0), "NFT collateral contract is not permitted"); require(uint256(_offer.loanDuration) <= maximumLoanDuration, "Loan duration exceeds maximum loan duration"); require(uint256(_offer.loanDuration) != 0, "Loan duration cannot be zero"); require( _offer.loanAdminFeeInBasisPoints == adminFeeInBasisPoints, "The admin fee has changed since this order was signed." ); } /** * @dev reads some variable values of a loan for payback functions, created to reduce code repetition */ function _getPartiesAndData(uint32 _loanId) internal view returns ( address borrower, address lender, LoanTerms memory loan, IDirectLoanCoordinator loanCoordinator ) { loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR)); IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; // Fetch loan details from storage, but store them in memory for the sake of saving gas. loan = loanIdToLoan[_loanId]; if (loan.borrower != address(0)) { borrower = loan.borrower; } else { // Fetch current owner of loan obligation note. borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId); } /** * @dev Creates a `LoanExtras` struct using data sent as the borrower's extra settings. * This is needed in order to avoid stack too deep issues. */ function _setupLoanExtras(address _revenueSharePartner, uint16 _referralFeeInBasisPoints) internal view returns (LoanExtras memory) { // Save loan details to a struct in memory first, to save on gas if any // of the below checks fail, and to avoid the "Stack Too Deep" error by // clumping the parameters together into one struct held in memory. return LoanExtras({ revenueSharePartner: _revenueSharePartner, revenueShareInBasisPoints: LoanChecksAndCalculations.getRevenueSharePercent(_revenueSharePartner, hub), referralFeeInBasisPoints: _referralFeeInBasisPoints }); } /** * @dev Calculates the payoff amount and admin fee */ function _payoffAndFee(LoanTerms memory _loanTerms) internal view virtual returns (uint256, uint256); /** * @dev Checks that the collateral is a supported contracts and returns what wrapper to use for the loan's NFT * collateral contract. * * @param _nftCollateralContract - The address of the the NFT collateral contract. * * @return Address of the NftWrapper to use for the loan's NFT collateral. */ function _getWrapper(address _nftCollateralContract) internal view returns (address) { return IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS)).getNFTWrapper(_nftCollateralContract); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title ContractKeys * @author NFTfi * @dev Common library for contract keys */ library ContractKeys { bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S"); bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS"); bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS"); bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY"); bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY"); bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER"); bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S"); bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS"); bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER"); bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY"); bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN"); bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER"); string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper"; /** * @notice Returns the bytes32 representation of a string * @param _key the string key * @return id bytes32 representation */ function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) { require(bytes(_key).length <= 32, "invalid key"); // solhint-disable-next-line no-inline-assembly assembly { id := mload(add(_key, 32)) } } } // SPDX-License-Identifier: BUSL-1.1 import "./LoanData.sol"; pragma solidity 0.8.4; interface IDirectLoanBase { function maximumLoanDuration() external view returns (uint256); function adminFeeInBasisPoints() external view returns (uint16); // solhint-disable-next-line func-name-mixedcase function LOAN_COORDINATOR() external view returns (bytes32); function loanIdToLoan(uint32) external view returns ( uint256, uint256, uint256, address, uint32, uint16, uint16, address, uint64, address, address ); function loanRepaidOrLiquidated(uint32) external view returns (bool); function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title LoanData * @author NFTfi * @notice An interface containg the main Loan struct shared by Direct Loans types. */ interface LoanData { /* ********** */ /* DATA TYPES */ /* ********** */ /** * @notice The main Loan Terms struct. This data is saved upon loan creation. * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the the NFT collateral contract. * @param nftCollateralWrapper - The NFTfi wrapper of the NFT collateral contract. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param loanStartTime - The block.timestamp when the loan first began (measured in seconds). * @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate * the loan and seize the underlying collateral NFT. * @param loanInterestRateForDurationInBasisPoints - This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param borrower */ struct LoanTerms { uint256 loanPrincipalAmount; uint256 maximumRepaymentAmount; uint256 nftCollateralId; address loanERC20Denomination; uint32 loanDuration; uint16 loanInterestRateForDurationInBasisPoints; uint16 loanAdminFeeInBasisPoints; address nftCollateralWrapper; uint64 loanStartTime; address nftCollateralContract; address borrower; } /** * @notice Some extra Loan's settings struct. This data is saved upon loan creation. * We need this to avoid stack too deep errors. * * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be * taken as a revenue share for a t * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.he partner, at the moment * the loan is begun. */ struct LoanExtras { address revenueSharePartner; uint16 revenueShareInBasisPoints; uint16 referralFeeInBasisPoints; } /** * @notice The offer made by the lender. Used as parameter on both acceptOffer (initiated by the borrower) and * acceptListing (initiated by the lender). * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always * have to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate * the loan and seize the underlying collateral NFT. * @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. */ struct Offer { uint256 loanPrincipalAmount; uint256 maximumRepaymentAmount; uint256 nftCollateralId; address nftCollateralContract; uint32 loanDuration; uint16 loanAdminFeeInBasisPoints; address loanERC20Denomination; address referrer; } /** * @notice Signature related params. Used as parameter on both acceptOffer (containing borrower signature) and * acceptListing (containing lender signature). * * @param signer - The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * @param nonce - The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @param expiry - Date when the signature expires * @param signature - The ECDSA signature of the borrower or the lender, obtained off-chain ahead of time, signing * the following combination of parameters: * - Borrower * - ListingTerms.loanERC20Denomination, * - ListingTerms.minLoanPrincipalAmount, * - ListingTerms.maxLoanPrincipalAmount, * - ListingTerms.nftCollateralContract, * - ListingTerms.nftCollateralId, * - ListingTerms.revenueSharePartner, * - ListingTerms.minLoanDuration, * - ListingTerms.maxLoanDuration, * - ListingTerms.maxInterestRateForDurationInBasisPoints, * - ListingTerms.referralFeeInBasisPoints, * - Signature.signer, * - Signature.nonce, * - Signature.expiry, * - address of the loan type contract * - chainId * - Lender: * - Offer.loanERC20Denomination * - Offer.loanPrincipalAmount * - Offer.maximumRepaymentAmount * - Offer.nftCollateralContract * - Offer.nftCollateralId * - Offer.referrer * - Offer.loanDuration * - Offer.loanAdminFeeInBasisPoints * - Signature.signer, * - Signature.nonce, * - Signature.expiry, * - address of the loan type contract * - chainId */ struct Signature { uint256 nonce; uint256 expiry; address signer; bytes signature; } /** * @notice Some extra parameters that the borrower needs to set when accepting an offer. * * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. */ struct BorrowerSettings { address revenueSharePartner; uint16 referralFeeInBasisPoints; } /** * @notice Terms the borrower set off-chain and is willing to accept automatically when fulfiled by a lender's * offer. * * @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * @param minLoanPrincipalAmount - The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maxLoanPrincipalAmount - The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral. * @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * @param revenueSharePartner - The address of the partner that will receive the revenue share. * @param minLoanDuration - The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param maxLoanDuration - The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param maxInterestRateForDurationInBasisPoints - This is maximum the interest rate (measured in basis points, * e.g. hundreths of a percent) for the loan. * @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. */ struct ListingTerms { uint256 minLoanPrincipalAmount; uint256 maxLoanPrincipalAmount; uint256 nftCollateralId; address nftCollateralContract; uint32 minLoanDuration; uint32 maxLoanDuration; uint16 maxInterestRateForDurationInBasisPoints; uint16 referralFeeInBasisPoints; address revenueSharePartner; address loanERC20Denomination; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @title LoanChecksAndCalculations * @author NFTfi * @notice Helper library for LoanBase */ library LoanChecksAndCalculations { uint16 private constant HUNDRED_PERCENT = 10000; /** * @dev Function that performs some validation checks before trying to repay a loan * * @param _loanId - The id of the loan being repaid */ function payBackChecks(uint32 _loanId, INftfiHub _hub) external view { checkLoanIdValidity(_loanId, _hub); // Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId. // Depending on how the rest of the code turns out, this check may be unnecessary. require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated"); // Fetch loan details from storage, but store them in memory for the sake of saving gas. (, , , , uint32 loanDuration, , , , uint64 loanStartTime, , ) = IDirectLoanBase(address(this)).loanIdToLoan( _loanId ); // When a loan exceeds the loan term, it is expired. At this stage the Lender can call Liquidate Loan to resolve // the loan. require(block.timestamp <= (uint256(loanStartTime) + uint256(loanDuration)), "Loan is expired"); } function checkLoanIdValidity(uint32 _loanId, INftfiHub _hub) public view { require( IDirectLoanCoordinator(_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())).isValidLoanId( _loanId, address(this) ), "invalid loanId" ); } /** * @dev Function that the partner is permitted and returns its shared percent. * * @param _revenueSharePartner - Partner's address * * @return The revenue share percent for the partner. */ function getRevenueSharePercent(address _revenueSharePartner, INftfiHub _hub) external view returns (uint16) { // return soon if no partner is set to avoid a public call if (_revenueSharePartner == address(0)) { return 0; } uint16 revenueSharePercent = IPermittedPartners(_hub.getContract(ContractKeys.PERMITTED_PARTNERS)) .getPartnerPermit(_revenueSharePartner); return revenueSharePercent; } /** * @dev Performs some validation checks before trying to renegotiate a loan. * Needed to avoid stack too deep. * * @param _loan - The main Loan Terms struct. * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are * referring instead to nonces that are used by both the lender and the borrower when they are first signing * off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * @return Borrower and Lender addresses */ function renegotiationChecks( LoanData.LoanTerms memory _loan, uint32 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _lenderNonce, INftfiHub _hub ) external view returns (address, address) { checkLoanIdValidity(_loanId, _hub); IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); uint256 smartNftId = loanCoordinator.getLoanData(_loanId).smartNftId; address borrower; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } require(msg.sender == borrower, "Only borrower can initiate"); require(block.timestamp <= (uint256(_loan.loanStartTime) + _newLoanDuration), "New duration already expired"); require( uint256(_newLoanDuration) <= IDirectLoanBase(address(this)).maximumLoanDuration(), "New duration exceeds maximum loan duration" ); require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated"); require( _newMaximumRepaymentAmount >= _loan.loanPrincipalAmount, "Negative interest rate loans are not allowed." ); // Fetch current owner of loan promissory note. address lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId); require( !IDirectLoanBase(address(this)).getWhetherNonceHasBeenUsedForUser(lender, _lenderNonce), "Lender nonce invalid" ); return (borrower, lender); } /** * @dev Performs some validation checks over loan parameters when accepting a listing * */ function bindingTermsSanityChecks(LoanData.ListingTerms memory _listingTerms, LoanData.Offer memory _offer) external pure { // offer vs listing validations require(_offer.loanERC20Denomination == _listingTerms.loanERC20Denomination, "Invalid loanERC20Denomination"); require( _offer.loanPrincipalAmount >= _listingTerms.minLoanPrincipalAmount && _offer.loanPrincipalAmount <= _listingTerms.maxLoanPrincipalAmount, "Invalid loanPrincipalAmount" ); uint256 maxRepaymentLimit = _offer.loanPrincipalAmount + (_offer.loanPrincipalAmount * _listingTerms.maxInterestRateForDurationInBasisPoints) / HUNDRED_PERCENT; require(_offer.maximumRepaymentAmount <= maxRepaymentLimit, "maxInterestRateForDurationInBasisPoints violated"); require( _offer.loanDuration >= _listingTerms.minLoanDuration && _offer.loanDuration <= _listingTerms.maxLoanDuration, "Invalid loanDuration" ); } /** * @notice A convenience function computing the revenue share taken from the admin fee to transferr to the permitted * partner. * * @param _adminFee - The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due * as an admin fee. * @param _revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be * taken as a revenue share for a the partner, at the moment the loan is begun. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to * the `revenueSharePartner`. */ function computeRevenueShare(uint256 _adminFee, uint256 _revenueShareInBasisPoints) external pure returns (uint256) { return (_adminFee * _revenueShareInBasisPoints) / HUNDRED_PERCENT; } /** * @notice A convenience function computing the adminFee taken from a specified quantity of interest. * * @param _interestDue - The amount of interest due, measured in the smallest quantity of the ERC20 currency being * used to pay the interest. * @param _adminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be taken * as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due as an admin * fee. */ function computeAdminFee(uint256 _interestDue, uint256 _adminFeeInBasisPoints) external pure returns (uint256) { return (_interestDue * _adminFeeInBasisPoints) / HUNDRED_PERCENT; } /** * @notice A convenience function computing the referral fee taken from the loan principal amount to transferr to * the referrer. * * @param _loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * @param _referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will * be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal * that there is no referrer. * * @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to * the referrer. */ function computeReferralFee( uint256 _loanPrincipalAmount, uint256 _referralFeeInBasisPoints, address _referrer ) external pure returns (uint256) { if (_referralFeeInBasisPoints == 0 || _referrer == address(0)) { return 0; } return (_loanPrincipalAmount * _referralFeeInBasisPoints) / HUNDRED_PERCENT; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "./IDirectLoanBase.sol"; import "./LoanData.sol"; import "../../../interfaces/IDirectLoanCoordinator.sol"; import "../../../utils/ContractKeys.sol"; import "../../../interfaces/INftfiHub.sol"; import "../../../interfaces/IPermittedPartners.sol"; import "../../../interfaces/IPermittedERC20s.sol"; import "../../../interfaces/IAirdropFlashLoan.sol"; import "../../../interfaces/INftWrapper.sol"; import "../../../airdrop/IAirdropReceiverFactory.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title LoanAirdropUtils * @author NFTfi * @notice Helper library for LoanBase */ library LoanAirdropUtils { /** * @notice This event is fired whenever a flashloan is initiated to pull an airdrop * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this * loan. * @param nftCollateralContract - The ERC721 contract of the NFT collateral * @param target - address of the airdropping contract * @param data - function selector to be called */ event AirdropPulledFlashloan( uint256 indexed loanId, address indexed borrower, uint256 nftCollateralId, address nftCollateralContract, address target, bytes data ); /** * @notice This event is fired whenever the collateral gets wrapped in an airdrop receiver * * @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator. * @param borrower - The address of the borrower. * @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this * loan. * @param nftCollateralContract - The contract of the NFT collateral * @param receiverId - id of the created AirdropReceiver, takes the place of nftCollateralId on the loan * @param receiverInstance - address of the created AirdropReceiver */ event CollateralWrapped( uint256 indexed loanId, address indexed borrower, uint256 nftCollateralId, address nftCollateralContract, uint256 receiverId, address receiverInstance ); function pullAirdrop( uint32 _loanId, LoanData.LoanTerms memory _loan, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount, INftfiHub _hub ) external { IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); address borrower; // scoped to aviod stack too deep { IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } } require(msg.sender == borrower, "Only borrower can airdrop"); { IAirdropFlashLoan airdropFlashLoan = IAirdropFlashLoan(_hub.getContract(ContractKeys.AIRDROP_FLASH_LOAN)); _transferNFT(_loan, address(this), address(airdropFlashLoan)); airdropFlashLoan.pullAirdrop( _loan.nftCollateralContract, _loan.nftCollateralId, _loan.nftCollateralWrapper, _target, _data, _nftAirdrop, _nftAirdropId, _is1155, _nftAirdropAmount, borrower ); } // revert if the collateral hasn't been transferred back before it ends require( INftWrapper(_loan.nftCollateralWrapper).isOwner( address(this), _loan.nftCollateralContract, _loan.nftCollateralId ), "Collateral should be returned" ); emit AirdropPulledFlashloan( _loanId, borrower, _loan.nftCollateralId, _loan.nftCollateralContract, _target, _data ); } function wrapCollateral( uint32 _loanId, LoanData.LoanTerms storage _loan, INftfiHub _hub ) external returns (address instance, uint256 receiverId) { IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator( _hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR()) ); // Fetch the current lender of the promissory note corresponding to this overdue loan. IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId); uint256 smartNftId = loanCoordinatorData.smartNftId; address borrower; if (_loan.borrower != address(0)) { borrower = _loan.borrower; } else { borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId); } require(msg.sender == borrower, "Only borrower can wrapp"); IAirdropReceiverFactory factory = IAirdropReceiverFactory(_hub.getContract(ContractKeys.AIRDROP_FACTORY)); (instance, receiverId) = factory.createAirdropReceiver(address(this)); // transfer collateral to airdrop receiver wrapper _transferNFTtoAirdropReceiver(_loan, instance, borrower); emit CollateralWrapped( _loanId, borrower, _loan.nftCollateralId, _loan.nftCollateralContract, receiverId, instance ); // set the receiver as the new collateral _loan.nftCollateralContract = instance; _loan.nftCollateralId = receiverId; } /** * @dev Transfers several types of NFTs using a wrapper that knows how to handle each case. * * @param _loan - * @param _sender - Current owner of the NFT * @param _recipient - Recipient of the transfer */ function _transferNFT( LoanData.LoanTerms memory _loan, address _sender, address _recipient ) internal { Address.functionDelegateCall( _loan.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loan.nftCollateralWrapper).transferNFT.selector, _sender, _recipient, _loan.nftCollateralContract, _loan.nftCollateralId ), "NFT not successfully transferred" ); } /** * @dev Transfers several types of NFTs to an airdrop receiver with an airdrop beneficiary * address attached as supplementing data using a wrapper that knows how to handle each case. * * @param _loan - * @param _airdropReceiverInstance - Recipient of the transfer * @param _airdropBeneficiary - Beneficiary of the future airdops */ function _transferNFTtoAirdropReceiver( LoanData.LoanTerms memory _loan, address _airdropReceiverInstance, address _airdropBeneficiary ) internal { Address.functionDelegateCall( _loan.nftCollateralWrapper, abi.encodeWithSelector( INftWrapper(_loan.nftCollateralWrapper).wrapAirdropReceiver.selector, _airdropReceiverInstance, _loan.nftCollateralContract, _loan.nftCollateralId, _airdropBeneficiary ), "NFT was not successfully migrated" ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../utils/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title BaseLoan * @author NFTfi * @dev Implements base functionalities common to all Loan types. * Mostly related to governance and security. */ abstract contract BaseLoan is Ownable, Pausable, ReentrancyGuard { /* *********** */ /* CONSTRUCTOR */ /* *********** */ /** * @notice Sets the admin of the contract. * * @param _admin - Initial admin of this contract. */ constructor(address _admin) Ownable(_admin) { // solhint-disable-previous-line no-empty-blocks } /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev Triggers stopped state. * * Requirements: * * - Only the owner can call this method. * - The contract must not be paused. */ function pause() external onlyOwner { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - Only the owner can call this method. * - The contract must be paused. */ function unpause() external onlyOwner { _unpause(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; /** * @title NftReceiver * @author NFTfi * @dev Base contract with capabilities for receiving ERC1155 and ERC721 tokens */ abstract contract NftReceiver is IERC1155Receiver, ERC721Holder { /** * @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. * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if allowed */ function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external virtual override returns (bytes4) { return this.onERC1155Received.selector; } /** * @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. * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if allowed */ function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external virtual override returns (bytes4) { revert("ERC1155 batch not supported"); } /** * @dev Checks whether this contract implements the interface defined by `interfaceId`. * @param _interfaceId Id of the interface * @return true if this contract implements the interface */ function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) { return _interfaceId == type(IERC1155Receiver).interfaceId || _interfaceId == type(IERC721Receiver).interfaceId || _interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "../interfaces/IBundleBuilder.sol"; import "../loans/direct/loanTypes/LoanData.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; /** * @title NFTfiSigningUtils * @author NFTfi * @notice Helper contract for NFTfi. This contract manages verifying signatures from off-chain NFTfi orders. * Based on the version of this same contract used on NFTfi V1 */ library NFTfiSigningUtils { /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev This function gets the current chain ID. */ function getChainID() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignature(LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature) external view returns (bool) { return isValidBorrowerSignature(_listingTerms, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignature( LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidBorrowerSignatureBundle(_listingTerms, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignature(LoanData.Offer memory _offer, LoanData.Signature memory _signature) external view returns (bool) { return isValidLenderSignature(_offer, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignature( LoanData.Offer memory _offer, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked(getEncodedOffer(_offer), getEncodedSignature(_signature), _loanContract, getChainID()) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderSignatureBundle(_offer, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedOffer(_offer), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is called in renegotiateLoan() to validate the lender's signature that the lender provided * off-chain to verify that they did indeed want to agree to this loan renegotiation according to these terms. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * - expiry - The date when the renegotiation offer expires * - lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _lenderNonce * - _expiry * - address of this contract * - chainId */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _signature, address(this) ); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Renegotiation Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) { return abi.encodePacked( _listingTerms.loanERC20Denomination, _listingTerms.minLoanPrincipalAmount, _listingTerms.maxLoanPrincipalAmount, _listingTerms.nftCollateralContract, _listingTerms.nftCollateralId, _listingTerms.revenueSharePartner, _listingTerms.minLoanDuration, _listingTerms.maxLoanDuration, _listingTerms.maxInterestRateForDurationInBasisPoints, _listingTerms.referralFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedOffer(LoanData.Offer memory _offer) internal pure returns (bytes memory) { return abi.encodePacked( _offer.loanERC20Denomination, _offer.loanPrincipalAmount, _offer.maximumRepaymentAmount, _offer.nftCollateralContract, _offer.nftCollateralId, _offer.referrer, _offer.loanDuration, _offer.loanAdminFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedSignature(LoanData.Signature memory _signature) internal pure returns (bytes memory) { return abi.encodePacked(_signature.signer, _signature.nonce, _signature.expiry); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftfiHub * @author NFTfi * @dev NftfiHub interface */ interface INftfiHub { function setContract(string calldata _contractKey, address _contractAddress) external; function getContract(bytes32 _contractKey) external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title IDirectLoanCoordinator * @author NFTfi * @dev DirectLoanCoordinator interface. */ interface IDirectLoanCoordinator { enum StatusType { NOT_EXISTS, NEW, RESOLVED } /** * @notice This struct contains data related to a loan * * @param smartNftId - The id of both the promissory note and obligation receipt. * @param status - The status in which the loan currently is. * @param loanContract - Address of the LoanType contract that created the loan. */ struct Loan { address loanContract; uint64 smartNftId; StatusType status; } function registerLoan(address _lender, bytes32 _loanType) external returns (uint32); function mintObligationReceipt(uint32 _loanId, address _borrower) external; function resolveLoan(uint32 _loanId) external; function promissoryNoteToken() external view returns (address); function obligationReceiptToken() external view returns (address); function getLoanData(uint32 _loanId) external view returns (Loan memory); function isValidLoanId(uint32 _loanId, address _loanContract) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title INftTypeRegistry * @author NFTfi * @dev Interface for NFT Wrappers. */ interface INftWrapper { function transferNFT( address from, address to, address nftContract, uint256 tokenId ) external returns (bool); function isOwner( address owner, address nftContract, uint256 tokenId ) external view returns (bool); function wrapAirdropReceiver( address _recipient, address _nftContract, uint256 _nftId, address _beneficiary ) external returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedPartners { function getPartnerPermit(address _partner) external view returns (uint16); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedERC20s { function getERC20Permit(address _erc20) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IPermittedNFTs { function setNFTPermit(address _nftContract, string memory _nftType) external; function getNFTPermit(address _nftContract) external view returns (bytes32); function getNFTWrapper(address _nftContract) external view returns (address); } // 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 (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; interface IAirdropFlashLoan { function pullAirdrop( address _nftCollateralContract, uint256 _nftCollateralId, address _nftWrapper, address _target, bytes calldata _data, address _nftAirdrop, uint256 _nftAirdropId, bool _is1155, uint256 _nftAirdropAmount, address _beneficiary ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; /** * @title IAirdropReceiver * @author NFTfi * @dev */ interface IAirdropReceiverFactory { function createAirdropReceiver(address _to) external returns (address, uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.4; import "@openzeppelin/contracts/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. * * Modified version from openzeppelin/contracts/access/Ownable.sol that allows to * initialize the owner using a parameter in the constructor */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /** * @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); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Sets the owner. */ function _setOwner(address _newOwner) private { address oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(oldOwner, _newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: 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. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @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; } } // 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: BUSL-1.1 pragma solidity 0.8.4; interface IBundleBuilder { /** * @notice data of a erc721 bundle element * * @param tokenContract - address of the token contract * @param id - id of the token * @param safeTransferable - wether the implementing token contract has a safeTransfer function or not */ struct BundleElementERC721 { address tokenContract; uint256 id; bool safeTransferable; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param amount - amount of the token */ struct BundleElementERC20 { address tokenContract; uint256 amount; } /** * @notice data of a erc20 bundle element * * @param tokenContract - address of the token contract * @param ids - list of ids of the tokens * @param amounts - list amounts of the tokens */ struct BundleElementERC1155 { address tokenContract; uint256[] ids; uint256[] amounts; } /** * @notice the lists of erc721-20-1155 tokens that are to be bundled * * @param erc721s list of erc721 tokens * @param erc20s list of erc20 tokens * @param erc1155s list of erc1155 tokens */ struct BundleElements { BundleElementERC721[] erc721s; BundleElementERC20[] erc20s; BundleElementERC1155[] erc1155s; } /** * @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan, * returns the id of the created bundle * * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _sender sender of the tokens in the bundle - the borrower * @param _receiver receiver of the created bundle, normally the loan contract */ function buildBundle( BundleElements memory _bundleElements, address _sender, address _receiver ) external returns (uint256); /** * @notice Remove all the children from the bundle * @dev This method may run out of gas if the list of children is too big. In that case, children can be removed * individually. * @param _tokenId the id of the bundle * @param _receiver address of the receiver of the children */ function decomposeBundle(uint256 _tokenId, address _receiver) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // 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: BUSL-1.1 INftTypeRegistry NFTfi Interface for NFT Wrappers./
interface INftWrapper { function transferNFT( address from, address to, address nftContract, uint256 tokenId ) external returns (bool); function isOwner( address owner, address nftContract, uint256 tokenId ) external view returns (bool); function wrapAirdropReceiver( address _recipient, address _nftContract, uint256 _nftId, address _beneficiary ) external returns (bool); }
1,474,600
./full_match/4/0xBd338B3193d8eAc21a48a4eac2cB8c9aa69cB7d5/sources/Volumes/Work/Code/token-installation-timelock/contracts/Lock.sol
return the beneficiary of the tokens./ return startTime - block.timestamp; solhint-disable-next-line not-rely-on-time uint timeLeft = ;
function getTimeRemaining() public view returns (uint) { if (_token.balanceOf(address(this)) == 0) return 0; if(block.timestamp >= startTime) return 0; }
648,013
./full_match/1/0x71e2dCd9bc0D2BE70719b3dd2AAC3e763466c9f1/sources/browser/dgexfinanceBank.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 DgextReward = multiplier.mul(DgextPerBlock).mul(pool.allocPoint).div(totalAllocPoint); dgext.mint(address(this), DgextReward); pool.accDgextPerShare = pool.accDgextPerShare.add(DgextReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
3,014,790
./partial_match/1/0x8BeEb8f4a719b17F326Bfc6bC928b99BE30aEB71/sources/StakingDextoken.sol
Retrieve the stake for a stakeholder
function stakeOf(address _stakeholder) external view returns (uint) { return _balances[_stakeholder]; }
2,895,238
./full_match/1/0xE5d35f68BB3e47bE5161387b061973e6F27a4C0c/sources/DUTToken.sol
add/remove a LP only callable by `owner()`/
function setIsLpPool(address pairAddress, bool isLp) external override onlyOwner { _setIsLpPool(pairAddress, isLp); }
2,989,489
./partial_match/1/0xC870BDd7185844E9b909a5E04b267a5A762fd8be/sources/MemeStream.sol
once enabled, can never be turned off
function beginTrading() external onlyOwner { isTradingOpen = true; isSwapEnabled = true; lastLpBurnTime = block.timestamp; }
2,582,124
pragma solidity 0.4.21; // File: contracts/BytesDeserializer.sol /* * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /* * Deserialize bytes payloads. * * Values are in big-endian byte order. * */ library BytesDeserializer { /* * Extract 256-bit worth of data from the bytes stream. */ function slice32(bytes b, uint offset) public pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } /* * Extract Ethereum address worth of data from the bytes stream. */ function sliceAddress(bytes b, uint offset) public pure returns (address) { bytes32 out; for (uint i = 0; i < 20; i++) { out |= bytes32(b[offset + i] & 0xFF) >> ((i+12) * 8); } return address(uint(out)); } /* * Extract 128-bit worth of data from the bytes stream. */ function slice16(bytes b, uint offset) public pure returns (bytes16) { bytes16 out; for (uint i = 0; i < 16; i++) { out |= bytes16(b[offset + i] & 0xFF) >> (i * 8); } return out; } /* * Extract 32-bit worth of data from the bytes stream. */ function slice4(bytes b, uint offset) public pure returns (bytes4) { bytes4 out; for (uint i = 0; i < 4; i++) { out |= bytes4(b[offset + i] & 0xFF) >> (i * 8); } return out; } /* * Extract 16-bit worth of data from the bytes stream. */ function slice2(bytes b, uint offset) public pure returns (bytes2) { bytes2 out; for (uint i = 0; i < 2; i++) { out |= bytes2(b[offset + i] & 0xFF) >> (i * 8); } return out; } } // File: contracts/KYCPayloadDeserializer.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * A mix-in contract to decode AML payloads. * * @notice This should be a library, but for the complexity and toolchain fragility risks involving of linking library inside library, we put this as a mix-in. */ contract KYCPayloadDeserializer { using BytesDeserializer for bytes; /** * This function takes the dataframe and unpacks it * We have the users ETH address for verification that they are using their own signature * CustomerID so we can track customer purchases * Min/Max ETH to invest for AML/CTF purposes - this can be supplied by the user OR by the back-end. */ function getKYCPayload(bytes dataframe) public pure returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); return (_whitelistedAddress, _customerId, _minETH, _maxETH); } } // File: contracts/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/ERC20Basic.sol /** * @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); } // File: contracts/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ReleasableToken.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * * Some of this code has been updated by Pickeringware ltd to faciliatte the new solidity compilation requirements */ pragma solidity 0.4.21; /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is StandardToken, 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) { if(!transferAgents[_sender]) { revert(); } } _; } /** * 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() onlyOwner inReleaseState(false) public { // We don&#39;t do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = owner; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyReleaseAgent 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) { if(releaseState != released) { revert(); } _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { if(msg.sender != releaseAgent) { revert(); } _; } 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); } } // File: contracts/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol * * Some of this code has been changed by Pickeringware ltd to facilitate solidities new compilation requirements */ contract MintableToken is ReleasableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(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; MintFinished(); return true; } } // File: contracts/AMLToken.sol /** * This contract has been written by Pickeringware ltd in some areas to facilitate custom crwodsale features */ pragma solidity 0.4.21; /** * The AML Token * * This subset of MintableCrowdsaleToken gives the Owner a possibility to * reclaim tokens from a participant before the token is released * after a participant has failed a prolonged AML process. * * It is assumed that the anti-money laundering process depends on blockchain data. * The data is not available before the transaction and not for the smart contract. * Thus, we need to implement logic to handle AML failure cases post payment. * We give a time window before the token release for the token sale owners to * complete the AML and claw back all token transactions that were * caused by rejected purchases. */ contract AMLToken is MintableToken { // An event when the owner has reclaimed non-released tokens event ReclaimedAllAndBurned(address claimedBy, address fromWhom, uint amount); // An event when the owner has reclaimed non-released tokens event ReclaimAndBurned(address claimedBy, address fromWhom, uint amount); /// @dev Here the owner can reclaim the tokens from a participant if /// the token is not released yet. Refund will be handled in sale contract. /// We also burn the tokens in the interest of economic value to the token holder /// @param fromWhom address of the participant whose tokens we want to claim function reclaimAllAndBurn(address fromWhom) public onlyReleaseAgent inReleaseState(false) { uint amount = balanceOf(fromWhom); balances[fromWhom] = 0; totalSupply = totalSupply.sub(amount); ReclaimedAllAndBurned(msg.sender, fromWhom, amount); } /// @dev Here the owner can reclaim the tokens from a participant if /// the token is not released yet. Refund will be handled in sale contract. /// We also burn the tokens in the interest of economic value to the token holder /// @param fromWhom address of the participant whose tokens we want to claim function reclaimAndBurn(address fromWhom, uint256 amount) public onlyReleaseAgent inReleaseState(false) { balances[fromWhom] = balances[fromWhom].sub(amount); totalSupply = totalSupply.sub(amount); ReclaimAndBurned(msg.sender, fromWhom, amount); } } // File: contracts/PickToken.sol /* * This token is part of Pickeringware ltds smart contracts * It is used to specify certain details about the token upon release */ contract PickToken is AMLToken { string public name = "AX1 Mining token"; string public symbol = "AX1"; uint8 public decimals = 5; } // File: contracts/Stoppable.sol contract Stoppable is Ownable { bool public halted; event SaleStopped(address owner, uint256 datetime); modifier stopInEmergency { require(!halted); _; } function hasHalted() internal view returns (bool isHalted) { return halted; } // called by the owner on emergency, triggers stopped state function stopICO() external onlyOwner { halted = true; SaleStopped(msg.sender, now); } } // File: contracts/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. * * This base contract has been changed in certain areas by Pickeringware ltd to facilitate extra functionality */ contract Crowdsale is Stoppable { using SafeMath for uint256; // The token being sold PickToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; address public contractAddr; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; uint256 public presaleWeiRaised; // amount of tokens sent uint256 public tokensSent; // These store balances of participants by ID, address and in wei, pre-sale wei and tokens mapping(uint128 => uint256) public balancePerID; mapping(address => uint256) public balanceOf; mapping(address => uint256) public presaleBalanceOf; mapping(address => uint256) public tokenBalanceOf; /** * 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, uint256 datetime); /* * Contructor * This initialises the basic crowdsale data * It transfers ownership of this token to the chosen beneficiary */ function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, PickToken _token) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = _token; startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; transferOwnership(_wallet); } /* * This method has been changed by Pickeringware ltd * We have split this method down into overidable functions which may affect how users purchase tokens * We also take in a customerID (UUiD v4) which we store in our back-end in order to track users participation */ function buyTokens(uint128 buyer) internal stopInEmergency { require(buyer != 0); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = tokensToRecieve(weiAmount); // MUST DO REQUIRE AFTER tokens are calculated to check for cap restrictions in stages require(validPurchase(tokens)); // We move the participants sliders before we mint the tokens to prevent re-entrancy finalizeSale(weiAmount, tokens, buyer); produceTokens(msg.sender, weiAmount, tokens); } // This function was created to be overridden by a parent contract function produceTokens(address buyer, uint256 weiAmount, uint256 tokens) internal { token.mint(buyer, tokens); TokenPurchase(msg.sender, buyer, weiAmount, tokens, now); } // This was created to be overriden by stages implementation // It will adjust the stage sliders accordingly if needed function finalizeSale(uint256 _weiAmount, uint256 _tokens, uint128 _buyer) internal { // Collect ETH and send them a token in return balanceOf[msg.sender] = balanceOf[msg.sender].add(_weiAmount); tokenBalanceOf[msg.sender] = tokenBalanceOf[msg.sender].add(_tokens); balancePerID[_buyer] = balancePerID[_buyer].add(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); tokensSent = tokensSent.add(_tokens); } // This was created to be overridden by the stages implementation // Again, this is dependent on the price of tokens which may or may not be collected in stages function tokensToRecieve(uint256 _wei) internal view returns (uint256 tokens) { return _wei.div(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function successfulWithdraw() external onlyOwner stopInEmergency { require(hasEnded()); owner.transfer(weiRaised); } // @return true if the transaction can buy tokens // Receives tokens to send as variable for custom stage implementation // Has an unused variable _tokens which is necessary for capped sale implementation function validPurchase(uint256 _tokens) internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/CappedCrowdsale.sol /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public softCap; uint256 public hardCap; uint256 public withdrawn; bool public canWithdraw; address public beneficiary; event BeneficiaryWithdrawal(address admin, uint256 amount, uint256 datetime); // Changed implentation to include soft/hard caps function CappedCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _beneficiary, uint256 _softCap, uint256 _hardCap, PickToken _token) Crowdsale(_startTime, _endTime, _rate, _wallet, _token) public { require(_hardCap > 0 && _softCap > 0 && _softCap < _hardCap); softCap = _softCap; hardCap = _hardCap; withdrawn = 0; canWithdraw = false; beneficiary = _beneficiary; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase(uint256 _tokens) internal view returns (bool) { bool withinCap = tokensSent.add(_tokens) <= hardCap; return super.validPurchase(_tokens) && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = tokensSent >= hardCap; return super.hasEnded() || capReached; } // overriding Crowdsale#successfulWithdraw to add cap logic // only allow beneficiary to withdraw if softcap has been reached // Uses withdrawn incase a parent contract requires withdrawing softcap early function successfulWithdraw() external onlyOwner stopInEmergency { require(hasEnded()); // This is used for extra functionality if necessary, i.e. KYC checks require(canWithdraw); require(tokensSent > softCap); uint256 withdrawalAmount = weiRaised.sub(withdrawn); withdrawn = withdrawn.add(withdrawalAmount); beneficiary.transfer(withdrawalAmount); BeneficiaryWithdrawal(msg.sender, withdrawalAmount, now); } } // File: contracts/SaleStagesLib.sol /* * SaleStagesLib is a part of Pickeringware ltd&#39;s smart contracts * Its intended use is to abstract the implementation of stages away from a contract to ease deployment and codel length * It uses a stage struct to store specific details about each stage * It has several functions which are used to get/change this data */ library SaleStagesLib { using SafeMath for uint256; // Stores Stage implementation struct Stage{ uint256 deadline; uint256 tokenPrice; uint256 tokensSold; uint256 minimumBuy; uint256 cap; } // The struct that is stored by the contract // Contains counter to iterate through map of stages struct StageStorage { mapping(uint8 => Stage) stages; uint8 stageCount; } // Initiliase the stagecount to 0 function init(StageStorage storage self) public { self.stageCount = 0; } // Create stage adds new stage to stages map and increments stage count function createStage( StageStorage storage self, uint8 _stage, uint256 _deadline, uint256 _price, uint256 _minimum, uint256 _cap ) internal { // Ensures stages cannot overlap each other uint8 prevStage = _stage - 1; require(self.stages[prevStage].deadline < _deadline); self.stages[_stage].deadline = _deadline; self.stages[_stage].tokenPrice = _price; self.stages[_stage].tokensSold = 0; self.stages[_stage].minimumBuy = _minimum; self.stages[_stage].cap = _cap; self.stageCount = self.stageCount + 1; } /* * 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. * Each one of these conditions checks if the time has passed into another stage and therefore, act as appropriate */ function getStage(StageStorage storage self) public view returns (uint8 stage) { uint8 thisStage = self.stageCount + 1; for (uint8 i = 0; i < thisStage; i++) { if(now <= self.stages[i].deadline){ return i; } } return thisStage; } // Both of the below are checked on the overridden validPurchase() function // Check to see if the tokens they&#39;re about to purchase is above the minimum for this stage function checkMinimum(StageStorage storage self, uint8 _stage, uint256 _tokens) internal view returns (bool isValid) { if(_tokens < self.stages[_stage].minimumBuy){ return false; } else { return true; } } // Both of the below are checked on the overridden validPurchase() function // Check to see if the tokens they&#39;re about to purchase is above the minimum for this stage function changeDeadline(StageStorage storage self, uint8 _stage, uint256 _deadline) internal { require(self.stages[_stage].deadline > now); self.stages[_stage].deadline = _deadline; } // Checks to see if the tokens they&#39;re about to purchase is below the cap for this stage function checkCap(StageStorage storage self, uint8 _stage, uint256 _tokens) internal view returns (bool isValid) { uint256 totalTokens = self.stages[_stage].tokensSold.add(_tokens); if(totalTokens > self.stages[_stage].cap){ return false; } else { return true; } } // Refund a particular participant, by moving the sliders of stages he participated in function refundParticipant(StageStorage storage self, uint256 stage1, uint256 stage2, uint256 stage3, uint256 stage4) internal { self.stages[1].tokensSold = self.stages[1].tokensSold.sub(stage1); self.stages[2].tokensSold = self.stages[2].tokensSold.sub(stage2); self.stages[3].tokensSold = self.stages[3].tokensSold.sub(stage3); self.stages[4].tokensSold = self.stages[4].tokensSold.sub(stage4); } // Both of the below are checked on the overridden validPurchase() function // Check to see if the tokens they&#39;re about to purchase is above the minimum for this stage function changePrice(StageStorage storage self, uint8 _stage, uint256 _tokenPrice) internal { require(self.stages[_stage].deadline > now); self.stages[_stage].tokenPrice = _tokenPrice; } } // File: contracts/PickCrowdsale.sol /* * PickCrowdsale and PickToken are a part of Pickeringware ltd&#39;s smart contracts * This uses the SaleStageLib which is also a part of Pickeringware ltd&#39;s smart contracts * We create the stages initially in the constructor such that stages cannot be added after the sale has started * We then pre-allocate necessary accounts prior to the sale starting * This contract implements the stages lib functionality with overriding functions for stages implementation */ contract PickCrowdsale is CappedCrowdsale { using SaleStagesLib for SaleStagesLib.StageStorage; using SafeMath for uint256; SaleStagesLib.StageStorage public stages; bool preallocated = false; bool stagesSet = false; address private founders; address private bounty; address private buyer; uint256 public burntBounty; uint256 public burntFounder; event ParticipantWithdrawal(address participant, uint256 amount, uint256 datetime); event StagePriceChanged(address admin, uint8 stage, uint256 price); event ExtendedStart(uint256 oldStart, uint256 newStart); modifier onlyOnce(bool _check) { if(_check) { revert(); } _; } function PickCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _beneficiary, address _buyer, address _founders, address _bounty, uint256 _softCap, uint256 _hardCap, PickToken _token) CappedCrowdsale(_startTime, _endTime, _rate, _wallet, _beneficiary, _softCap, _hardCap, _token) public { stages.init(); stages.createStage(0, _startTime, 0, 0, 0); founders = _founders; bounty = _bounty; buyer = _buyer; } function setPreallocations() external onlyOwner onlyOnce(preallocated) { preallocate(buyer, 1250000, 10000000000); preallocate(founders, 1777777, 0); preallocate(bounty, 444445, 0); preallocated = true; } function setStages() external onlyOwner onlyOnce(stagesSet) { stages.createStage(1, startTime.add(1 weeks), 10000000000, 10000000, 175000000000); //Deadline 1 day (86400) after start - price: 0.001 - min: 90 - cap: 1,250,000 stages.createStage(2, startTime.add(2 weeks), 11000000000, 5000000, 300000000000); //Deadline 2 days (172800) after start - price: 0.0011 - min: 60 - cap: 3,000,000 stages.createStage(3, startTime.add(4 weeks), 12000000000, 2500000, 575000000000); //Deadline 4 days (345600) after start - price: 0.0012 - cap: 5,750,000 stages.createStage(4, endTime, 15000000000, 1000000, 2000000000000); //Deadline 1 week after start - price: 0.0015 - cap: 20,000,000 stagesSet = true; } // Creates new stage for the crowdsale // Can ONLY be called by the owner of the contract as should never change after creating them on initialisation function createStage(uint8 _stage, uint256 _deadline, uint256 _price, uint256 _minimum, uint256 _cap ) internal onlyOwner { stages.createStage(_stage, _deadline, _price, _minimum, _cap); } // Creates new stage for the crowdsale // Can ONLY be called by the owner of the contract as should never change after creating them on initialisation function changePrice(uint8 _stage, uint256 _price) public onlyOwner { stages.changePrice(_stage, _price); StagePriceChanged(msg.sender, _stage, _price); } // Get stage is required to rethen the stage we are currently in // This is necessary to check the stage details listed in the below functions function getStage() public view returns (uint8 stage) { return stages.getStage(); } function getStageDeadline(uint8 _stage) public view returns (uint256 deadline) { return stages.stages[_stage].deadline; } function getStageTokensSold(uint8 _stage) public view returns (uint256 sold) { return stages.stages[_stage].tokensSold; } function getStageCap(uint8 _stage) public view returns (uint256 cap) { return stages.stages[_stage].cap; } function getStageMinimum(uint8 _stage) public view returns (uint256 min) { return stages.stages[_stage].minimumBuy; } function getStagePrice(uint8 _stage) public view returns (uint256 price) { return stages.stages[_stage].tokenPrice; } // This is used for extending the sales start time (and the deadlines of each stage) accordingly function extendStart(uint256 _newStart) external onlyOwner { require(_newStart > startTime); require(_newStart > now); require(now < startTime); uint256 difference = _newStart - startTime; uint256 oldStart = startTime; startTime = _newStart; endTime = endTime + difference; // Loop through every stage in the sale for (uint8 i = 0; i < 4; i++) { // Extend that stages deadline accordingly uint256 temp = stages.stages[i].deadline; temp = temp + difference; stages.changeDeadline(i, temp); } ExtendedStart(oldStart, _newStart); } // @Override crowdsale contract to check the current stage price // @return tokens investors are due to recieve function tokensToRecieve(uint256 _wei) internal view returns (uint256 tokens) { uint8 stage = getStage(); uint256 price = getStagePrice(stage); return _wei.div(price); } // overriding Crowdsale validPurchase to add extra stage logic // @return true if investors can buy at the moment function validPurchase(uint256 _tokens) internal view returns (bool) { bool isValid = false; uint8 stage = getStage(); if(stages.checkMinimum(stage, _tokens) && stages.checkCap(stage, _tokens)){ isValid = true; } return super.validPurchase(_tokens) && isValid; } // Override crowdsale finalizeSale function to log balance change plus tokens sold in that stage function finalizeSale(uint256 _weiAmount, uint256 _tokens, uint128 _buyer) internal { // Collect ETH and send them a token in return balanceOf[msg.sender] = balanceOf[msg.sender].add(_weiAmount); tokenBalanceOf[msg.sender] = tokenBalanceOf[msg.sender].add(_tokens); balancePerID[_buyer] = balancePerID[_buyer].add(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); tokensSent = tokensSent.add(_tokens); uint8 stage = getStage(); stages.stages[stage].tokensSold = stages.stages[stage].tokensSold.add(_tokens); } /** * Preallocate tokens for the early investors. */ function preallocate(address receiver, uint tokens, uint weiPrice) internal { uint decimals = token.decimals(); uint tokenAmount = tokens * 10 ** decimals; uint weiAmount = weiPrice * tokens; presaleWeiRaised = presaleWeiRaised.add(weiAmount); tokensSent = tokensSent.add(tokenAmount); tokenBalanceOf[receiver] = tokenBalanceOf[receiver].add(tokenAmount); presaleBalanceOf[receiver] = presaleBalanceOf[receiver].add(weiAmount); produceTokens(receiver, weiAmount, tokenAmount); } // If the sale is unsuccessful (has halted or reached deadline and didnt reach softcap) // Allows participants to withdraw their balance function unsuccessfulWithdrawal() external { require(balanceOf[msg.sender] > 0); require(hasEnded() && tokensSent < softCap || hasHalted()); uint256 withdrawalAmount; withdrawalAmount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; msg.sender.transfer(withdrawalAmount); assert(balanceOf[msg.sender] == 0); ParticipantWithdrawal(msg.sender, withdrawalAmount, now); } // Burn the percentage of tokens not sold from the founders and bounty wallets // Must do it this way as solidity doesnt deal with decimals function burnFoundersTokens(uint256 _bounty, uint256 _founders) internal { require(_founders < 177777700000); require(_bounty < 44444500000); // Calculate the number of tokens to burn from founders and bounty wallet burntFounder = _founders; burntBounty = _bounty; token.reclaimAndBurn(founders, burntFounder); token.reclaimAndBurn(bounty, burntBounty); } } // File: contracts/KYCCrowdsale.sol /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * * Some implementation has been changed by Pickeringware ltd to achieve custom features */ /* * A crowdsale that allows only signed payload with server-side specified buy in limits. * * The token distribution happens as in the allocated crowdsale contract */ contract KYCCrowdsale is KYCPayloadDeserializer, PickCrowdsale { /* Server holds the private key to this address to decide if the AML payload is valid or not. */ address public signerAddress; mapping(address => uint256) public refundable; mapping(address => bool) public refunded; mapping(address => bool) public blacklist; /* A new server-side signer key was set to be effective */ event SignerChanged(address signer); event TokensReclaimed(address user, uint256 amount, uint256 datetime); event AddedToBlacklist(address user, uint256 datetime); event RemovedFromBlacklist(address user, uint256 datetime); event RefundCollected(address user, uint256 datetime); event TokensReleased(address agent, uint256 datetime, uint256 bounty, uint256 founders); /* * Constructor. */ function KYCCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _beneficiary, address _buyer, address _founders, address _bounty, uint256 _softCap, uint256 _hardCap, PickToken _token) public PickCrowdsale(_startTime, _endTime, _rate, _wallet, _beneficiary, _buyer, _founders, _bounty, _softCap, _hardCap, _token) {} // This sets the token agent to the contract, allowing the contract to reclaim and burn tokens if necessary function setTokenAgent() external onlyOwner { // contractAddr = token.owner(); // Give the sale contract rights to reclaim tokens token.setReleaseAgent(); } /* * This function was written by Pickeringware ltd to facilitate a refund action upon failure of KYC analysis * * It simply allows the participant to withdraw his ether from the sale * Moves the crowdsale sliders accordingly * Reclaims the users tokens and burns them * Blacklists the user to prevent them from buying any more tokens * * Stage 1, 2, 3, & 4 are all collected from the database prior to calling this function * It allows us to calculate how many tokens need to be taken from each individual stage */ function refundParticipant(address participant, uint256 _stage1, uint256 _stage2, uint256 _stage3, uint256 _stage4) external onlyOwner { require(balanceOf[participant] > 0); uint256 balance = balanceOf[participant]; uint256 tokens = tokenBalanceOf[participant]; balanceOf[participant] = 0; tokenBalanceOf[participant] = 0; // Refund the participant refundable[participant] = balance; // Move the crowdsale sliders weiRaised = weiRaised.sub(balance); tokensSent = tokensSent.sub(tokens); // Reclaim the participants tokens and burn them token.reclaimAllAndBurn(participant); // Blacklist participant so they cannot make further purchases blacklist[participant] = true; AddedToBlacklist(participant, now); stages.refundParticipant(_stage1, _stage2, _stage3, _stage4); TokensReclaimed(participant, tokens, now); } // Allows only the beneficiary to release tokens to people // This is needed as the token is owned by the contract, in order to mint tokens // therefore, the owner essentially gives permission for the contract to release tokens function releaseTokens(uint256 _bounty, uint256 _founders) onlyOwner external { // Unless the hardcap was reached, theremust be tokens to burn require(_bounty > 0 || tokensSent == hardCap); require(_founders > 0 || tokensSent == hardCap); burnFoundersTokens(_bounty, _founders); token.releaseTokenTransfer(); canWithdraw = true; TokensReleased(msg.sender, now, _bounty, _founders); } // overriding Crowdsale#validPurchase to add extra KYC blacklist logic // @return true if investors can buy at the moment function validPurchase(uint256 _tokens) internal view returns (bool) { bool onBlackList; if(blacklist[msg.sender] == true){ onBlackList = true; } else { onBlackList = false; } return super.validPurchase(_tokens) && !onBlackList; } // This is necessary for the blacklisted user to pull his ether from the contract upon being refunded function collectRefund() external { require(refundable[msg.sender] > 0); require(refunded[msg.sender] == false); uint256 theirwei = refundable[msg.sender]; refundable[msg.sender] = 0; refunded[msg.sender] == true; msg.sender.transfer(theirwei); RefundCollected(msg.sender, now); } /* * A token purchase with anti-money laundering and KYC checks * This function takes in a dataframe and EC signature to verify if the purchaser has been verified * on the server side of our application and has therefore, participated in KYC. * Upon registering to the site, users are supplied with a signature allowing them to purchase tokens, * which can be revoked at any time, this containst their ETH address, a unique ID and the min and max * ETH that user has stated they will purchase. (Any more than the max may be subject to AML checks). */ function buyWithKYCData(bytes dataframe, uint8 v, bytes32 r, bytes32 s) public payable { bytes32 hash = sha256(dataframe); address whitelistedAddress; uint128 customerId; uint32 minETH; uint32 maxETH; (whitelistedAddress, customerId, minETH, maxETH) = getKYCPayload(dataframe); // Check that the KYC data is signed by our server require(ecrecover(hash, v, r, s) == signerAddress); // Check that the user is using his own signature require(whitelistedAddress == msg.sender); // Check they are buying within their limits - THIS IS ONLY NEEDED IF SPECIFIED BY REGULATORS uint256 weiAmount = msg.value; uint256 max = maxETH; uint256 min = minETH; require(weiAmount < (max * 1 ether)); require(weiAmount > (min * 1 ether)); buyTokens(customerId); } /// @dev This function can set the server side address /// @param _signerAddress The address derived from server&#39;s private key function setSignerAddress(address _signerAddress) external onlyOwner { // EC rcover returns 0 in case of error therefore, this CANNOT be 0. require(_signerAddress != 0); signerAddress = _signerAddress; SignerChanged(signerAddress); } function removeFromBlacklist(address _blacklisted) external onlyOwner { require(blacklist[_blacklisted] == true); blacklist[_blacklisted] = false; RemovedFromBlacklist(_blacklisted, now); } }
This function was written by Pickeringware ltd to facilitate a refund action upon failure of KYC analysis It simply allows the participant to withdraw his ether from the sale Moves the crowdsale sliders accordingly Reclaims the users tokens and burns them Blacklists the user to prevent them from buying any more tokens Stage 1, 2, 3, & 4 are all collected from the database prior to calling this function It allows us to calculate how many tokens need to be taken from each individual stage/ Refund the participant Move the crowdsale sliders Reclaim the participants tokens and burn them Blacklist participant so they cannot make further purchases
function refundParticipant(address participant, uint256 _stage1, uint256 _stage2, uint256 _stage3, uint256 _stage4) external onlyOwner { require(balanceOf[participant] > 0); uint256 balance = balanceOf[participant]; uint256 tokens = tokenBalanceOf[participant]; balanceOf[participant] = 0; tokenBalanceOf[participant] = 0; refundable[participant] = balance; weiRaised = weiRaised.sub(balance); tokensSent = tokensSent.sub(tokens); token.reclaimAllAndBurn(participant); blacklist[participant] = true; AddedToBlacklist(participant, now); stages.refundParticipant(_stage1, _stage2, _stage3, _stage4); TokensReclaimed(participant, tokens, now); }
2,166,628
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/common/ERC2981.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./Base58.sol"; contract NftArtForUkraine is ERC2981, IERC1155, ERC1155, ReentrancyGuard, Ownable { using Strings for bytes; string private _uri; string private _contractMetadataURI; uint256 public minPrice = 5*10**16; //0.05ETH bool public mintEnabled = false; address public artManager; uint256 public totalCollected; uint256 public idCounter; mapping(uint256 => uint256) public totalSupply; mapping(uint256 => uint256) public maxSupply; mapping(uint256 => bool) public mintEnabledId; mapping(uint256 => bytes32) public idHash; bool public autoForward = true; mapping(address => bool) public approvedRecipients; address[] public approvedRecipientsList; event NewMinPrice(uint256 oldPrice, uint256 newPrice); event Forwarded(address to, uint256 amount); event NewArt(uint256 id, bytes hash); event Rescued(address token, uint256 amount, address to); event MintingEnabled(bool enable); event MintingEnabledId(uint256 id, bool enable); event Contributed(address from, uint256 amount); constructor(string memory uri_, string memory contractMetadataURI) ERC1155(uri_) { artManager = msg.sender; _uri = uri_; _contractMetadataURI = contractMetadataURI; address recipient = 0x1D45c8fa65F6b18E7dAe04b2efEa332c55696DaA; _setDefaultRoyalty(recipient, 1000); approvedRecipients[recipient] = true; approvedRecipientsList.push(recipient); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC2981, IERC165) returns (bool) { return interfaceId == type(ERC2981).interfaceId || interfaceId == type(IERC1155).interfaceId || super.supportsInterface(interfaceId); } /** * @notice Reverts if the ID does not exist * @param id Token id */ function idExists(uint256 id) internal view { require(idHash[id] != 0, "Provided ID does not exist"); } /** * @notice Allows artManager to add new art piece to the contract * @param hashes Array of IPFS CIDs for metadata representing the art pieces * @return uint256[] Array of newly added ids */ function newArt(bytes[] memory hashes) external onlyArtManager returns (uint256[] memory) { require(hashes.length > 0, "No new art to add"); uint256[] memory result = new uint256[](hashes.length); for(uint256 i=0; i<hashes.length; i++) { uint256 _id = idCounter; bytes memory tmpHash = hashes[i]; bytes32 tmp; assembly { tmp := mload(add(add(tmpHash, 2), 32)) } idHash[_id] = tmp; mintEnabledId[_id] = true; result[i] = _id; idCounter++; emit NewArt(_id, tmpHash); } return result; } /** * @notice Mints given amount of specific art pieces to sender address * @param id Art piece ID * @param amount Amount of tokens to mint */ function mint(uint256 id, uint256 amount, address[] memory to) external payable nonReentrant { require(mintEnabled, "Minting disabled"); idExists(id); require(mintEnabledId[id], "Minting disabled for id"); require(msg.value >= amount * minPrice, "Not enough ETH sent"); uint256 _maxSupply = maxSupply[id]; require(_maxSupply == 0 || _maxSupply > totalSupply[id], "Max supply reached"); totalSupply[id] += amount; totalCollected += msg.value; _mint(msg.sender, id, amount, ""); if (autoForward) { _forwardMulti(to, msg.value); } emit Contributed(msg.sender, msg.value); } /** * @notice Mints art pieces in batch * @param ids Array of art piece IDs to mint * @param amounts Array of amounts of tokens to mint */ function mintBatch( uint256[] memory ids, uint256[] memory amounts, address[] memory to, bytes memory data ) external payable nonReentrant { require(mintEnabled, "Minting disabled"); uint256 totalAmount; for(uint256 i=0; i<amounts.length; i++) { uint256 id = ids[i]; totalAmount += amounts[i]; idExists(id); uint256 _maxSupply = maxSupply[id]; require(_maxSupply == 0 || _maxSupply > totalSupply[id], "Max supply reached"); require(mintEnabledId[id], "Minting disabled for id"); totalSupply[ids[i]] += amounts[i]; } require(msg.value >= totalAmount * minPrice, "Not enough ETH sent"); totalCollected += msg.value; _mintBatch(msg.sender, ids, amounts, data); if (autoForward) { _forwardMulti(to, msg.value); } emit Contributed(msg.sender, msg.value); } /** * @notice Public wrapper of _forward method * @param to recipient address (must be in approvedRecipients) * @param amount amount of ETH to send */ function forward(address to, uint256 amount) public onlyOwner { _forward(to, amount); } /** * @notice Transfers given amount to a given address if the address is approved * @param to recipient address (must be in approvedRecipients) * @param amount amount of ETH to send */ function _forward(address to, uint256 amount) internal { require(approvedRecipients[to], "Not a valid recipient"); require(address(this).balance >= amount, "Not enough ETH"); payable(to).transfer(amount); emit Forwarded(to, amount); } /** * @notice Forward given ETH value equally to multiple approved addresses * @param to List of recipients * @param amount amount of ETH to forward */ function _forwardMulti(address[] memory to, uint256 amount) internal { uint256 toForward = amount / to.length; for(uint256 i=0; i<to.length; i++) { if(i == to.length - 1) { uint256 rest = amount - toForward*to.length; toForward += rest; } _forward(to[i], toForward); } } /** * @notice Splits contract ETH balance among the list of addresses based on given portions * @param recipients Array of recipient addresses * @param portions Array of portions to transfer to recipients in percent (sum must be <= 100) */ function split(address[] memory recipients, uint256[] memory portions) external onlyOwner nonReentrant { require(recipients.length == portions.length, "Recipients and portions do not match"); uint256 sum; for(uint256 i=0; i<portions.length; i++) { sum += portions[i]; } require(sum <= 100, "Cannot distribute more than 100%"); uint256 balance = address(this).balance; for(uint256 i=0; i<recipients.length; i++) { uint256 toSend = balance * portions[i] / 100; _forward(recipients[i], toSend); } } /** * @notice Sets an address is approved recipient * @param to Address to configure * @param enable Whether the address is approved */ function setApprovedRecipient(address to, bool enable) external onlyOwner { require(approvedRecipients[to] != enable, "Already configured"); require(to != address(0), "Cannot approve 0 address"); approvedRecipients[to] = enable; if(enable) { approvedRecipientsList.push(to); } else { for(uint256 i=0; i<approvedRecipientsList.length; i++) { if(approvedRecipientsList[i] == to) { approvedRecipientsList[i] = approvedRecipientsList[approvedRecipientsList.length-1]; approvedRecipientsList.pop(); break; } } } } /** * @notice Sets minimal price per token * @param amount Minimal price in wei (10**18) */ function setMinPrice(uint256 amount) external onlyOwner { require(amount > 0, "Min price cannot be 0"); uint256 oldPrice = minPrice; minPrice = amount; emit NewMinPrice(oldPrice, minPrice); } /** * @notice Sets the art manager * @param account Address to be used as art manager */ function setArtManager(address account) external onlyOwner { require(account != address(0), "Address 0"); artManager = account; } /** * @notice Enable/Disable minting for whole collection * @param enable Whether the minting is enable or not */ function setMintEnabled(bool enable) external onlyOwner { mintEnabled = enable; emit MintingEnabled(enable); } /** * @notice Enable/Disable minting for given token id * @param id Token id * @param enable Whether the minting is enabled or not */ function setMintEnabledForId(uint256 id, bool enable) external onlyArtManager { idExists(id); mintEnabledId[id] = enable; emit MintingEnabledId(id, enable); } /** * @notice Sets maximum supply for given token id * @param id Token id * @param max Maximum supply */ function setMaxSupply(uint256 id, uint256 max) external onlyArtManager { idExists(id); maxSupply[id] = max; } /** * @notice Enable/Disable automatic forwarding of ETH to */ function setAutoForward(bool enable) external onlyOwner { require(autoForward != enable, "Already set"); autoForward = enable; } /** * @notice Allows rescuing ERC20 tokens from the contract * @param token Token address * @param to Recipient address */ function rescueTokens(address token, address to) external onlyOwner nonReentrant { require(token != address(0), "Nothing to rescue"); uint256 amount = IERC20(token).balanceOf(address(this)); if (amount > 0) { require(IERC20(token).transfer(to, amount), "Transfer failed"); } emit Rescued(token, amount, to); } /** * @notice Generates full IPFS CID from stored bytes32 part * @param id Token id */ function getHash(uint256 id) public view returns (bytes memory) { bytes32 hash = idHash[id]; require(hash != 0, "Incorrect ID"); uint8 x = 0x12; uint8 y = 0x20; return abi.encodePacked(x, y, hash); } /** * @notice Constructs and returns URI to token metadata on IPFS * @param id Token id * @return string URI to metadata.json*/ function uri(uint256 id) public view override returns(string memory) { bytes memory hash = getHash(id); return string(abi.encodePacked(_uri, Base58.toBase58(hash), "/metadata.json")); } struct TokenInfo { string uri; bool mintable; uint256 maxSupply; uint256 totalSupply; } /** * @notice Get URIs for all tokens * returns string[] Array of URIs */ function getInfo() external view returns(TokenInfo[] memory) { TokenInfo[] memory info = new TokenInfo[](idCounter); for(uint256 i=0; i<idCounter; i++) { info[i].maxSupply = maxSupply[i]; info[i].uri = uri(i); info[i].totalSupply = totalSupply[i]; info[i].mintable = mintEnabledId[i]; } return info; } function getApprovedRecipients() external view returns(address[] memory) { return approvedRecipientsList; } function contractURI() public view returns (string memory) { return _contractMetadataURI; } modifier onlyArtManager() { require(msg.sender == artManager, "Not the art manager"); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol) pragma solidity ^0.8.0; import "../../interfaces/IERC2981.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information. * * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the * fee is specified in basis points by default. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC2981 is IERC2981, ERC165 { struct RoyaltyInfo { address receiver; uint96 royaltyFraction; } RoyaltyInfo private _defaultRoyaltyInfo; mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @inheritdoc IERC2981 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view virtual override returns (address, uint256) { RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId]; if (royalty.receiver == address(0)) { royalty = _defaultRoyaltyInfo; } uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator(); return (royalty.receiver, royaltyAmount); } /** * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an * override. */ function _feeDenominator() internal pure virtual returns (uint96) { return 10000; } /** * @dev Sets the royalty information that all ids in this contract will default to. * * Requirements: * * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: invalid receiver"); _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Removes default royalty information. */ function _deleteDefaultRoyalty() internal virtual { delete _defaultRoyaltyInfo; } /** * @dev Sets the royalty information for a specific token id, overriding the global default. * * Requirements: * * - `tokenId` must be already minted. * - `receiver` cannot be the zero address. * - `feeNumerator` cannot be greater than the fee denominator. */ function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator ) internal virtual { require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice"); require(receiver != address(0), "ERC2981: Invalid parameters"); _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator); } /** * @dev Resets royalty information for the token id back to the global default. */ function _resetTokenRoyalty(uint256 tokenId) internal virtual { delete _tokenRoyaltyInfo[tokenId]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Base58 { /// @dev Converts hex string to base 58 function toBase58(bytes memory source) internal pure returns (bytes memory) { if (source.length == 0) return new bytes(0); uint8[] memory digits = new uint8[](64); //TODO: figure out exactly how much is needed digits[0] = 0; uint8 digitlength = 1; for (uint256 i = 0; i<source.length; ++i) { uint carry = uint8(source[i]); for (uint256 j = 0; j<digitlength; ++j) { carry += uint(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } //return digits; return toAlphabet(reverse(truncate(digits, digitlength))); } function truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](length); for (uint256 i = 0; i<length; i++) { output[i] = array[i]; } return output; } function reverse(uint8[] memory input) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](input.length); for (uint256 i = 0; i<input.length; i++) { output[i] = input[input.length-1-i]; } return output; } bytes constant ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; function toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) { bytes memory output = new bytes(indices.length); for (uint256 i = 0; i<indices.length; i++) { output[i] = ALPHABET[indices[i]]; } return output; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: 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. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
Sets the art manager account Address to be used as art manager/
function setArtManager(address account) external onlyOwner { require(account != address(0), "Address 0"); artManager = account; }
14,453,256
./full_match/1/0xc1374b803DFb1A9c87eaB9e76929222DBa3a8C39/sources/contracts/lazy-forge/NiftyIslandCreations.sol
Retrieve the total burned supply for a token id _id token id/
function totalBurnedSupply(uint256 _id) public view returns (uint256) { return _burned[_id]; }
3,070,473
./partial_match/56/0x128c0A35a70E184484cD49fa7c3e26626Fd81f66/sources/MasterChef.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMousePerShare: 0, depositFeeBP: _depositFeeBP })); }
11,104,487
./partial_match/3/0xd15693E50DCFd6d2A3D93729ED2b9C49C152eF9c/sources/SwanMasterFarmer.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/
{ require(blockNumber < block.number, "SWAN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; function delegates(address delegator) external view returns (address) } } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external } function getCurrentVotes(address account) external view returns (uint256) } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } else if (cp.fromBlock < blockNumber) { } else { }
5,076,820
./partial_match/56/0xA4a7ab8a4Bc413F3f81Ac894430537dBa12Ab816/sources/StrategyKebabLP.sol
Swaps {kebab} for {lpToken0}, {lpToken1} & {wbnb} using PancakeSwap./
function addLiquidity() internal { uint256 kebabHalf = IERC20(kebab).balanceOf(address(this)).div(2); if (lpToken0 != kebab) { IPancakeRouter(unirouter).swapExactTokensForTokens(kebabHalf, 0, kebabToLp0Route, address(this), now.add(600)); } if (lpToken1 != kebab) { IPancakeRouter(unirouter).swapExactTokensForTokens(kebabHalf, 0, kebabToLp1Route, address(this), now.add(600)); } uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IPancakeRouter(unirouter).addLiquidity(lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now.add(600)); }
11,098,609
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; /// @title Witnet Request Board basic administration interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardAdmin { event OwnershipTransferred(address indexed from, address indexed to); /// Gets admin/owner address. function owner() external view returns (address); /// Transfers ownership. function transferOwnership(address) external; }
Witnet Request Board basic administration interface. The Witnet Foundation.
interface IWitnetRequestBoardAdmin { event OwnershipTransferred(address indexed from, address indexed to); function owner() external view returns (address); function transferOwnership(address) external; }
5,420,114
./full_match/40/0x48EFAf072b75BB0EDc20B3eeB4FA37a5Bb61d7Bd/sources/scripts/Generator/DeployContracts/Test1.sol
withdraw ether from contract. only owner function
function withdraw() public payable onlyOwner { require(os); }
9,545,117
./full_match/1/0xe1272adbf95FA29ab6aC9Cd8bF2D5462BCD766B3/sources/contracts/cash/CashManager.sol
Override admin function for changing the representation of the amount of collateral a user has deposited to kick off minting process user The user whose balance is being set epoch The epoch in which to set user balance for oldBalance The user's previous balance newBalance The user's new balance to set `oldBalance` is provided to prevent front running attacks where a user could attempt to claim before and after this is set./
function setPendingMintBalance( address user, uint256 epoch, uint256 oldBalance, uint256 newBalance ) external updateEpoch onlyRole(MANAGER_ADMIN) { if (oldBalance != mintRequestsPerEpoch[epoch][user]) { revert UnexpectedMintBalance(); } if (epoch > currentEpoch) { revert CannotServiceFutureEpoch(); } mintRequestsPerEpoch[epoch][user] = newBalance; emit PendingMintBalanceSet(user, epoch, oldBalance, newBalance); }
17,003,321
pragma solidity >=0.8.0 <0.9.0; import "../openzeppelin/Safemath.sol"; import "./FriendRegistry.sol"; import "../utility/StakePool.sol"; import "hardhat/console.sol"; contract Freelancer { using SafeMath for uint256; using SafeMath for uint32; // Use MAX_UINT to signify null uint value uint256 constant MAX_UINT = 2**256 - 1; //Default stake allocation = 5% of earned amount uint256 constant DEFAULT_STAKE_ALLOCATION = 5; // Null bytes32 values bytes32 constant NULL = ""; /** * @dev freelancer properties **/ struct FreelancerMetadata { uint16 jobsWorked; bool isAvailable; bool isInitialized; } /** * @dev freelancer financials **/ struct FreelancerFinancials { uint256 totalEarned; uint256 forgoneEarnings; uint256 stakeAllocation; uint256 totalUnpaid; } address[] freelancers; mapping(address => FreelancerMetadata) public freelancerToMetadata; mapping(address => FreelancerFinancials) public freelancerToFinancials; mapping(address => StakePool) public freelancerToStakePool; event FreelancerInit(FreelancerMetadata freelancerMetadata); event Slashed(address freelancer, address to, uint256 amount); FriendRegistry friendRegistry; address tokenAddress; constructor(address _friendRegistry, address _tokenAddress) { friendRegistry = FriendRegistry(_friendRegistry); tokenAddress = _tokenAddress; } modifier ifAvailable(address freelancer) { require( freelancerToMetadata[freelancer].isAvailable == true, "freelancer is not available" ); _; } modifier onlyFriend(address contractAddress) { require( friendRegistry.isFriend(contractAddress) == true, "Contract is not a friend contract" ); _; } modifier onlyIfFreelancerExists(address freelancerAddress) { require( freelancerToMetadata[freelancerAddress].isInitialized == true, "Freelancer doesnt exist" ); _; } /** * @dev Sets a freelancer's stake allocation called by freelancer. **/ function setMyAllocation(uint256 allocation) external { freelancerToFinancials[msg.sender].stakeAllocation = allocation; } /** * @dev Sets a freelancer's stake allocation called by a friend contract. **/ function setFreelancerAllocation(address freelancer, uint256 allocation) external onlyIfFreelancerExists(freelancer) onlyFriend(msg.sender) { freelancerToFinancials[freelancer].stakeAllocation = allocation; } /** * @dev Sets a freelancer's total number of jobs worked. * - Must be called by logic contracts upon completion of a job and can only be set if logic contract has access to set it * @param freelancer The address of the freelancer whose rating needs to be updated **/ function incrementJobsWorked(address freelancer) external onlyFriend(msg.sender) { freelancerToMetadata[freelancer].jobsWorked++; } /** * @dev Sets a freelancer's availability. * - Must be called by logic contracts upon completion or beginning of a job and can only be set if logic contract has access to set it * @param freelancer The address of the freelancer whose rating needs to be updated * @param isAvailable Availability set to true or false **/ function setAvailability(address freelancer, bool isAvailable) external onlyFriend(msg.sender) { freelancerToMetadata[freelancer].isAvailable = isAvailable; } /** * @dev Adds to a freelancer's stake pool called by freelancer. **/ function addToMyStake(uint256 amount) external onlyIfFreelancerExists(msg.sender) { freelancerToStakePool[msg.sender].stake(amount); } /** * @dev Adds to a freelancer's stake pool called by freelancer. **/ function addToFreelancerStake(address freelancer, uint256 amount) external onlyIfFreelancerExists(freelancer) onlyFriend(msg.sender) { freelancerToStakePool[freelancer].stake(amount); } /** * @dev Reduce a freelancer's stake pool called by freelancer. **/ function reduceMyStake(uint256 amount) external onlyIfFreelancerExists(msg.sender) { freelancerToStakePool[msg.sender].unstake(amount); } /** * @dev Adds to a freelancer's stake pool called by freelancer. **/ function lockFreelancerStake(address freelancer, uint256 amount) external onlyIfFreelancerExists(freelancer) onlyFriend(msg.sender) { freelancerToStakePool[freelancer].lock(amount); } /** * @dev Adds to a freelancer's stake pool called by freelancer. **/ function unlockFreelancerStake(address freelancer, uint256 amount) external onlyIfFreelancerExists(freelancer) onlyFriend(msg.sender) { freelancerToStakePool[freelancer].unlock(amount); } /** * @dev Sets a freelancer's stake allocation called by freelancer. **/ function addToFreelancerEarned(address freelancer, uint256 amount) external onlyIfFreelancerExists(freelancer) onlyFriend(msg.sender) { freelancerToFinancials[freelancer].totalEarned = amount; } /** * @dev Sets a freelancer's stake allocation called by freelancer. **/ function addToFreelancerForgoneEarnings(address freelancer, uint256 amount) external onlyIfFreelancerExists(freelancer) onlyFriend(msg.sender) { freelancerToFinancials[freelancer].forgoneEarnings = amount; } /** * @dev Initialize a freelancer's metadata. * - Called by createfreelancerIfFirstTime when a freelancer picks up his first job or stakes his tokens for the first time * @param freelancer The address of the new freelancer **/ function initializeFreelancerMetadataIfFirstTime(address freelancer) external onlyFriend(msg.sender) { if (freelancerToMetadata[freelancer].isInitialized == false) { freelancerToMetadata[freelancer] = FreelancerMetadata( 0, true, true ); freelancerToFinancials[freelancer] .stakeAllocation = DEFAULT_STAKE_ALLOCATION; freelancerToStakePool[freelancer] = new StakePool( freelancer, tokenAddress ); freelancers.push(freelancer); emit FreelancerInit(freelancerToMetadata[freelancer]); } } /** * @dev Slash a freelancer's locked stake **/ function slashLockedStake( address freelancer, address to, uint256 amount ) external onlyFriend(msg.sender) { freelancerToStakePool[freelancer].unlock(amount); freelancerToStakePool[freelancer].unstake(amount); freelancerToStakePool[freelancer].slash(amount, to); emit Slashed(freelancer, to, amount); } /** * @dev Gets a freelancer's total earnings called by freelancer. **/ function getFreelancerEarned(address freelancer) external view returns (uint256) { return freelancerToFinancials[freelancer].totalEarned; } /** * @dev Gets a freelancer's total earnings called by freelancer. **/ function getFreelancerForgoneEarnings(address freelancer) external view returns (uint256) { return freelancerToFinancials[freelancer].forgoneEarnings; } /** * @dev Gets a freelancer by address. **/ function getFreelancerMetadata(address freelancer) external view returns (FreelancerMetadata memory) { return freelancerToMetadata[freelancer]; } /** * @dev Gets a freelancer by address. **/ function getFreelancerAllocation(address freelancer) external view returns (uint256) { return freelancerToFinancials[freelancer].stakeAllocation; } /** * @dev Gets a freelancer by address. **/ function getFreelancerStake(address freelancer) external view returns (uint256) { return freelancerToStakePool[freelancer].getOwnerStake(); } /** * @dev Gets a freelancer by address. **/ function getFreelancerLockedStake(address freelancer) external view returns (uint256) { return freelancerToStakePool[freelancer].getLockedStake(); } function selfInitializeFreelancerMetadata() external { if (freelancerToMetadata[msg.sender].isInitialized == false) { freelancerToMetadata[msg.sender] = FreelancerMetadata( 0, true, true ); freelancerToFinancials[msg.sender] .stakeAllocation = DEFAULT_STAKE_ALLOCATION; freelancerToStakePool[msg.sender] = new StakePool( msg.sender, tokenAddress ); freelancers.push(msg.sender); emit FreelancerInit(freelancerToMetadata[msg.sender]); } } }
Sets a freelancer's availability. - Must be called by logic contracts upon completion or beginning of a job and can only be set if logic contract has access to set it freelancer The address of the freelancer whose rating needs to be updated isAvailable Availability set to true or false/
function setAvailability(address freelancer, bool isAvailable) external onlyFriend(msg.sender) { freelancerToMetadata[freelancer].isAvailable = isAvailable; }
7,320,107
./partial_match/1/0x860aCd0f9E6436E15407977602bf11fD39db29f1/sources/Dubai1764.sol
Change Price functions for Diamond Tier
function changeUSDTPriceDiamond(uint256 usdtPrice) public onlyOwner { priceUSDTDiamond = usdtPrice; }
16,136,227
// File: contracts\SmartTreasuryV3FragmentPWC.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /////////////////////////////////////////////////////////////////////////// // __/| // __/ // /| This smart contract is part of Mover infrastructure // |/ //_/// https://viamover.com // |_/ // // |/ /////////////////////////////////////////////////////////////////////////// /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(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)); } } /** * @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); } } } } /** * @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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** * @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 AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, 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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @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); } /** * _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); } /** * @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 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; } /** * @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(0).onERC1155Received.selector ^ ERC1155ReceiverUpgradeable(0).onERC1155BatchReceived.selector ); } uint256[50] private __gap; } /** Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface IERC1155Powercard { /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; } // SmartTreasury PowerCard Fragment // this is deployed as a separate contract (with it's own state related to PowerCard) // it is stand-alone and upgradeable contract SmartTreasuryFragmentPWC is Initializable, AccessControlUpgradeable, ERC1155ReceiverUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; // role that grants most of financial operations for Treasury (tresholds, etc.) bytes32 public constant FINMGMT_ROLE = keccak256("FINMGMT_ROLE"); // allowed to set tresholds and perform rebalancing // special values for PWC search for address (any numbers larger than 21 powercard minted) uint256 constant POWERCARD_NOT_FOUND = 32768; // PowerCard not found in staked info uint256 constant POWERCARD_UNSTAKE_LOCK = 32769; // PowerCard was unstaked, but is still in cooldown // probably these would remain constants, but made public to be accessible from view functions for convenience uint256 public POWERCARD_ACTIVE_PERIOD; // = 2592000; // 30 days uint256 public POWERCARD_COOLDOWN_PERIOD; // = 5184000; // 60 days // actual PWC (Semi-)NFT ERC1155 parameters address private PWCAddress; // address of ERC1155 PowerCard contract 0xd07dc4262BCDbf85190C01c996b4C06a461d2430; uint256 constant PWC_ID = 107150; // ID of PowerCard contract //https://docs.soliditylang.org/en/v0.6.2/miscellaneous.html //Use shorter types for struct elements and sort them such that short types are grouped together. // in theory, this 28-bytes struct element could be packed as less than uint256 bits (64 bytes) // there are 21 PowerCard NFTs in total struct NFTStake { uint32 timestamp; // 4-byte (32 bits) address staker; // 20-byte (160 bits) uint32 tsUnstaked; // 4-byte (32 bits) so after unstaking address cannot immediately stake again // (but other address can, we currently don't think this would be abused, as ST stake should also be moved) } event PowercardStake(address account); event PowercardUnstake(address account); // staking data storage array NFTStake[] public nft_stakes; function initialize() public initializer { __Context_init_unchained(); __AccessControl_init_unchained(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(FINMGMT_ROLE, _msgSender()); } // set address for PWC contract function setPowercardAddress(address _address) public { require(hasRole(FINMGMT_ROLE, msg.sender), "finmgmt only"); PWCAddress = _address; } // set active and cooldown periods for powercard staking (in seconds) function setPowercardParams(uint256 _active, uint256 _cooldown) public { require(hasRole(FINMGMT_ROLE, msg.sender), "finmgmt only"); POWERCARD_ACTIVE_PERIOD = _active; POWERCARD_COOLDOWN_PERIOD = _cooldown; } // returns timestamp when the address that recently unstaked could stake again // (the lock period is for the address, not the card) function unstakeLockTimestamp(uint256 _stakeTS, uint256 _unstakeTS) view internal returns(uint256) { return _unstakeTS.sub(_stakeTS).div(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD).add(1).mul(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD).add(_stakeTS); } // return true if a staked at a specific timestamp powercard has active effect now function isPowerCardActive(uint _tsStaked) view public returns(bool) { if (block.timestamp.sub(_tsStaked).mod(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD) < POWERCARD_ACTIVE_PERIOD) { return true; } return false; } // return true if a staked at a specific timestamp powercard is on cooldown now function isPowerCardCooldown(uint _tsStaked) view public returns(bool) { if (block.timestamp.sub(_tsStaked).mod(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD) >= POWERCARD_ACTIVE_PERIOD) { return true; } return false; } // get remaining time (in seconds) for the specific powercard effect function getRemainingTimingsInt(uint _tsStaked) view internal returns(uint256 active, uint256 cooldown) { if (isPowerCardActive(_tsStaked)) { active = POWERCARD_ACTIVE_PERIOD.sub(block.timestamp.sub(block.timestamp.sub(_tsStaked).div(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD).mul(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD).add(_tsStaked))); //cooldown = 0;' } else { //active = 0; cooldown = block.timestamp.sub(_tsStaked).div(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD).add(1).mul(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD).add(_tsStaked).sub(block.timestamp); } } function getRemainingTimings(address _staker) view public returns(uint256 active, uint256 cooldown) { return getRemainingTimingsInt(nft_stakes[getPowercardIndex(_staker)].timestamp); } // return index of a Powercard staked for an address (if found) // returns POWERCARD_NOT_FOUND if index not found // unstaked powercards are skipped function getPowercardIndex(address _owner) view public returns(uint256) { for (uint256 i = 0; i < nft_stakes.length; i++) { if (nft_stakes[i].staker == _owner) { if (nft_stakes[i].tsUnstaked == 0) { return i; } else if (block.timestamp < unstakeLockTimestamp(nft_stakes[i].timestamp, nft_stakes[i].tsUnstaked)) { return POWERCARD_UNSTAKE_LOCK; } } } return POWERCARD_NOT_FOUND; } ////////////////////////////////////////////////////////////////////////////// // Stake/unstake of PowerCard ////////////////////////////////////////////////////////////////////////////// // stake PowerCard, making it active for a period (and locking down for that period) // requires approval, transfers PWC to the contract address function stakePowercard() public { // as staked card can only be unstaked after active period passes, this provides // spoof-protection (so PWC could not be transferred across addresses and re-staked, // increasing array size, however, if all owners unstake and transfer cards to different // addresses immediately after active period and restake, then repeat, maximal size of // array before sweeping would be 63 records) require(nft_stakes.length < 63, "too much staking activity"); sweepNFTArray(); // check that this address has no powercards staked (no multiple stakes) // check when restaking card from same address when record is present in array uint256 index = this.getPowercardIndex(msg.sender); require(index != POWERCARD_UNSTAKE_LOCK, "recently unstaked cooldown"); require(index == POWERCARD_NOT_FOUND, "already staked"); //NOTE: we don't check allowance and balance (it would revert on transfer) //NOTE: this contract must implement the ERC1155Receiver interface IERC1155Powercard(PWCAddress).safeTransferFrom(msg.sender, address(this), PWC_ID, 1, ""); NFTStake memory stake = NFTStake(uint32(block.timestamp), msg.sender, 0); nft_stakes.push(stake); emit PowercardStake(msg.sender); } // PowerCard could be unstaked only by its owner, and only during cooldown period // in such case, user gets card back on his wallet balance function unstakePowercard() public { uint256 index = this.getPowercardIndex(msg.sender); require(index != POWERCARD_NOT_FOUND, "not staked"); require(!this.isPowerCardActive(nft_stakes[index].timestamp), "only on cooldown"); // make unstaked timestamp mark nft_stakes[index].tsUnstaked = uint32(block.timestamp); // transfer one powercard from ST contract to user IERC1155Powercard(PWCAddress).safeTransferFrom(address(this), msg.sender, PWC_ID, 1, ""); emit PowercardUnstake(msg.sender); } // remove NFT cards from array that were unstaked and cooldown has passed (could be called publicly) function sweepNFTArray() public { uint256 to_remove = 0; for (uint256 i = 0; i < nft_stakes.length - to_remove; i++) { // when card 'is active' by period calculation, but was unstaked, we can remove this record from array if(nft_stakes[i].tsUnstaked > 0 && block.timestamp >= unstakeLockTimestamp(nft_stakes[i].timestamp, nft_stakes[i].tsUnstaked)) { nft_stakes[i] = nft_stakes[nft_stakes.length - to_remove - 1]; to_remove++; } } //nft_stakes.length -= to_remove; // Implicitly recovers gas from last elements storage // in current solidity versions resizing arrays through modifying lenth is not supported for (uint256 i = 0; i < to_remove; i++) { nft_stakes.pop(); } } ////////////////////////////////////////////////////////////////////////////// // ERC1155 receiver interface ////////////////////////////////////////////////////////////////////////////// function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external override returns(bytes4) { return 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) } function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external override returns(bytes4) { return 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) } ////////////////////////////////////////////////////////////////////////////// // Calculation functions used by Smart Treasury contract ////////////////////////////////////////////////////////////////////////////// // getActiveNFTstakers is used by main Smart Treasury contract to // return addresses list with active staked PowerCard (21 address max) // such addresses are having increased yield (calculated by ST) function getActiveNFTstakers() public view returns (address[] memory, uint256) { uint length = 0; address[] memory stakers = new address[](21); for (uint256 index = 0; index < nft_stakes.length; index++) { if (nft_stakes[index].tsUnstaked == 0 && this.isPowerCardActive(nft_stakes[index].timestamp)) { stakers[length] = nft_stakes[index].staker; length++; } } return (stakers, length); } }
return true if a staked at a specific timestamp powercard is on cooldown now
function isPowerCardCooldown(uint _tsStaked) view public returns(bool) { if (block.timestamp.sub(_tsStaked).mod(POWERCARD_ACTIVE_PERIOD + POWERCARD_COOLDOWN_PERIOD) >= POWERCARD_ACTIVE_PERIOD) { return true; } return false; }
1,368,528
pragma solidity 0.5.15; import "ROOT/IAugur.sol"; import "ROOT/ISimpleDex.sol"; import "ROOT/CashSender.sol"; import "ROOT/libraries/token/IERC20.sol"; import "ROOT/libraries/token/VariableSupplyToken.sol"; import "ROOT/libraries/Initializable.sol"; import "ROOT/libraries/ReentrancyGuard.sol"; import "ROOT/libraries/math/SafeMathUint256.sol"; contract BaseSimpleDex is Initializable, ReentrancyGuard, VariableSupplyToken, CashSender { using SafeMathUint256 for uint256; string constant public name = "Simple Decentralized Exchange"; string constant public symbol = "SDE"; IAugur public augur; address public token; uint256 public tokenReserve; uint256 public cashReserve; uint256 public blockNumberLast; uint256 public tokenPriceCumulativeLast; event Mint(address indexed sender, uint256 tokenAmount, uint256 cashAmount); event Burn(address indexed sender, uint256 tokenAmount, uint256 cashAmount, address indexed to); event Swap(address indexed sender, address indexed tokenIn, uint256 amountIn, uint256 amountOut, address indexed to); event Sync(uint256 tokenReserve, uint256 cashReserve); function initializeInternal(address _augurAddress, address _token) internal { endInitialization(); IAugur _augur = IAugur(_augurAddress); augur = _augur; token = _token; initializeCashSender(_augur.lookup("DaiVat"), _augur.lookup("Cash")); require(cash != IERC20(0)); } function transferToken(address _to, uint256 _value) private; function getTokenBalance() public returns (uint256); function transferCash(address _to, uint _value) private { cashTransfer(_to, _value); } function getCashBalance() public view returns (uint256) { return cashBalance(address(this)); } function update(uint256 _tokenBalance, uint256 _cashBalance) internal { uint256 _blockNumber = block.number; uint256 _blocksElapsed = _blockNumber - blockNumberLast; uint256 _cashReserve = cashReserve; uint256 _tokenReserve = tokenReserve; if (_tokenReserve != 0 && _cashReserve != 0 && _blocksElapsed > 0) { // cannot reasonably overflow unless the supply of Cash, REP, or ETH became several OOM larger uint256 _priceCumulativeIncrease = _cashReserve.mul(10**18).mul(_blocksElapsed).div(_tokenReserve); onUpdate(_blocksElapsed, _priceCumulativeIncrease); tokenPriceCumulativeLast += _priceCumulativeIncrease; } tokenReserve = _tokenBalance; cashReserve = _cashBalance; blockNumberLast = _blockNumber; emit Sync(_tokenBalance, _cashBalance); } function onUpdate(uint256 _blocksElapsed, uint256 _priceCumulativeIncrease) internal; function publicMint(address _to) public nonReentrant returns (uint256 _liquidity) { uint256 _tokenBalance = getTokenBalance(); uint256 _cashBalance = getCashBalance(); uint256 _tokenReserve = tokenReserve; uint256 _cashReserve = cashReserve; uint256 _totalSupply = totalSupply; uint256 _tokenAmount = _tokenBalance.sub(_tokenReserve); uint256 _cashAmount = _cashBalance.sub(_cashReserve); _liquidity = _totalSupply == 0 ? _tokenAmount.mul(_cashAmount).sqrt() : (_tokenAmount.mul(_totalSupply) / _tokenReserve).min(_cashAmount.mul(_totalSupply) / _cashReserve); require(_liquidity > 0, "Insufficient liquidity"); mint(_to, _liquidity); update(_tokenBalance, _cashBalance); emit Mint(msg.sender, _tokenAmount, _cashAmount); } function publicBurnAuto(address _to, uint256 _amount) external returns (uint256 _tokenAmount, uint256 _cashAmount) { transferFrom(msg.sender, address(this), _amount); publicBurn(_to); } function publicBurn(address _to) public nonReentrant returns (uint256 _tokenAmount, uint256 _cashAmount) { uint256 _liquidity = balances[address(this)]; uint256 _totalSupply = totalSupply; _tokenAmount = _liquidity.mul(tokenReserve) / _totalSupply; _cashAmount = _liquidity.mul(cashReserve) / _totalSupply; require(_tokenAmount > 0 && _cashAmount > 0, "Insufficient liquidity"); burn(address(this), _liquidity); transferToken(_to, _tokenAmount); transferCash(_to, _cashAmount); update(getTokenBalance(), getCashBalance()); emit Burn(msg.sender, _tokenAmount, _cashAmount, _to); } function getTokenSaleProceeds(uint256 _tokenAmount) public view returns (uint256) { return getSaleProceeds(_tokenAmount, tokenReserve, cashReserve); } function getCashSaleProceeds(uint256 _cashAmount) public view returns (uint256) { return getSaleProceeds(_cashAmount, cashReserve, tokenReserve); } function getSaleProceeds(uint256 _inputAmount, uint256 _inputReserve, uint256 _outputReserve) public pure returns (uint256) { require(_inputReserve > 0 && _outputReserve > 0, "inputReserve & outputReserve must be > 0"); uint256 _amountInputWithFee = _inputAmount.mul(997); uint256 _numerator = _amountInputWithFee.mul(_outputReserve); uint256 _denominator = _inputReserve.mul(1000).add(_amountInputWithFee); return _numerator / _denominator; } function getTokenPurchaseCost(uint256 _tokenAmount) public view returns (uint256) { return getPurchaseCost(_tokenAmount, cashReserve, tokenReserve); } function getCashPurchaseCost(uint256 _cashAmount) public view returns (uint256) { return getPurchaseCost(_cashAmount, tokenReserve, cashReserve); } function getPurchaseCost(uint256 _outputAmount, uint256 _inputReserve, uint256 _outputReserve) public pure returns (uint256) { require(_inputReserve > 0 && _outputReserve > 0, "inputReserve & outputReserve must be > 0"); uint256 _numerator = _outputAmount.mul(_inputReserve).mul(1000); uint256 _denominator = _outputReserve.sub(_outputAmount).mul(997); return _numerator / _denominator; } function autoSellToken(address _recipient, uint256 _tokenAmount) external payable returns (uint256 _cashAmount); function sellToken(address _recipient) public nonReentrant returns (uint _cashAmount) { uint256 _tokenBalance = getTokenBalance(); uint256 _tokenAmount = _tokenBalance.sub(tokenReserve); _cashAmount = getTokenSaleProceeds(_tokenAmount); require(_cashAmount > 0, "cashAmount must be > 0"); transferCash(_recipient, _cashAmount); update(_tokenBalance, getCashBalance()); emit Swap(msg.sender, token, _tokenAmount, _cashAmount, _recipient); } function autoBuyToken(address _recipient, uint256 _cashAmount) external returns (uint256 _tokenAmount) { augur.trustedCashTransfer(msg.sender, address(this), _cashAmount); buyToken(_recipient); } function buyToken(address _recipient) public nonReentrant returns (uint256 _tokenAmount) { uint256 _cashBalance = getCashBalance(); uint256 _cashAmount = _cashBalance.sub(cashReserve); _tokenAmount = getCashSaleProceeds(_cashAmount); require(_tokenAmount > 0, "tokenAmount must be > 0"); transferToken(_recipient, _tokenAmount); update(getTokenBalance(), _cashBalance); emit Swap(msg.sender, address(cash), _cashAmount, _tokenAmount, _recipient); } function skim(address to) external nonReentrant { transferToken(to, getTokenBalance().sub(tokenReserve)); transferCash(to, getCashBalance().sub(cashReserve)); } function sync() external nonReentrant { update(getTokenBalance(), getCashBalance()); } function onTokenTransfer(address _from, address _to, uint256 _value) internal { } function onMint(address _target, uint256 _amount) internal { } function onBurn(address _target, uint256 _amount) internal { } }
cannot reasonably overflow unless the supply of Cash, REP, or ETH became several OOM larger
function update(uint256 _tokenBalance, uint256 _cashBalance) internal { uint256 _blockNumber = block.number; uint256 _blocksElapsed = _blockNumber - blockNumberLast; uint256 _cashReserve = cashReserve; uint256 _tokenReserve = tokenReserve; if (_tokenReserve != 0 && _cashReserve != 0 && _blocksElapsed > 0) { uint256 _priceCumulativeIncrease = _cashReserve.mul(10**18).mul(_blocksElapsed).div(_tokenReserve); onUpdate(_blocksElapsed, _priceCumulativeIncrease); tokenPriceCumulativeLast += _priceCumulativeIncrease; } tokenReserve = _tokenBalance; cashReserve = _cashBalance; blockNumberLast = _blockNumber; emit Sync(_tokenBalance, _cashBalance); }
5,381,371
pragma solidity ^0.5.0; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract EthMadness is Ownable { // Represents the submission to the contest. struct Entrant { // The user who submitted this entry address submitter; // The "index" of this entry. Used to break ties incase two submissions are the same. (earlier submission wins) uint48 entryIndex; } // Represents a current top score in the contest struct TopScore { // The index of this entry (used for tie-breakas a de-dups) uint48 entryIndex; // This bracket's score uint32 score; // The total point differential for this bracket uint64 difference; // The account which submitted this bracket address submitter; } // Represents the results of the contest. struct Result { // The encoded results of the tournament bytes16 winners; // Team A's score in the final uint8 scoreA; // Team B's score in the final uint8 scoreB; // Whether or not this is the final Results (used to tell if a vote is real or not) bool isFinal; } // Represents the various states that the contest will go through. enum ContestState { // The contest is open for people to submit entries. Oracles can also be added during this period. OPEN_FOR_ENTRIES, // The tournament is in progress, no more entries can be received and no oracles can vote TOURNAMENT_IN_PROGRESS, // The tournament is over and we're waiting for all the oracles to submit the results WAITING_FOR_ORACLES, // The oracels have submitted the results and we're waiting for winners to claim their prize WAITING_FOR_WINNING_CLAIMS, // The contest has completed and the winners have been paid out COMPLETED } // Maximum number of entries that will be allowed uint constant MAX_ENTRIES = 2**48; // The number of entries which have been received. uint48 entryCount = 0; // Map of the encoded entry to the user who crreated it. mapping (uint256 => Entrant) public entries; // The times where we're allowed to transition the contract's state mapping (uint => uint) public transitionTimes; // The current state of the contest ContestState public currentState; // The recorded votes of our oracles mapping (address => Result) public oracleVotes; // The oracles who will submit the results of the tournament address[] public oracles; // The maximum number of oracles we'll allow vote in our contest uint constant MAX_ORACLES = 10; // The final result of the tournament that the oracles agreed on Result public finalResult; // Keeps the current top 3 best scores and who submitted them. When the contest ends, they'll be paid out TopScore[3] public topThree; // The address of the ERC20 token that defines our prize address public prizeERC20TokenAddress; // The amount of the prize to reward uint public prizeAmount; // Event emitted when a new entry gets submitted to the contest event EntrySubmitted( // The account who submitted this bracket address indexed submitter, // A compressed representation of the entry combining the picks and final game scores uint256 indexed entryCompressed, // The order this entry was received. Used for tiebreaks uint48 indexed entryIndex, // Optional bracket name provided by the submitter string bracketName ); // Constructs a new instance of the EthMadness contract with the given transition times constructor(uint[] memory times, address erc20Token, uint erc20Amount) public { // Initialize the oracles array with the sender's address oracles = [msg.sender]; // Set up our prize info prizeERC20TokenAddress = erc20Token; prizeAmount = erc20Amount; // Set up our transition times require(times.length == 4); transitionTimes[uint(ContestState.TOURNAMENT_IN_PROGRESS)] = times[0]; transitionTimes[uint(ContestState.WAITING_FOR_ORACLES)] = times[1]; transitionTimes[uint(ContestState.WAITING_FOR_WINNING_CLAIMS)] = times[2]; transitionTimes[uint(ContestState.COMPLETED)] = times[3]; // The initial state should be allowing people to make entries currentState = ContestState.OPEN_FOR_ENTRIES; } // Gets the total number of entries we've received function getEntryCount() public view returns (uint256) { return entryCount; } // Gets the number of Oracles we have registered function getOracleCount() public view returns(uint256) { return oracles.length; } // Returns the transition times for our contest function getTransitionTimes() public view returns (uint256, uint256, uint256, uint256) { return ( transitionTimes[uint(ContestState.TOURNAMENT_IN_PROGRESS)], transitionTimes[uint(ContestState.WAITING_FOR_ORACLES)], transitionTimes[uint(ContestState.WAITING_FOR_WINNING_CLAIMS)], transitionTimes[uint(ContestState.COMPLETED)] ); } // Internal function for advancing the state of the bracket function advanceState(ContestState nextState) private { require(uint(nextState) == uint(currentState) + 1, "Can only advance state by 1"); require(now > transitionTimes[uint(nextState)], "Transition time hasn't happened yet"); currentState = nextState; } // Helper to make sure the picks submitted are legal function arePicksOrResultsValid(bytes16 picksOrResults) public pure returns (bool) { // Go through and make sure that this entry has 1 pick for each game for (uint8 gameId = 0; gameId < 63; gameId++) { uint128 currentPick = extractResult(picksOrResults, gameId); if (currentPick != 2 && currentPick != 1) { return false; } } return true; } // Submits a new entry to the tournament function submitEntry(bytes16 picks, uint64 scoreA, uint64 scoreB, string memory bracketName) public { require(currentState == ContestState.OPEN_FOR_ENTRIES, "Must be in the open for entries state"); require(arePicksOrResultsValid(picks), "The supplied picks are not valid"); // Do some work to encode the picks and scores into a single uint256 which becomes a key uint256 scoreAShifted = uint256(scoreA) * (2 ** (24 * 8)); uint256 scoreBShifted = uint256(scoreB) * (2 ** (16 * 8)); uint256 picksAsNumber = uint128(picks); uint256 entryCompressed = scoreAShifted | scoreBShifted | picksAsNumber; require(entries[entryCompressed].submitter == address(0), "This exact bracket & score has already been submitted"); // Emit the event that this entry was received and save the entry emit EntrySubmitted(msg.sender, entryCompressed, entryCount, bracketName); Entrant memory entrant = Entrant(msg.sender, entryCount); entries[entryCompressed] = entrant; entryCount++; } // Adds an allowerd oracle who will vote on the results of the contest. Only the contract owner can do this // and it can only be done while the tournament is still open for entries function addOracle(address oracle) public onlyOwner { require(currentState == ContestState.OPEN_FOR_ENTRIES, "Must be accepting entries"); require(oracles.length < MAX_ORACLES - 1, "Must be less than max number of oracles"); oracles.push(oracle); } // In case something goes wrong, allow the owner to eject from the contract // but only while picks are still being made or after the contest completes function refundRemaining(uint256 amount) public onlyOwner { require(currentState == ContestState.OPEN_FOR_ENTRIES || currentState == ContestState.COMPLETED, "Must be accepting entries"); IERC20 erc20 = IERC20(prizeERC20TokenAddress); erc20.transfer(msg.sender, amount); } // Submits a new oracle's vote describing the results of the tournament function submitOracleVote(uint oracleIndex, bytes16 winners, uint8 scoreA, uint8 scoreB) public { require(currentState == ContestState.WAITING_FOR_ORACLES, "Must be in waiting for oracles state"); require(oracles[oracleIndex] == msg.sender, "Wrong oracle index"); require(arePicksOrResultsValid(winners), "Results are not valid"); oracleVotes[msg.sender] = Result(winners, scoreA, scoreB, true); } // Close the voting and set the final result. Pass in what should be the consensus agreed by the // 70% of the oracles function closeOracleVoting(bytes16 winners, uint8 scoreA, uint8 scoreB) public { require(currentState == ContestState.WAITING_FOR_ORACLES); // Count up how many oracles agree with this result uint confirmingOracles = 0; for (uint i = 0; i < oracles.length; i++) { Result memory oracleVote = oracleVotes[oracles[i]]; if (oracleVote.isFinal && oracleVote.winners == winners && oracleVote.scoreA == scoreA && oracleVote.scoreB == scoreB) { confirmingOracles++; } } // Require 70%+ of Oracles to have voted and agree on the result uint percentAggreement = (confirmingOracles * 100) / oracles.length; require(percentAggreement > 70, "To close oracle voting, > 70% of oracles must agree"); // Change the state and set our final result which will be used to compute scores advanceState(ContestState.WAITING_FOR_WINNING_CLAIMS); finalResult = Result(winners, scoreA, scoreB, true); } // Closes the entry period and marks that the actual tournament is in progress function markTournamentInProgress() public { advanceState(ContestState.TOURNAMENT_IN_PROGRESS); require(oracles.length > 0, "Must have at least 1 oracle registered"); // Require that we have the amount of funds locked in the contract we expect IERC20 erc20 = IERC20(prizeERC20TokenAddress); require(erc20.balanceOf(address(this)) >= prizeAmount, "Must have a balance in this contract"); } // Mark that the tournament has completed and oracles can start submitting results function markTournamentFinished() public { advanceState(ContestState.WAITING_FOR_ORACLES); } // After the oracles have voted and winners have claimed their prizes, this closes the contest and // pays out the winnings to the 3 winners function closeContestAndPayWinners() public { advanceState(ContestState.COMPLETED); require(topThree[0].submitter != address(0), "Not enough claims"); require(topThree[1].submitter != address(0), "Not enough claims"); require(topThree[2].submitter != address(0), "Not enough claims"); uint firstPrize = (prizeAmount * 70) / 100; uint secondPrize = (prizeAmount * 20) / 100; uint thirdPrize = (prizeAmount * 10) / 100; IERC20 erc20 = IERC20(prizeERC20TokenAddress); erc20.transfer(topThree[0].submitter, firstPrize); erc20.transfer(topThree[1].submitter, secondPrize); erc20.transfer(topThree[2].submitter, thirdPrize); } // Scores an entry and places it in the right sort order function scoreAndSortEntry(uint256 entryCompressed, bytes16 results, uint64 scoreAActual, uint64 scoreBActual) private returns (uint32) { require(currentState == ContestState.WAITING_FOR_WINNING_CLAIMS, "Must be in the waiting for claims state"); require(entries[entryCompressed].submitter != address(0), "The entry must have actually been submitted"); // Pull out the pick information from the compressed entry bytes16 picks = bytes16(uint128((entryCompressed & uint256((2 ** 128) - 1)))); uint256 shifted = entryCompressed / (2 ** 128); // shift over 128 bits uint64 scoreA = uint64((shifted & uint256((2 ** 64) - 1))); shifted = entryCompressed / (2 ** 192); uint64 scoreB = uint64((shifted & uint256((2 ** 64) - 1))); // Compute the score and the total difference uint32 score = scoreEntry(picks, results); uint64 difference = computeFinalGameDifference(scoreA, scoreB, scoreAActual, scoreBActual); // Make a score and place it in the right sort order TopScore memory scoreResult = TopScore(entries[entryCompressed].entryIndex, score, difference, entries[entryCompressed].submitter); if (isScoreBetter(scoreResult, topThree[0])) { topThree[2] = topThree[1]; topThree[1] = topThree[0]; topThree[0] = scoreResult; } else if (isScoreBetter(scoreResult, topThree[1])) { topThree[2] = topThree[1]; topThree[1] = scoreResult; } else if (isScoreBetter(scoreResult, topThree[2])) { topThree[2] = scoreResult; } return score; } function claimTopEntry(uint256 entryCompressed) public { require(currentState == ContestState.WAITING_FOR_WINNING_CLAIMS, "Must be in the waiting for winners state"); require(finalResult.isFinal, "The final result must be marked as final"); scoreAndSortEntry(entryCompressed, finalResult.winners, finalResult.scoreA, finalResult.scoreB); } function computeFinalGameDifference( uint64 scoreAGuess, uint64 scoreBGuess, uint64 scoreAActual, uint64 scoreBActual) private pure returns (uint64) { // Don't worry about overflow here, not much you can really do with it uint64 difference = 0; difference += ((scoreAActual > scoreAGuess) ? (scoreAActual - scoreAGuess) : (scoreAGuess - scoreAActual)); difference += ((scoreBActual > scoreBGuess) ? (scoreBActual - scoreBGuess) : (scoreBGuess - scoreBActual)); return difference; } // Gets the bit at index n in a function getBit16(bytes16 a, uint16 n) private pure returns (bool) { uint128 mask = uint128(2) ** n; return uint128(a) & mask != 0; } // Sets the bit at index n to 1 in a function setBit16(bytes16 a, uint16 n) private pure returns (bytes16) { uint128 mask = uint128(2) ** n; return a | bytes16(mask); } // Sets the bit at index n to 0 in a function clearBit16(bytes16 a, uint16 n) private pure returns (bytes16) { uint128 mask = uint128(2) ** n; mask = mask ^ uint128(-1); return a & bytes16(mask); } // Returns either 0 if there is no possible winner, 1 if team B is chosen, or 2 if team A is chosen function extractResult(bytes16 a, uint8 n) private pure returns (uint128) { uint128 mask = uint128(0x00000000000000000000000000000003) * uint128(2) ** (n * 2); uint128 masked = uint128(a) & mask; // Shift back to get either 0, 1 or 2 return (masked / (uint128(2) ** (n * 2))); } // Gets which round a game belongs to based on its id function getRoundForGame(uint8 gameId) private pure returns (uint8) { if (gameId < 32) { return 0; } else if (gameId < 48) { return 1; } else if (gameId < 56) { return 2; } else if (gameId < 60) { return 3; } else if (gameId < 62) { return 4; } else { return 5; } } // Gets the first game in a round given the round number function getFirstGameIdOfRound(uint8 round) private pure returns (uint8) { if (round == 0) { return 0; } else if (round == 1) { return 32; } else if (round == 2) { return 48; } else if (round == 3) { return 56; } else if (round == 4) { return 60; } else { return 62; } } // Looks at two scores and decided whether newScore is a better score than old score function isScoreBetter(TopScore memory newScore, TopScore memory oldScore) private pure returns (bool) { if (newScore.score > oldScore.score) { return true; } if (newScore.score < oldScore.score) { return false; } // Case where we have a tie if (newScore.difference < oldScore.difference) { return true; } if (newScore.difference < oldScore.difference) { return false; } require(newScore.entryIndex != oldScore.entryIndex, "This entry has already claimed a prize"); // Crazy case where we have the same score and same diference. Return the earlier entry as the winnner return newScore.entryIndex < oldScore.entryIndex; } // Scores an entry given the picks and the results function scoreEntry(bytes16 picks, bytes16 results) private pure returns (uint32) { uint32 score = 0; uint8 round = 0; bytes16 currentPicks = picks; for (uint8 gameId = 0; gameId < 63; gameId++) { // Update which round we're in when on the transitions round = getRoundForGame(gameId); uint128 currentPick = extractResult(currentPicks, gameId); if (currentPick == extractResult(results, gameId)) { score += (uint32(2) ** round); } else if (currentPick != 0) { // If we actually had a pick, propagate forward // Mark all the future currentPicks which required this team winning as null uint16 currentPickId = (gameId * 2) + (currentPick == 2 ? 1 : 0); for (uint8 futureRound = round + 1; futureRound < 6; futureRound++) { uint16 currentPickOffset = currentPickId - (getFirstGameIdOfRound(futureRound - 1) * 2); currentPickId = (getFirstGameIdOfRound(futureRound) * 2) + (currentPickOffset / 2); bool pickedLoser = getBit16(currentPicks, currentPickId); if (pickedLoser) { currentPicks = clearBit16(currentPicks, currentPickId); } else { break; } } } } return score; } }
Submits a new oracle's vote describing the results of the tournament
function submitOracleVote(uint oracleIndex, bytes16 winners, uint8 scoreA, uint8 scoreB) public { require(currentState == ContestState.WAITING_FOR_ORACLES, "Must be in waiting for oracles state"); require(oracles[oracleIndex] == msg.sender, "Wrong oracle index"); require(arePicksOrResultsValid(winners), "Results are not valid"); oracleVotes[msg.sender] = Result(winners, scoreA, scoreB, true); }
5,431,616
// 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 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; }
13,001,444
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_205(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,453,918
pragma solidity 0.4.15; contract owned { address public owner; event ContractOwnershipTransferred(address newOwner); function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function setContractOwner(address newOwner) external onlyOwner { owner = newOwner; ContractOwnershipTransferred(newOwner); } } /// Cillionaire is a lottery where people can participate until a pot limit is reached. Then, a random participant is chosen to be the winner. /// /// Randomness is achieved by XOR'ing the following two numbers: /// ownerRandomNumber ... a random number supplied by the contract owner and submitted upon `start` as a hash, much like a concealed bid in an auction. /// minerRandomNumber ... timestamp of the block that contains the last participant's `particpate` transaction. /// Neither can the owner know the minerRandomNumber, nor can the miner know the ownerRandomNumber (unless the owner supplies a breakable hash, e.h. keccak256(1)). /// /// Many safeguards are in place to prevent loss of participants' stakes and ensure fairness: /// - The owner can `cancel`, in which case participants must be refunded. /// - If the owner does not end the game via `chooseWinner` within 24 hours after PARTICIPATION `state` ended, then anyone can `cancel`. /// - The contract has no `kill` function which would allow the owner to run off with the pot. /// - Game parameters cannot be changed when a game is ongoing /// - Logging of relevant events to increase transparency contract Cillionaire is owned { enum State { ENDED, PARTICIPATION, CHOOSE_WINNER, REFUND } /// Target amount of ether. As long as the `potTarget` is not reached, people can `participate` when the contract is in PARTICIPATION `state`. uint public potTarget; /// Amount of ether that will be used to `participate`. uint public stake; /// Amount of ether that will be taken from `stake` as a fee for the owner. uint public fee; State public state; address[] public participants; bytes32 public ownerRandomHash; uint public minerRandomNumber; uint public ownerRandomNumber; uint public participationEndTimestamp; uint public pot; address public winner; mapping (address => uint) public funds; uint public fees; uint public lastRefundedIndex; event StateChange(State newState); event NewParticipant(address participant, uint total, uint stakeAfterFee, uint refundNow); event MinerRandomNumber(uint number); event OwnerRandomNumber(uint number); event RandomNumber(uint randomNumber); event WinnerIndex(uint winnerIndex); event Winner(address _winner, uint amount); event Refund(address participant, uint amount); event Cancelled(address cancelledBy); event ParametersChanged(uint newPotTarget, uint newStake, uint newFee); modifier onlyState(State _state) { require(state == _state); _; } // Taken from: https://solidity.readthedocs.io/en/develop/common-patterns.html // This modifier requires a certain // fee being associated with a function call. // If the caller sent too much, he or she is // refunded, but only after the function body. // This was dangerous before Solidity version 0.4.0, // where it was possible to skip the part after `_;`. modifier costs(uint _amount) { require(msg.value >= _amount); _; if (msg.value > _amount) { msg.sender.transfer(msg.value - _amount); } } function Cillionaire() { state = State.ENDED; potTarget = 0.1 ether; stake = 0.05 ether; fee = 0; } function setState(State _state) internal { state = _state; StateChange(state); } /// Starts the game, i.e. resets game variables and transitions to state `PARTICIPATION` /// `_ownerRandomHash` is the owner's concealed random number. /// It must be a keccak256 hash that can be verfied in `chooseWinner`. function start(bytes32 _ownerRandomHash) external onlyOwner onlyState(State.ENDED) { ownerRandomHash = _ownerRandomHash; minerRandomNumber = 0; ownerRandomNumber = 0; participationEndTimestamp = 0; winner = 0; pot = 0; lastRefundedIndex = 0; delete participants; setState(State.PARTICIPATION); } /// Participate in the game. /// You must send at least `stake` amount of ether. Surplus ether is refunded automatically and immediately. /// This function will only work when the contract is in `state` PARTICIPATION. /// Once the `potTarget` is reached, the `state` transitions to CHOOSE_WINNER. function participate() external payable onlyState(State.PARTICIPATION) costs(stake) { participants.push(msg.sender); uint stakeAfterFee = stake - fee; pot += stakeAfterFee; fees += fee; NewParticipant(msg.sender, msg.value, stakeAfterFee, msg.value - stake); if (pot >= potTarget) { participationEndTimestamp = block.timestamp; minerRandomNumber = block.timestamp; MinerRandomNumber(minerRandomNumber); setState(State.CHOOSE_WINNER); } } /// Reveal the owner's random number and choose a winner using all three random numbers. /// The winner is credited the pot and can get their funds using `withdraw`. /// This function will only work when the contract is in `state` CHOOSE_WINNER. function chooseWinner(string _ownerRandomNumber, string _ownerRandomSecret) external onlyOwner onlyState(State.CHOOSE_WINNER) { require(keccak256(_ownerRandomNumber, _ownerRandomSecret) == ownerRandomHash); require(!startsWithDigit(_ownerRandomSecret)); // This is needed because keccak256("12", "34") == keccak256("1", "234") to prevent owner from changing his initially comitted random number ownerRandomNumber = parseInt(_ownerRandomNumber); OwnerRandomNumber(ownerRandomNumber); uint randomNumber = ownerRandomNumber ^ minerRandomNumber; RandomNumber(randomNumber); uint winnerIndex = randomNumber % participants.length; WinnerIndex(winnerIndex); winner = participants[winnerIndex]; funds[winner] += pot; Winner(winner, pot); setState(State.ENDED); } /// Cancel the game. /// Participants' stakes (including fee) are refunded. Use the `withdraw` function to get the refund. /// Owner can cancel at any time in `state` PARTICIPATION or CHOOSE_WINNER /// Anyone can cancel 24h after `state` PARTICIPATION ended. This is to make sure no funds get locked up due to inactivity of the owner. function cancel() external { if (msg.sender == owner) { require(state == State.PARTICIPATION || state == State.CHOOSE_WINNER); } else { require((state == State.CHOOSE_WINNER) && (participationEndTimestamp != 0) && (block.timestamp > participationEndTimestamp + 1 days)); } Cancelled(msg.sender); // refund index 0 so lastRefundedIndex=0 is correct if (participants.length > 0) { funds[participants[0]] += stake; fees -= fee; lastRefundedIndex = 0; Refund(participants[0], stake); if (participants.length == 1) { setState(State.ENDED); } else { setState(State.REFUND); } } else { // nothing to refund setState(State.ENDED); } } /// Refund a number of accounts specified by `_count`, beginning at the next un-refunded index which is lastRefundedIndex`+1. /// This is so that refunds can be dimensioned such that they don't exceed block gas limit. /// Once all participants are refunded `state` transitions to ENDED. /// Any user can do the refunds. function refund(uint _count) onlyState(State.REFUND) { require(participants.length > 0); uint first = lastRefundedIndex + 1; uint last = lastRefundedIndex + _count; if (last > participants.length - 1) { last = participants.length - 1; } for (uint i = first; i <= last; i++) { funds[participants[i]] += stake; fees -= fee; Refund(participants[i], stake); } lastRefundedIndex = last; if (lastRefundedIndex >= participants.length - 1) { setState(State.ENDED); } } /// Withdraw your funds, i.e. winnings and refunds. /// This function can be called in any state and will withdraw all winnings as well as refunds. function withdraw() external { uint amount = funds[msg.sender]; funds[msg.sender] = 0; msg.sender.transfer(amount); } /// Withdraw accumulated fees. /// Usable by contract owner when `state` is ENDED. function withdrawFees() external onlyOwner onlyState(State.ENDED) { uint amount = fees; fees = 0; msg.sender.transfer(amount); } /// Adjust game parameters. All parameters are in Wei. /// Can be called by the contract owner in `state` ENDED. function setParams(uint _potTarget, uint _stake, uint _fee) external onlyOwner onlyState(State.ENDED) { require(_fee < _stake); potTarget = _potTarget; stake = _stake; fee = _fee; ParametersChanged(potTarget, stake, fee); } function startsWithDigit(string str) internal returns (bool) { bytes memory b = bytes(str); return b[0] >= 48 && b[0] <= 57; // 0-9; see http://dev.networkerror.org/utf8/ } // parseInt // Copyright (c) 2015-2016 Oraclize SRL // Copyright (c) 2016 Oraclize LTD // Source: https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) // Copyright (c) 2015-2016 Oraclize SRL // Copyright (c) 2016 Oraclize LTD // Source: https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } }
Withdraw your funds, i.e. winnings and refunds. This function can be called in any state and will withdraw all winnings as well as refunds.
function withdraw() external { uint amount = funds[msg.sender]; funds[msg.sender] = 0; msg.sender.transfer(amount); }
5,472,933
./full_match/100/0xd2FDc59405d1D6B5F293AB3E8fC2fC62D110Ecd6/sources/contracts/OrbisMain.sol
Interface for the ERC20 contracts created for reputation/
interface ReputationToken { function mint(address _member, uint _amount) external; function burn(address _member, uint _amount) external; function setMerkleRoot(uint _type, uint _id, bytes32 _merkleRoot) external; }
14,267,255
./full_match/1/0x71079954D970435C4049e8b81cd393A8aCd1B3E1/sources/contracts/MultiTB.sol
Add or remove addresses from whitelist addrs List of addresses values List of values - true for adding to whitelist, false for removing from whitelist
function setWhitelist( address[] calldata addrs, bool[] calldata values ) external onlyOwner { require(addrs.length == values.length, "Wrong params. Unequal lengths"); for (uint256 i = 0; i < addrs.length; i++) { _setWhitelist(addrs[i], values[i]); } }
17,075,062
./full_match/43113/0x0A26B100F2b8f52f7655d66D07e90323EC988eDF/sources/YieldFarming/Farm.sol
Transfers accrued PMKN yield to the user The if conditional statement checks for a stored PMKN balance. If it exists, the the accrued yield is added to the accruing yield before the PMKN mint function is called
function withdrawYield() public { uint256 toTransfer = calculateYieldTotal(msg.sender); require( toTransfer > 0 || pmknBalance[msg.sender] > 0, "Nothing to withdraw" ); if(pmknBalance[msg.sender] != 0){ uint256 oldBalance = pmknBalance[msg.sender]; pmknBalance[msg.sender] = 0; toTransfer += oldBalance; } startTime[msg.sender] = block.timestamp; pmknToken.mint(msg.sender, toTransfer); emit YieldWithdraw(msg.sender, toTransfer); }
7,189,003
pragma solidity 0.4.21; import "./ERC223.sol"; import "./ERC223Reciever.sol"; import "./StandardToken.sol"; import "./AddressTools.sol"; /** * @title (Not)Reference implementation of the ERC223 standard token. */ contract ERC223Token is ERC223, StandardToken { using AddressTools for address; /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address * @param _value Amount of tokens that will be transferred * @param _data Transaction metadata */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { return executeTransfer(_to, _value, _data); } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn"t contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address * @param _value Amount of tokens that will be transferred */ function transfer(address _to, uint256 _value) public returns (bool) { bytes memory _data; return executeTransfer(_to, _value, _data); } /** * @dev Makes execution of the token fallback method from if reciever address is contract */ function executeTokenFallback(address _to, uint256 _value, bytes _data) private returns (bool) { ERC223Reciever receiver = ERC223Reciever(_to); return receiver.tokenFallback(msg.sender, _value, _data); } /** * @dev Makes execution of the tokens transfer method from super class */ function executeTransfer(address _to, uint256 _value, bytes _data) private returns (bool) { require(super.transfer(_to, _value)); if(_to.isContract()) { require(executeTokenFallback(_to, _value, _data)); emit ERC223Transfer(msg.sender, _to, _value, _data); } return true; } }
Transfer the specified amount of tokens to the specified address. This function works the same with the previous one but doesn"t contain `_data` param. Added due to backwards compatibility reasons. _to Receiver address _value Amount of tokens that will be transferred/
function transfer(address _to, uint256 _value) public returns (bool) { bytes memory _data; return executeTransfer(_to, _value, _data); }
1,773,481
// SPDX-License-Identifier: BlueOak-1.0.0 pragma solidity 0.8.9; import "contracts/libraries/Fixed.sol"; import "contracts/p0/RToken.sol"; import "contracts/p0/mixins/Component.sol"; import "contracts/p1/RToken.sol"; import "contracts/interfaces/IBackingManager.sol"; import "contracts/interfaces/IBasketHandler.sol"; import "contracts/plugins/mocks/ERC20Mock.sol"; import "contracts/fuzz/Mocks.sol"; import "contracts/fuzz/Utils.sol"; /* TODO: Here's a few of the many ways that this test could be improved: - Decorate basically everything with events for clues about test failures - Have the MockBasketHandler and MockBackingManager save an "event" log, representing the state-change events that they've been issued, so that we can ensure the equivalence of the function call sequence that each RToken emits - Get these mocks to be more active, so they exercise more of the RToken space. - In particular, make the referesher functions do more of what they're intended to do - Have the mock contracts act wildly, possibly represented by more actions from the RTokenDiffTest contract, to mock out changes that might effect the RToken (but that the RToken probably doesn't model directly) - Change the mock basket model from "token A" to "switches between token A and token B" or use - Or something yet more ambitious? This could be practically anything we can drive from random actions. - It *might* be that these mocked-out component models are really useful for other fuzz tests too */ contract MockBackingManager is IBackingManager, ComponentMock { function init( IMain, uint32, uint192, uint192, uint192 ) external {} function grantRTokenAllowance(IERC20) external {} function manageTokens(IERC20[] memory) external {} /// Settle any auctions that can be settled function settleTrade(IERC20) external virtual override {} function claimAndSweepRewards() external virtual override {} function trades(IERC20) external view virtual override returns (ITrade) { return ITrade(address(0)); } /// @return {%} The maximum trade slippage acceptable function maxTradeSlippage() external view virtual override returns (uint192) { return 1e16; } /// @return {UoA} The smallest amount of value worth trading function dustAmount() external view virtual override returns (uint192) { return 2e20; } } contract MockBasketHandler is IBasketHandler, ComponentMock { using FixLib for uint192; /* The mock basket we're running with, here, is always either 100% A or 100% B. * Each is always assumed to have a price of 1 UoA. * We can (and maybe should) build something with wider behavior */ // Is the basket 100% A (instead of 100% B?) bool public modeA = true; IERC20 public tokenA; IERC20 public tokenB; uint256 public nonce = 0; uint256 public timestamp; constructor(IERC20 tokenA_, IERC20 tokenB_) { tokenA = tokenA_; tokenB = tokenB_; timestamp = block.timestamp; } function init(IMain) external {} function token() private view returns (IERC20) { return modeA ? tokenA : tokenB; } /// Set the prime basket function setPrimeBasket(IERC20[] memory, uint192[] memory) external {} /// Set the backup configuration for a given target function setBackupConfig( bytes32, uint256, IERC20[] calldata ) external {} /// Default the basket in order to schedule a basket refresh function disableBasket() external {} /// Governance-controlled setter to cause a basket switch explicitly function refreshBasket() external { // TODO: modeA = !modeA, and we do all the needed trades and handle capitalization ++nonce; timestamp = block.timestamp; } /// @return If the BackingManager has sufficient collateral to redeem the entire RToken supply function fullyCapitalized() external pure returns (bool) { return true; } /// @return status The worst CollateralStatus of all collateral in the basket function status() external pure returns (CollateralStatus) { return CollateralStatus.SOUND; } /// @return {tok/BU} The whole token quantity of token in the reference basket function quantity(IERC20 erc20) external view returns (uint192) { return token() == erc20 ? FIX_ONE : FIX_ZERO; } /// @param amount {BU} /// @return erc20s The addresses of the ERC20 tokens in the reference basket /// @return quantities {qTok} The quantity of each ERC20 token to issue `amount` baskets function quote(uint192 amount, RoundingMode rounding) external view returns (address[] memory erc20s, uint256[] memory quantities) { erc20s = new address[](1); erc20s[0] = modeA ? address(tokenA) : address(tokenB); quantities = new uint256[](1); quantities[0] = amount.shiftl(18).toUint(rounding); } /// @return baskets {BU} The quantity of complete baskets at an address. A balance for BUs function basketsHeldBy(address acct) external view returns (uint192 baskets) { int8 decimals = int8(IERC20Metadata(address(token())).decimals()); baskets = shiftl_toFix(token().balanceOf(acct), -decimals); } /// @return p {UoA/BU} The protocol's best guess at what a BU would be priced at in UoA function price() external pure returns (uint192 p) { return FIX_ONE; } /// @return nonce_ The basket nonce, a monotonically increasing unique identifier /// @return timestamp_ The timestamp at which the basket was last set function lastSet() external view returns (uint256 nonce_, uint256 timestamp_) { nonce_ = nonce; timestamp_ = timestamp; } } contract RTokenTestSystem is MainMock { using FixLib for uint192; ERC20Mock public baseA; ERC20Mock public baseB; constructor(IRToken rToken_) { DeploymentParams memory params = defaultParams(); Components memory components; baseA = new ERC20Mock("Base Token A", "A$"); baseB = new ERC20Mock("Base Token B", "B$"); for (uint256 i = 0; i < USERS.length; i++) { baseA.mint(USERS[i], 1e24); baseB.mint(USERS[i], 1e24); } init(components, IERC20(address(0)), 0); basketHandler = new MockBasketHandler(baseA, baseB); basketHandler.init(this); backingManager = new MockBackingManager(); backingManager.init( this, params.tradingDelay, params.backingBuffer, params.maxTradeSlippage, params.dustAmount ); rToken = rToken_; rToken.init(this, "RToken", "RTK", "rtoken://1", params.issuanceRate); } } contract RTokenP0Test is RTokenP0 { function _msgSender() internal view virtual override returns (address) { return MainMock(address(main)).sender(); } } contract RTokenP1Test is RTokenP1 { function _msgSender() internal view virtual override returns (address) { return MainMock(address(main)).sender(); } } contract RTokenDiffTest { using FixLib for uint192; address[] public USERS = [address(0x10000), address(0x20000), address(0x30000)]; RTokenTestSystem public p0; RTokenTestSystem public p1; modifier fromSender() { p0.setSender(msg.sender); p1.setSender(msg.sender); _; p0.setSender(address(0)); p1.setSender(address(0)); } modifier fromBackingMgr() { p0.setSender(address(p0.backingManager())); p1.setSender(address(p1.backingManager())); _; p0.setSender(address(0)); p1.setSender(address(0)); } constructor() { p0 = new RTokenTestSystem(new RTokenP0Test()); p1 = new RTokenTestSystem(new RTokenP1Test()); } // Actions and state modifiers // ==== user actions, performed by 0x[123]0000. Melt function issue(uint256 amount) external fromSender { amount %= 1e36; p0.rToken().issue(amount); p1.rToken().issue(amount); } function cancel(uint256 endId, bool e) external fromSender { p0.rToken().cancel(endId, e); p1.rToken().cancel(endId, e); } function vest(address acct, uint256 endId) external fromSender { p0.rToken().vest(acct, endId); p1.rToken().vest(acct, endId); } // TODO: Add "cancel" and "vest" variations that are likely to succeed too // i.e, ones that have valid endIDs function redeem(uint256 amount) external fromSender { amount %= 1e36; p0.rToken().redeem(amount); p1.rToken().redeem(amount); } function melt(uint256 amount) external fromSender { amount %= 1e36; p0.rToken().melt(amount); p1.rToken().melt(amount); } function mint(address recipient, uint256 amount) external fromBackingMgr { amount %= 1e36; recipient = address((uint160(recipient) % 3) * 0x10000); // mint only to USERS p0.rToken().mint(recipient, amount); p1.rToken().mint(recipient, amount); } function setBasketsNeeded(uint192 basketsNeeded) external fromBackingMgr { basketsNeeded %= 1e36; p0.rToken().setBasketsNeeded(basketsNeeded); p1.rToken().setBasketsNeeded(basketsNeeded); } // Auth on these is that the caller needs to be main.owner. That... should be this contract? function setIssuanceRate(uint192 val) external { val %= 1e24; assert(p0.owner() == address(this)); // hope but verify assert(p1.owner() == address(this)); RTokenP0(address(p0.rToken())).setIssuanceRate(val); RTokenP1(address(p1.rToken())).setIssuanceRate(val); } // TODO: changes to MockERC20 balances // Invariant: the observable rtoken prices are equal function echidna_prices_equal() external view returns (bool) { return p0.rToken().price() == p1.rToken().price(); } function echidna_vesting_ids_equal() external view returns (bool) { return p0.rToken().endIdForVest(USERS[0]) == p1.rToken().endIdForVest(USERS[0]) && p0.rToken().endIdForVest(USERS[1]) == p1.rToken().endIdForVest(USERS[1]) && p0.rToken().endIdForVest(USERS[2]) == p1.rToken().endIdForVest(USERS[2]); } function echidna_baskets_needed_equal() external view returns (bool) { return p0.rToken().basketsNeeded() == p1.rToken().basketsNeeded(); } function all_balances_equal(address acct0, address acct1) internal view returns (bool) { return p0.baseA().balanceOf(acct0) == p1.baseA().balanceOf(acct1) && p0.baseB().balanceOf(acct0) == p1.baseB().balanceOf(acct1) && p0.rToken().balanceOf(acct0) == p1.rToken().balanceOf(acct1); } function echidna_user_balances_equal() external view returns (bool equal) { equal = all_balances_equal(address(p0.backingManager()), address(p1.backingManager())) && all_balances_equal(address(p0.basketHandler()), address(p1.basketHandler())) && all_balances_equal(address(p0), address(p1)); for (uint256 i = 0; i < USERS.length; i++) { equal = equal && all_balances_equal(USERS[i], USERS[i]); } } }
Governance-controlled setter to cause a basket switch explicitly TODO: modeA = !modeA, and we do all the needed trades and handle capitalization
function setBackupConfig( bytes32, uint256, IERC20[] calldata function refreshBasket() external { ++nonce; timestamp = block.timestamp; }
1,833,294
//Address: 0xc22407b1f34e494b7f85187fafc2ce5d13871ffb //Contract name: GratitudeCrowdsale //Balance: 0 Ether //Verification Date: 11/1/2017 //Transacion Count: 11 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @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) constant returns (uint256); function transfer(address to, uint256 value) 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) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // Standard token variables contract TokenOfGratitude is MintableToken { string constant public name = "Token Of Gratitude"; string constant public symbol = "ToG"; uint8 constant public decimals = 0; uint256 public expirationDate = 1672531199; address public goldenTicketOwner; // Mappings for easier backchecking mapping (address => uint) redeemed; // ToG redeem event with encrypted message (hopefully a contact info) event tokenRedemption(address indexed supported, string message); // Golden ticket related events event goldenTicketMoved(address indexed newOwner); event goldenTicketUsed(address charlie, string message); function TokenOfGratitude() { goldenTicketOwner = msg.sender; } /** * Function returning the current price of ToG * @dev can be used prior to the donation as a constant function but it is mainly used in the noname function * @param message should contain an encrypted contract info of the redeemer to setup a meeting */ function redeem(string message) { // Check caller has a token require (balances[msg.sender] >= 1); // Check tokens did not expire require (now <= expirationDate); // Lock the token against further transfers balances[msg.sender] -= 1; redeemed[msg.sender] += 1; // Call out tokenRedemption(msg.sender, message); } /** * Function using the Golden ticket - the current holder will be able to get the prize only based on the "goldenTicketUsed" event * @dev First checks the GT owner, then fires the event and then changes the owner to null so GT can't be used again * @param message should contain an encrypted contract info of the redeemer to claim the reward */ function useGoldenTicket(string message){ require(msg.sender == goldenTicketOwner); goldenTicketUsed(msg.sender, message); goldenTicketOwner = 0x0; } /** * Function using the Golden ticket - the current holder will be able to get the prize only based on the "goldenTicketUsed" event * @dev First checks the GT owner, then change the owner and fire an event about the ticket changing owner * @dev The Golden ticket isn't a standard ERC20 token and therefore it needs special handling * @param newOwner should be a valid address of the new owner */ function giveGoldenTicket(address newOwner) { require (msg.sender == goldenTicketOwner); goldenTicketOwner = newOwner; goldenTicketMoved(newOwner); } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){ bool match_ = true; for (var i=0; i<prefix.length; i++){ if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold TokenOfGratitude public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected //address public wallet; => funds are collected in this contract // amount of raised money in wei 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); function Crowdsale(uint256 _startTime, uint256 _endTime) { require(_startTime >= now); require(_endTime >= _startTime); token = createTokenContract(); startTime = _startTime; endTime = _endTime; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (TokenOfGratitude) { return new TokenOfGratitude(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable {} // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, 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(hasEnded()); finalization(); 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 Token of Gratitude fundraiser */ contract GratitudeCrowdsale is FinalizableCrowdsale, usingOraclize { // Utility variables uint256 public tokensLeft; // Defining helper variables to differentiate Oraclize queries bytes32 qID1; bytes32 qID2; // Rate related variables uint256 public rate; bool public hasRate; uint public rateAge; /* * Randomly chosen number for the meal invitation winner * @dev each supporter gets a nonce - the luckyNumber is randomly picked nonce by Oraclize * @dev then points to donorsList[luckyNumber] mapping to get the address of the winner */ bool public hasRandom; uint256 luckyNumber; /* * Medicines sans frontiers (MSF) | Doctors without borders - the public donation address * @dev please check for due diligence: * @notice Link to English site: https://www.lekari-bez-hranic.cz/en/bank-details#cryptocurrencies * @notice Link to Czech site: https://www.lekari-bez-hranic.cz/bankovni-spojeni#kryptomeny * @notice Link to Etherscan: https://etherscan.io/address/0x249f02676d09a41938309447fda33fb533d91dfc */ address constant public addressOfMSF = 0x249F02676D09A41938309447fdA33FB533d91DFC; address constant public communityAddress = 0x008e9392ef82edBA2c45f2B02B9A21ac6B599BCA; // Mapping of supporters for random selection uint256 public donors = 0; mapping (address => bool) donated; mapping (uint256 => address) donorsList; // Fundraising finalization events event finishFundraiser(uint raised); event fundsToMSF(uint value); event fundsToCommunity(uint value); // Special events for a very special golden ticket! event goldenTicketFound(address winner); // Oraclize related events event newOraclizeQuery(string description); event newRate(string price); event newRandom(string price); /** * Constructor * @dev Contract constructor * @param _startTime uint256 is a unix timestamp of when the fundraiser starts * @param _endTime uint256 is a unix timestamp of when the fundraiser ends */ function GratitudeCrowdsale(uint256 _startTime, uint256 _endTime) FinalizableCrowdsale() Crowdsale(_startTime, _endTime) { owner = msg.sender; tokensLeft = 500; } /** * buyTokens override * @dev Implementation of the override to the buy in function for incoming ETH * @param beneficiary address of the participating party */ function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); // Sign up first-time donors to the list + give them a nonce so they can win the golden ticket! if (!donated[beneficiary]) { donated[beneficiary] = true; donorsList[donors] = beneficiary; donors += 1; } // Check if there are still tokens left (otherwise skipped) if (tokensLeft > 0) { // See how many tokens can the donor get. uint256 toGet = howMany(msg.value); // If some, give the tokens to the donor. if (toGet > 0) { token.mint(beneficiary,toGet); TokenPurchase(msg.sender, beneficiary, msg.value, toGet); } } // update state weiRaised = weiRaised.add(msg.value); } /** * Recursive function that counts amount of tokens to assign (even if a contribution overflows certain price range) * @dev Recalculating tokens to receive based on teh currentPrice(2) function. * @dev Number of recursive entrances is equal to the number of price levels (not counting the initial call) * @return toGet - amount of tokens to receive from the particular price range */ function howMany(uint256 _value) internal returns (uint256){ // Check current price level var (price, canGet) = currentPrice(); uint256 toGet = _value.div(price); // Act based on amount of tokens to get if (canGet == 0) { toGet = 0; } else if (toGet > canGet) { tokensLeft -= canGet; toGet = canGet + howMany(_value - (canGet*price)); } else { tokensLeft -= toGet; } return toGet; } /** * Function returning the current price of ToG and amount of tokens available at that price * @dev can be used prior to the donation as a constant function but it is mainly used in the noname function * @return price - current price range * @return maxAtPrice - maximal amount of tokens available at current price */ function currentPrice() constant returns (uint256 price, uint256 maxAtPrice){ if (tokensLeft > 400) { return (100 finney, tokensLeft - 400); } else if (tokensLeft > 300) { return (200 finney, tokensLeft - 300); } else if (tokensLeft > 200) { return (300 finney, tokensLeft - 200); } else if (tokensLeft > 100) { return (400 finney, tokensLeft - 100); } else { return (500 finney, tokensLeft); } } /** * The pre-finalization requirement - get ETHUSD rate * @dev initiates Oraclize call for ETHUSD rate * @param gasLimit uint256 setting gasLimit of the __callback tx from Oraclize */ function loadRate(uint256 gasLimit) payable { // Owner check require(msg.sender == owner); // Make an Oraclize queriey for ETHUSD rate getRateUSD(gasLimit); } /** * The pre-finalization requirement - get Random number * @dev initiates Oraclize call for random number * @param gasLimit uint256 setting gasLimit of the __callback tx from Oraclize */ function loadRandom(uint256 gasLimit) payable { // Owner check require(msg.sender == owner); // Make an Oraclize query for a random number getRandom(gasLimit); } /** * The finalization override - commented bellow */ function finalization() internal { //Check if the crowdsale has ended require(hasEnded()); // Check the rate was queried less then 1 hour ago require(hasRate); require((now - rateAge) <= 3600); // Check the random number was received require(hasRandom); // Assign GoldenTicket token.giveGoldenTicket(donorsList[luckyNumber]); goldenTicketFound(donorsList[luckyNumber]); // Calling checkResult from PriceChecker contract uint256 funding = checkResult(); uint256 raisedWei = this.balance; uint256 charityShare; uint256 toCharity; // If goal isn't met => send everything to MSF if (funding < 10000) { addressOfMSF.transfer(raisedWei); fundsToMSF(toCharity); } else if (funding < 25000) { // If 2nd goal isn't met => send the rest above the 1st goal to MSF charityShare = toPercentage(funding, funding-10000); toCharity = fromPercentage(raisedWei, charityShare); // Donate to charity first addressOfMSF.transfer(toCharity); fundsToMSF(toCharity); // Send funds to community; communityAddress.transfer(raisedWei - toCharity); fundsToCommunity(raisedWei - toCharity); } else { // If 2nd goal is met => send the rest above the 2nd goal to MSF charityShare = toPercentage(funding, funding-25000); toCharity = fromPercentage(raisedWei, charityShare); // Donate to charity first addressOfMSF.transfer(toCharity); fundsToMSF(toCharity); // Send funds to community; communityAddress.transfer(raisedWei - toCharity); fundsToCommunity(raisedWei - toCharity); } token.finishMinting(); super.finalization(); } /** * @dev Checking results of the fundraiser in USD * @return rated - total funds raised converted to USD */ function checkResult() internal returns (uint256){ uint256 raised = this.balance; // convert wei => usd to perform checks uint256 rated = (raised.mul(rate)).div(10000000000000000000000); return rated; } /** * Helper function to get split funds between the community and charity I * @dev Counts percentage of the total funds that belongs to the charity * @param total funds raised in USD * @param part of the total funds raised that should go to the charity * @return percentage in full expressed as a natural number between 0 and 100 */ function toPercentage (uint256 total, uint256 part) internal returns (uint256) { return (part*100)/total; } /** * Helper function to get split funds between the community and charity II * @dev Counts the exact amount of Wei to get send to the charity * @param value of total funds raised in Wei * @param percentage to be used obtained from the toPercentage(2) function * @return amount of Wei to be send to the charity */ function fromPercentage(uint256 value, uint256 percentage) internal returns (uint256) { return (value*percentage)/100; } // <DATA FEEDS USING ORACLIZE> /** * @dev Create the ETHUSD query to Kraken thorough Oraclize */ function getRateUSD(uint256 _gasLimit) internal { //require(msg.sender == owner); oraclize_setProof(proofType_TLSNotary); if (oraclize.getPrice("URL") > this.balance) { newOraclizeQuery("Oraclize: Insufficient funds!"); } else { newOraclizeQuery("Oraclize was asked for ETHUSD rate."); qID1 = oraclize_query("URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.p.1", _gasLimit); } } /** * @dev Create the random number query to Oraclize */ function getRandom(uint256 _gasLimit) internal { //require (msg.sender == owner); oraclize_setProof(proofType_Ledger); if (oraclize.getPrice("random") > this.balance) { newOraclizeQuery("Oraclize: Insufficient funds!"); } else { newOraclizeQuery("Oraclize was asked for a random number."); // Make query for 4 random bytes to potentially get a number between 0 and 4294967295. // The assumption is that there won't be more then 4294967295 participants. // This may potentially hurt your contract as the "random mod participants" result distribution is unequal. // There creates an incentive to join earlier to have an micro advantage. qID2 = oraclize_newRandomDSQuery(0, 4, _gasLimit); } } /** *Oraclize callback function awaiting for response from the queries * @dev uses qType to handle the last called query type * @dev different querytypes shouldn't be called before callback was received * @dev -> not implementing a query que as "owner" is the only party responsible for creating order */ function __callback(bytes32 myid, string result, bytes proof) { require(msg.sender == oraclize_cbAddress()); if (myid == qID1) { checkQueryA(myid, result, proof); } else if (myid == qID2) { checkQueryB(myid, result, proof); } } /** * A helper function to separate reaction to different Oraclize queries - ETHUSD rate * @dev reaction to ETHUSD rate oraclize callback - getRateUSD() * @dev sets global vars rate to the result and rateAge to current timeStamp * @param _myid 32 bytes identifying the query generated by Oraclize * @param _result string with query result by Oraclize * @param _proof byte array with the proof of source by Oraclize */ function checkQueryA(bytes32 _myid, string _result, bytes _proof) internal { newRate(_result); // calling Oraclize string => uint256 converter for a number with 4 decimals rate = parseInt(_result,4); rateAge = now; hasRate = true; } /** * A helper function to separate reaction to different Oraclize queries - random number * @dev reaction to random number oraclize callback - getRandom(number of participants) * @dev sets global var luckyNumber to the result * @param _myid 32 bytes identifying the query generated by Oraclize * @param _result string with query result by Oraclize * @param _proof byte array with the proof of source by Oraclize */ function checkQueryB(bytes32 _myid, string _result, bytes _proof) internal oraclize_randomDS_proofVerify(_myid, _result, _proof) { newRandom(_result); // Calling Oraclize string => uint converter uint256 someNumber = parseInt(string(bytes(_result)),0); // Getting a luckyNumber between 0 and the number of donors (Random-number modulo number of donors) luckyNumber = someNumber%donors; hasRandom = true; } //Adjusting the hasEnded function to a case where all tokens were sold function hasEnded() public constant returns (bool) { return ((now > endTime) || (tokensLeft <= 0)) ; } }
Function using the Golden ticket - the current holder will be able to get the prize only based on the "goldenTicketUsed" event First checks the GT owner, then change the owner and fire an event about the ticket changing owner The Golden ticket isn't a standard ERC20 token and therefore it needs special handling newOwner should be a valid address of the new owner/
function giveGoldenTicket(address newOwner) { require (msg.sender == goldenTicketOwner); goldenTicketOwner = newOwner; goldenTicketMoved(newOwner); }
12,655,506
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract CryptoProtect is Ownable { using SafeMath for uint256; ERC20Interface tokenInterface; // Policy State -- // 1 - active // 2 - inactive // 3 - claimed struct Policy { uint256 premiumAmount; uint256 payoutAmount; uint256 endDate; uint8 state; } struct Token { mapping (string => Policy) token; } struct Exchange { mapping (string => Token) exchange; } struct Pool{ uint256 endDate; uint256 amount; } mapping(address => Exchange) policies; Pool[] private poolRecords; uint private poolRecordsIndex; uint256 private poolBackedAmount; // poolState state -- // 1 - active // 2 - not active uint8 public poolState; uint256 public poolMaxAmount; uint256 public poolStartDate; uint256 public minPremium; uint256 public maxPremium; string public contractName; event PoolStateUpdate(uint8 indexed state); event PremiumReceived(address indexed addr, uint256 indexed amount, uint indexed id); event ClaimSubmitted(address indexed addr, string indexed exchange, string indexed token); event ClaimPayout(address indexed addr, string indexed exchange, string indexed token); event PoolBackedAmountUpdate(uint256 indexed amount); event PoolPremiumLimitUpdate(uint256 indexed min, uint256 indexed max); constructor( string _contractName, address _tokenContract, uint256 _poolMaxAmount, uint256 _poolBackedAmount, uint256 _minPremium, uint256 _maxPremium ) public { contractName = _contractName; tokenInterface = ERC20Interface(_tokenContract); poolState = 1; poolStartDate = now; poolMaxAmount = _poolMaxAmount; poolBackedAmount = _poolBackedAmount; minPremium = _minPremium; maxPremium = _maxPremium; } /** * @dev Modifier to check pool state */ modifier verifyPoolState() { require(poolState == 1); _; } /** * @dev Check policy eligibility */ function isEligible(address _addr, string _exchange, string _token) internal view returns (bool) { if ( policies[_addr].exchange[_exchange].token[_token].state == 0 || policies[_addr].exchange[_exchange].token[_token].endDate < now ) { return true; } return false; } /** * @dev Compute Pool Amount */ function computePoolAmount() internal view returns (uint256) { uint256 currentPoolAmount = 0; // limited by gas for (uint i = poolRecordsIndex; i< poolRecords.length; i++) { if (poolRecords[i].endDate < now) { continue; } currentPoolAmount = currentPoolAmount.add(poolRecords[i].amount); } return currentPoolAmount.add(poolBackedAmount); } /** * @dev Make Transaction * Make transaction using transferFrom */ function MakeTransaction( address _tokenOwner, uint256 _premiumAmount, uint256 _payoutAmount, string _exchange, string _token, uint8 _id ) external verifyPoolState() { // check parameters require(_tokenOwner != address(0)); require(_premiumAmount < _payoutAmount); require(_premiumAmount >= minPremium); require(_premiumAmount <= maxPremium); require(bytes(_exchange).length > 0); require(bytes(_token).length > 0); require(_id > 0); // require(computePoolAmount() < poolMaxAmount); // reduce cost // check eligibility require(isEligible(_tokenOwner, _exchange, _token)); // check that token owner address has valid amount require(tokenInterface.balanceOf(_tokenOwner) >= _premiumAmount); require(tokenInterface.allowance(_tokenOwner, address(this)) >= _premiumAmount); // record data policies[_tokenOwner].exchange[_exchange].token[_token].premiumAmount = _premiumAmount; policies[_tokenOwner].exchange[_exchange].token[_token].payoutAmount = _payoutAmount; policies[_tokenOwner].exchange[_exchange].token[_token].endDate = now.add(90 * 1 days); policies[_tokenOwner].exchange[_exchange].token[_token].state = 1; // record pool poolRecords.push(Pool(now.add(90 * 1 days), _premiumAmount)); // transfer amount tokenInterface.transferFrom(_tokenOwner, address(this), _premiumAmount); emit PremiumReceived(_tokenOwner, _premiumAmount, _id); } /** * @dev Get Policy */ function GetPolicy(address _addr, string _exchange, string _token) public view returns ( uint256 premiumAmount, uint256 payoutAmount, uint256 endDate, uint8 state ) { return ( policies[_addr].exchange[_exchange].token[_token].premiumAmount, policies[_addr].exchange[_exchange].token[_token].payoutAmount, policies[_addr].exchange[_exchange].token[_token].endDate, policies[_addr].exchange[_exchange].token[_token].state ); } /** * @dev Get Policy */ function SubmitClaim(address _addr, string _exchange, string _token) public returns (bool submitted) { require(policies[_addr].exchange[_exchange].token[_token].state == 1); require(policies[_addr].exchange[_exchange].token[_token].endDate > now); emit ClaimSubmitted(_addr, _exchange, _token); return true; } /** * @dev Get Current Pool Amount */ function GetCurrentPoolAmount() public view returns (uint256) { return computePoolAmount(); } /** * @dev Check Eligibility */ function CheckEligibility(address _addr, string _exchange, string _token) public view returns (bool) { return(isEligible(_addr, _exchange, _token)); } /** * @dev Check Token Balance */ function CheckBalance(address _addr) public view returns (uint256){ return tokenInterface.balanceOf(_addr); } /** * @dev Check Token Allowance */ function CheckAllowance(address _addr) public view returns (uint256){ return tokenInterface.allowance(_addr, address(this)); } /** * @dev Update Pool State */ function UpdatePolicyState(address _addr, string _exchange, string _token, uint8 _state) external onlyOwner { require(policies[_addr].exchange[_exchange].token[_token].state != 0); policies[_addr].exchange[_exchange].token[_token].state = _state; if (_state == 3) { emit ClaimPayout(_addr, _exchange, _token); } } /** * @dev Update Pool State */ function UpdatePoolState(uint8 _state) external onlyOwner { poolState = _state; emit PoolStateUpdate(_state); } /** * @dev Update Backed Amount */ function UpdateBackedAmount(uint256 _amount) external onlyOwner { poolBackedAmount = _amount; emit PoolBackedAmountUpdate(_amount); } /** * @dev Update Premium Limit */ function UpdatePremiumLimit(uint256 _min, uint256 _max) external onlyOwner { require(_min < _max); minPremium = _min; maxPremium = _max; emit PoolPremiumLimitUpdate(_min, _max); } /** * @dev Initiate Payout */ function InitiatePayout(address _addr, string _exchange, string _token) external onlyOwner { require(policies[_addr].exchange[_exchange].token[_token].state == 1); require(policies[_addr].exchange[_exchange].token[_token].payoutAmount > 0); uint256 payoutAmount = policies[_addr].exchange[_exchange].token[_token].payoutAmount; require(payoutAmount <= tokenInterface.balanceOf(address(this))); policies[_addr].exchange[_exchange].token[_token].state = 3; tokenInterface.transfer(_addr, payoutAmount); emit ClaimPayout(_addr, _exchange, _token); } /** * @dev Withdraw Fee */ function WithdrawFee(uint256 _amount) external onlyOwner { require(_amount <= tokenInterface.balanceOf(address(this))); tokenInterface.transfer(owner, _amount); } /** * @dev Emergency Drain * in case something went wrong and token is stuck in contract */ function EmergencyDrain(ERC20Interface _anyToken) external onlyOwner returns(bool) { if (address(this).balance > 0) { owner.transfer(address(this).balance); } if (_anyToken != address(0)) { _anyToken.transfer(owner, _anyToken.balanceOf(this)); } return true; } }
Check policy eligibility/
function isEligible(address _addr, string _exchange, string _token) internal view returns (bool) { if ( policies[_addr].exchange[_exchange].token[_token].state == 0 || policies[_addr].exchange[_exchange].token[_token].endDate < now ) { return true; } return false; }
2,474,634
//Address: 0xee61d0f4d7da6953b4e3ca62cbe10c16045b6a67 //Contract name: BitindiaVestingContract //Balance: 0 Ether //Verification Date: 1/25/2018 //Transacion Count: 6 // CODE STARTS HERE /** * The MIT License (MIT) Copyright (c) 2018 Bitindia. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information regarding the MIT License visit: https://opensource.org/licenses/MIT @AUTHOR Bitindia. https://bitindia.co/ * */ pragma solidity ^0.4.15; contract IERC20 { function totalSupply() public constant returns (uint _totalSupply); function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title Ownable * @notice 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; /** * @notice The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @notice Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @notice 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)); owner = newOwner; } } /** * BitindiaVestingContract * This Contract is a custodian for Bitindia Tokens reserved for Founders * Founders can claim as per fixed Vesting Schedule * Founders can only claim the amount alloted to them before initialization * The Contract gets into a locked state once initialized and no more founder address can be further added * The Founder addresses are added using addVestingUser method and logs an Event AddUser on successful addition * Only the contract owner can add the Vesting users and cannot change the address once inititialized * Anyone can check the state inititialized, as its a public variable * Once initialized, founders can anytime change their claim address, and this can be done only using their private key, * No body else can change claimant address other than themselves. * No kind of recovery is possible once the private key of any claimant is lost and any unclaimed tokens will be locked in this contract forever */ contract BitindiaVestingContract is Ownable{ IERC20 token; mapping (address => uint256) ownersMap; mapping (address => uint256) ownersMapFirstPeriod; mapping (address => uint256) ownersMapSecondPeriod; mapping (address => uint256) ownersMapThirdPeriod; /** * Can be initialized only once all the committed token amount is deposited to this contract * Once initialized, it cannot be set False again * Once initialized, no more founder address can be registered */ bool public initialized = false; /** * At any point displays total anount that is yet to be claimed */ uint256 public totalCommitted; /** * To avoid too many address changes, * */ mapping (address => address) originalAddressTraker; mapping (address => uint) changeAddressAttempts; /** * Fixed Vesting Schedule * */ uint256 public constant firstDueDate = 1544486400; // Human time (GMT): Tuesday, 11 December 2018 00:00:00 uint256 public constant secondDueDate = 1560211200; // Human time (GMT): Tuesday, Tuesday, 11 June 2019 00:00:00 uint256 public constant thirdDueDate = 1576022400; // Human time (GMT): Wednesday, 11 December 2019 00:00:00 /** * Address of the Token to be vested */ address public constant tokenAddress = 0x420335D3DEeF2D5b87524Ff9D0fB441F71EA621f; /** * Event to log change of address request if successful, only the Actual owner can transfer its ownership * */ event ChangeClaimAddress(address oldAddress, address newAddress); /** * Event to log claimed amount once the vesting condition is met. */ event AmountClaimed(address user, uint256 amount); /** * Event to Log added user */ event AddUser(address userAddress, uint256 amount); /** * Cnstr BitindiaVestingContract * Sets the vesting period in utc timestamp and the vesting token address */ function BitindiaVestingContract() public { token = IERC20(tokenAddress); initialized = false; totalCommitted = 0; } /** * Initializes the contract only once * Requires token balance to be atleast equal to total commited, any amount greater than commited is lost in the contract forever */ function initialize() public onlyOwner { require(totalCommitted>0); require(totalCommitted <= token.balanceOf(this)); if(!initialized){ initialized = true; } } /** * @notice To check if Contract is active */ modifier whenContractIsActive() { // Check if Contract is active require(initialized); _; } /** * @notice To check if Contract is not yet initialized */ modifier preInitState() { // Check if Contract is not initialized require(!initialized); _; } /** * @notice To check if Claimable */ modifier whenClaimable() { // Check if Contract is active assert(now>firstDueDate); _; } /** * Asserts the msg sender to have valid stake in the vesting schedule, else eat up their GAS * this is to discourage SPAMMERS */ modifier checkValidUser(){ assert(ownersMap[msg.sender]>0); _; } /** * @notice Can be called only before initialization * Equal vesting in three periods */ function addVestingUser(address user, uint256 amount) public onlyOwner preInitState { uint256 oldAmount = ownersMap[user]; ownersMap[user] = amount; ownersMapFirstPeriod[user] = amount/3; ownersMapSecondPeriod[user] = amount/3; ownersMapThirdPeriod[user] = amount - ownersMapFirstPeriod[user] - ownersMapSecondPeriod[user]; originalAddressTraker[user] = user; changeAddressAttempts[user] = 0; totalCommitted += (amount - oldAmount); AddUser(user, amount); } /** * This is to change the address of the claimant. * SPRECIAL NOTE: ONLY THE VALID CLAIMANT CAN change its address and nobody else can do this */ function changeClaimAddress(address newAddress) public checkValidUser{ // Validates if Change address is not meant to Spam address origAddress = originalAddressTraker[msg.sender]; uint newCount = changeAddressAttempts[origAddress]+1; assert(newCount<5); changeAddressAttempts[origAddress] = newCount; // Do the address change transaction uint256 balance = ownersMap[msg.sender]; ownersMap[msg.sender] = 0; ownersMap[newAddress] = balance; // Do the address change transaction for FirstPeriod balance = ownersMapFirstPeriod[msg.sender]; ownersMapFirstPeriod[msg.sender] = 0; ownersMapFirstPeriod[newAddress] = balance; // Do the address change transaction for SecondPeriod balance = ownersMapSecondPeriod[msg.sender]; ownersMapSecondPeriod[msg.sender] = 0; ownersMapSecondPeriod[newAddress] = balance; // Do the address change transaction for FirstPeriod balance = ownersMapThirdPeriod[msg.sender]; ownersMapThirdPeriod[msg.sender] = 0; ownersMapThirdPeriod[newAddress] = balance; // Update Original Address Tracker Map originalAddressTraker[newAddress] = origAddress; ChangeClaimAddress(msg.sender, newAddress); } /** * Admin function to restart attempt counts for a user */ function updateChangeAttemptCount(address user) public onlyOwner{ address origAddress = originalAddressTraker[user]; changeAddressAttempts[origAddress] = 0; } /** * Check the balance of the Vesting Contract */ function getBalance() public constant returns (uint256) { return token.balanceOf(this); } /** * To claim the vesting amount * Asserts the vesting condition is met * Asserts callee to be valid vested user * Claims as per Vesting Schedule and remaining eligible balance */ function claimAmount() internal whenContractIsActive whenClaimable checkValidUser{ uint256 amount = 0; uint256 periodAmount = 0; if(now>firstDueDate){ periodAmount = ownersMapFirstPeriod[msg.sender]; if(periodAmount > 0){ ownersMapFirstPeriod[msg.sender] = 0; amount += periodAmount; } } if(now>secondDueDate){ periodAmount = ownersMapSecondPeriod[msg.sender]; if(periodAmount > 0){ ownersMapSecondPeriod[msg.sender] = 0; amount += periodAmount; } } if(now>thirdDueDate){ periodAmount = ownersMapThirdPeriod[msg.sender]; if(periodAmount > 0){ ownersMapThirdPeriod[msg.sender] = 0; amount += periodAmount; } } require(amount>0); ownersMap[msg.sender]= ownersMap[msg.sender]-amount; token.transfer(msg.sender, amount); totalCommitted -= amount; } /** * Main fallback to claim tokens after successful vesting * Asserts the sender to be a valid owner of tokens and vesting period is over */ function () external payable { claimAmount(); } /** * To check total remaining claimable amount */ function getClaimable() public constant returns (uint256){ return totalCommitted; } /** * Check Own Balance * Works only for transaction senders with valid Balance */ function getMyBalance() public checkValidUser constant returns (uint256){ return ownersMap[msg.sender]; } }
Check Own Balance Works only for transaction senders with valid Balance/
function getMyBalance() public checkValidUser constant returns (uint256){ return ownersMap[msg.sender]; }
6,477,146
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0 <0.9.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function transfer(address to, uint256 value) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); function approve(address spender, uint256 value) external returns (bool success); function allowance(address owner, address spender) external view returns (uint256 remaining); } /** * Simple ERC-20 implementation */ contract WRVN is IERC20 { address internal owner; address public issuer; mapping (address => uint256) public override balanceOf; mapping (address => mapping (address => uint256)) public override allowance; string public override name; string public override symbol; uint8 public override decimals; uint256 public override totalSupply; modifier onlyIssuer() { require(msg.sender == issuer); // dev: requires issuer _; } /** * Sets the token fields: owner, issuer, name, and symbol * */ constructor(address tokenOwner, address tokenIssuer, string memory tokenName, string memory tokenSymbol) { owner = tokenOwner; issuer = tokenIssuer; name = tokenName; symbol = tokenSymbol; decimals = 8; } function setIssuer(address newIssuer) external { require(msg.sender == owner); // dev: requires owner issuer = newIssuer; } /** * Mints {value} tokens to the {to} wallet. * * @param to The address receiving the newly minted tokens * @param value The number of tokens to mint */ function mint(address to, uint256 value) external onlyIssuer { require(to != address(0)); // dev: requires non-zero address totalSupply += value; balanceOf[to] += value; emit Transfer(address(0), to, value); } /** * Burn {value} tokens of the {from} wallet. * * @param from The address to burn tokens from * @param value The number of tokens to burn */ function burn(address from, uint256 value) external onlyIssuer { uint256 balance = balanceOf[from]; require(balance >= value); // dev: exceeds balance balanceOf[from] = balance - value; totalSupply -= value; emit Transfer(from, address(0), value); } /** * Approves the `spender` to transfer `value` tokens of the caller. * * @param spender The address which will spend the funds * @param value The value approved to be spent by the spender * @return A boolean that indicates if the operation was successful */ function approve(address spender, uint256 value) external override returns(bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * Transfers {value} tokens from the caller, to {to} * * @param to The address to transfer tokens to * @param value The number of tokens to be transferred * @return A boolean that indicates if the operation was successful */ function transfer(address to, uint256 value) external override returns (bool) { move(msg.sender, to, value); return true; } /** * Transfers {value} tokens of {from} to {to}, on behalf of the caller. * * @param from The address to transfer tokens from * @param to The address to transfer tokens to * @param value The number of tokens to be transferred * @return A boolean that indicates if the operation was successful */ function transferFrom(address from, address to, uint256 value) external override returns (bool) { uint256 currentAllowance = allowance[from][msg.sender]; require(currentAllowance >= value); // dev: exceeds allowance move(from, to, value); allowance[from][msg.sender] = currentAllowance - value; return true; } function move(address from, address to, uint256 value) internal { require(to != address(0)); // dev: requires non-zero address uint256 balance = balanceOf[from]; require(balance >= value); // dev: exceeds balance balanceOf[from] = balance - value; balanceOf[to] += value; emit Transfer(from, to, value); } }
Transfers {value} tokens of {from} to {to}, on behalf of the caller. from The address to transfer tokens from to The address to transfer tokens to value The number of tokens to be transferred return A boolean that indicates if the operation was successful/
function transferFrom(address from, address to, uint256 value) external override returns (bool) { uint256 currentAllowance = allowance[from][msg.sender]; move(from, to, value); allowance[from][msg.sender] = currentAllowance - value; return true; }
5,963,358
pragma solidity ^ 0.5.0; import "./Agreement.sol"; import "./Transaction.sol"; import "./SafeMath.sol"; import "./Graph.sol"; import "./MainGraph.sol"; import "./AgreementFactory.sol"; import "./Transaction Factory.sol"; import "./Tools.sol"; import "./ToolFactory.sol"; contract Netereum { using SafeMath for uint256; int256 public constant MAX_INT = int256(~(uint256(1) << 255)); uint256 constant MAX_UINT = ~uint256(0); address owner; MainGraph mainGraph; AgreementFactory aFactory; TransactionFactory tFactory; ToolFactory toolFactory; Tools tool; constructor(/*AgreementFactory _aFactory,TransactionFactory tFactory,ToolFactory toolFactory*/) public { owner = msg.sender; // aFactory = _aFactory; aFactory = new AgreementFactory(); tFactory = new TransactionFactory(); toolFactory = new ToolFactory(); tool = toolFactory.create(); } function setMainGraph(address mainGraphAddress) public { // require(msg.sender == owner); mainGraph = MainGraph(address (mainGraphAddress)); } //uint256 barterTime = 15669098070; address[] confirmedCoordinators; mapping(address => bool) isCoordinatorInserted; mapping(address => Transaction) createdTransactions;// these are all the transactions that have been created address [] public createdTransactionsAddress; mapping(address => uint8) public transactionsStatus ;// 0: not created 1:created 2: pending 3:added 4:declined: mapping(address => Agreement) createdAgreements;// these are all the Agreements that have been created address [] public createdAgreementsAddress; mapping(address => uint8) public agreementsStatus;// 0: not created 1:offered 2:pending 3:expired 4:declined 5:altering //mapping(address => bool) agreementExists;// this mapping shows if an agreement with a specific address has been created or not //mapping(address => bool) isAgreementAdded;// this mapping shows if an agreement has been added to the final agreements(for preventing that an agreement is added multiple times) Transaction[] public transactions;// These are the finalized transaction Agreement[] public agreements;//These are the finalized agreements QUESTION: SHOULD THESE TWO BE MAPS OR ARRAYS? mapping(address => uint256) transactionsExpireTime; uint256 public numberOfCreatedTransactions = 0; uint256 public numberOfCreatedAgreements = 0; uint256 public numberOfTransactions = 0; uint256 public numberOfAgreements = 0; uint256 public numberOfCoordinators = 0; // event coordinatorAdded(address coordinator,bool added); // event agreementCreated(address agreement); // event transactionCreated(address transaction); // event transactionAdded(address transaction, bool added); function addCoordinator(address coordinator) public // adding a coordinator to the list of valid coordinators { //require(msg.sender == owner); if (!isCoordinatorInserted[coordinator]) { //nodes[coordinator].coordinator = coordinator; //nodes[coordinator].isInserted = true; confirmedCoordinators.push(coordinator); isCoordinatorInserted[coordinator] = true; numberOfCoordinators++; mainGraph.addNode(coordinator); //emit coordinatorAdded(coordinator,true); } //emit coordinatorAdded(coordinator,false); } function createAgreement(address _debtor, address _creditor, address _debtorCoordinator, address _creditorCoordinator, uint256 _debtAmount, uint256 _exchangeRate ,uint256 _expireTime,address agreementAddress)/*if the last field isn't 0, then this means that an agreement that has already been submitted needs to be change*/ public returns(address) { uint256 cost = 0; if(agreementAddress == address(0)) { //require(msg.sender == _debtor, "2"); require(isCoordinatorInserted[_debtorCoordinator] == true, "3"); require(isCoordinatorInserted[_creditorCoordinator] == true, "4"); // require(_expireTime > block.timestamp,"5"); cost = _debtAmount; } else { require(agreementsStatus[agreementAddress] == 2, "21"); //require(msg.sender == createdAgreements[agreementAddress].debtor(), "2"); agreementsStatus[agreementAddress] = 5;// altering cost = mainGraph.wrappedRemoveEdge(0,0,agreementAddress,1); require(cost> 0,"26"); } require(_exchangeRate < uint256 (MAX_INT/2) && _exchangeRate > 0 ,"24"); require(cost < (MAX_UINT / 1000000)); //require(cost < (MAX_UINT / _exchangeRate)); Agreement newAgreement = aFactory.create( _debtor, _creditor, _debtorCoordinator, _creditorCoordinator, cost,_exchangeRate,_expireTime,address (this) ); address newAgreementAddress = address(newAgreement); numberOfCreatedAgreements++; createdAgreements[newAgreementAddress] = newAgreement; createdAgreementsAddress.push(newAgreementAddress); agreementsStatus[newAgreementAddress] = 1;//offered if(cost > 0 && agreementAddress != address (0)) agreementsStatus[agreementAddress] = 2;// pending //emit agreementCreated(newAgreementAddress); return newAgreementAddress; } function addAgreement(address agreementAddress) external { require(agreementsStatus[agreementAddress] == 1, "6"); // require(createdAgreements[agreementAddress].expireTime() > block.timestamp,"5"); //require(createdAgreements[agreementAddress].counterPermission() == 4, "7 "); agreementsStatus[agreementAddress] = 2;// pending agreements.push(Agreement(address(agreementAddress))); numberOfAgreements++; mainGraph.wrappedAddEdge(createdAgreements[agreementAddress].creditorCoordinator(), createdAgreements[agreementAddress].debtorCoordinator(), createdAgreements[agreementAddress].exchangeRate(),tool.logarithm(int256(createdAgreements[agreementAddress].exchangeRate())),0, createdAgreements[agreementAddress].debtAmount() ,address(agreementAddress)); } function createTransaction(address _buyer, address _seller, address _buyerCoordinator, address _sellerCoordinator, uint256 _buyerCost, uint256 _sellerCost) external returns(address) { //require(msg.sender == _buyer, "8"); require(isCoordinatorInserted[_buyerCoordinator] == true, "3"); require(isCoordinatorInserted[_sellerCoordinator] == true, "4"); Transaction newTransaction = tFactory.create(_buyer, _seller, _buyerCoordinator, _sellerCoordinator, _buyerCost, _sellerCost,address (this)); address newTransactionAddress = address(newTransaction); createdTransactions[newTransactionAddress] = newTransaction; createdTransactionsAddress.push(newTransactionAddress); transactionsStatus[newTransactionAddress] = 1;// created numberOfCreatedTransactions++; //emit transactionCreated(addr); return newTransactionAddress; } /* When a customer is trying to execute a transaction, the parameters of the transaction are first sent to the Create transaction function which creates a transaction and returns the address of that transaction. then when all sides have given permission, then he transaction will be able to be sent to the do transaction function. if the transactions buyerCost is less than the buyerCost that the system can handle with its current state, the transaction will be added to the mapping "transactions" and can be executed by the coordinators. */ uint256 public xy; function doTransaction(address addr) external { require(transactionsStatus[addr] == 1, "11"); //require(createdTransactions[addr].counterPermission() == 4, "12"); transactionsStatus[addr] = 2; //pending bool returnBool; uint256 returnFund; (returnBool,returnFund) = mainGraph.maxFund(createdTransactions[addr].buyerCoordinator(), createdTransactions[addr].sellerCoordinator(), createdTransactions[addr].buyerCost(), createdTransactions[addr].sellerCost() ,false); xy = returnFund; if (returnBool == true) { transactionsStatus[addr] = 3; transactions.push(Transaction(address(addr))); numberOfTransactions ++; //emit transactionAdded(addr,true); } else { transactionsStatus[addr] = 1; //emit transactionAdded(addr,false); } } // function approximateMaxFee(address _buyerCoordinator, address _sellerCoordinator, // uint256 _sellerCost) public returns(uint256) // { //// require(nodes[_buyerCoordinator].isInserted == true, "3"); //// require(nodes[_sellerCoordinator].isInserted == true, "4"); // bool temp; // uint256 returnValue; // (temp,returnValue) = maxFund(_buyerCoordinator,_sellerCoordinator,0, _sellerCost,true); // return returnValue; // } function declineAgreement(address agreementAddress) public { require(agreementsStatus[agreementAddress] == 1, "14"); require(msg.sender == agreementAddress); agreementsStatus[agreementAddress] = 4; } function declineTransaction(address transactionAddress) public { require(transactionsStatus[transactionAddress] == 1, "18"); require(msg.sender == transactionAddress); transactionsStatus[transactionAddress] = 4; } }
require(createdAgreements[agreementAddress].expireTime() > block.timestamp,"5");require(createdAgreements[agreementAddress].counterPermission() == 4, "7 ");
function addAgreement(address agreementAddress) external { require(agreementsStatus[agreementAddress] == 1, "6"); agreements.push(Agreement(address(agreementAddress))); numberOfAgreements++; mainGraph.wrappedAddEdge(createdAgreements[agreementAddress].creditorCoordinator(), createdAgreements[agreementAddress].debtorCoordinator(), createdAgreements[agreementAddress].exchangeRate(),tool.logarithm(int256(createdAgreements[agreementAddress].exchangeRate())),0, createdAgreements[agreementAddress].debtAmount() ,address(agreementAddress)); }
12,966,618
/** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @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; } } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * SourceUnit: d:\GitWork\MintedTunesNFT\contracts\contracts\MintedTunesAuction.sol */ // MintedTunes Auction Contract ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; ////import "@openzeppelin/contracts/utils/math/SafeMath.sol"; ////import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; ////import "@openzeppelin/contracts/access/Ownable.sol"; ////import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; interface IMintedTunesNFT { function safeTransferFrom(address from, address to, uint256 tokenId) external; function creatorOf(uint256 _tokenId) external view returns (address); function royalties(uint256 _tokenId) external view returns (uint256); } contract MintedTunesAuction is Ownable, ERC721Holder { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; uint256 constant public PERCENTS_DIVIDER = 1000; uint256 constant public MIN_BID_INCREMENT_PERCENT = 50; // 5% uint256 public feePercent = 25; // 2.5% address public feeAddress; // Bid struct to hold bidder and amount struct Bid { address from; uint256 bidPrice; } // Auction struct which holds all the required info struct Auction { uint256 auctionId; address collectionId; uint256 tokenId; uint256 startTime; uint256 endTime; uint256 startPrice; address creator; address owner; bool active; } // Array with all auctions Auction[] public auctions; // Mapping from auction index to user bids mapping (uint256 => Bid[]) public auctionBids; // Mapping from owner to a list of owned auctions mapping (address => uint256[]) public ownedAuctions; event BidSuccess(address _from, uint256 _auctionId, uint256 _amount, uint256 _bidIndex); // AuctionCreated is fired when an auction is created event AuctionCreated(Auction auction); // AuctionCanceled is fired when an auction is canceled event AuctionCanceled(uint _auctionId); // AuctionFinalized is fired when an auction is finalized event AuctionFinalized(address buyer, Auction auction, uint256 price); constructor (uint256 _feePercent, address _feeAddress) { feePercent = _feePercent; feeAddress = _feeAddress; } function setFee(uint256 _feePercent, address _feeAddress) external onlyOwner { feePercent = _feePercent; feeAddress = _feeAddress; } /* * @dev Creates an auction with the given informatin * @param _tokenRepositoryAddress address of the TokenRepository contract * @param _tokenId uint256 of the deed registered in DeedRepository * @param _startPrice uint256 starting price of the auction * @return bool whether the auction is created */ function createAuction(address _collectionId, uint256 _tokenId, uint256 _startPrice, uint256 _startTime, uint256 _endTime) onlyTokenOwner(_collectionId, _tokenId) public { require(block.timestamp < _endTime, "end timestamp have to be bigger than current time"); IMintedTunesNFT nft = IMintedTunesNFT(_collectionId); uint256 auctionId = auctions.length; Auction memory newAuction; newAuction.auctionId = auctionId; newAuction.collectionId = _collectionId; newAuction.tokenId = _tokenId; newAuction.startPrice = _startPrice; newAuction.startTime = _startTime; newAuction.endTime = _endTime; newAuction.owner = msg.sender; newAuction.creator = nft.creatorOf(_tokenId); newAuction.active = true; auctions.push(newAuction); ownedAuctions[msg.sender].push(auctionId); nft.safeTransferFrom(msg.sender, address(this), _tokenId); emit AuctionCreated(newAuction); } /** * @dev Finalized an ended auction * @dev The auction should be ended, and there should be at least one bid * @dev On success Deed is transfered to bidder and auction owner gets the amount * @param _auctionId uint256 ID of the created auction */ function finalizeAuction(uint256 _auctionId) public { Auction memory myAuction = auctions[_auctionId]; uint256 bidsLength = auctionBids[_auctionId].length; require(msg.sender == myAuction.owner || msg.sender == owner(), "only auction owner can finalize"); // if there are no bids cancel if(bidsLength == 0) { IMintedTunesNFT(myAuction.collectionId).safeTransferFrom(address(this), myAuction.owner, myAuction.tokenId); auctions[_auctionId].active = false; emit AuctionCanceled(_auctionId); }else{ // 2. the money goes to the auction owner Bid memory lastBid = auctionBids[_auctionId][bidsLength - 1]; address _creator = IMintedTunesNFT(myAuction.collectionId).creatorOf(myAuction.tokenId); uint256 royalty = IMintedTunesNFT(myAuction.collectionId).royalties(myAuction.tokenId); // % commission cut uint256 _adminValue = lastBid.bidPrice.mul(feePercent).div(PERCENTS_DIVIDER); uint256 _creatorValue = lastBid.bidPrice.mul(royalty).div(PERCENTS_DIVIDER); uint256 _sellerValue = lastBid.bidPrice.sub(_adminValue).sub(_creatorValue); if(_adminValue > 0){ payable(feeAddress).transfer(_adminValue); } if(_creatorValue > 0){ payable(_creator).transfer(_creatorValue); } payable(myAuction.owner).transfer(_sellerValue); // approve and transfer from this contract to the bid winner IMintedTunesNFT(myAuction.collectionId).safeTransferFrom(address(this), lastBid.from, myAuction.tokenId); auctions[_auctionId].active = false; emit AuctionFinalized(lastBid.from, myAuction, lastBid.bidPrice); } } /** * @dev Bidder sends bid on an auction * @dev Auction should be active and not ended * @dev Refund previous bidder if a new bid is valid and placed. * @param _auctionId uint256 ID of the created auction */ function bidOnAuction(uint256 _auctionId, uint256 amount) external payable { require(_auctionId <= auctions.length && auctions[_auctionId].auctionId == _auctionId, "Could not find item"); // owner can't bid on their auctions Auction memory myAuction = auctions[_auctionId]; require(myAuction.owner != msg.sender, "owner can not bid"); require(myAuction.active, "not exist"); // if auction is expired require(block.timestamp < myAuction.endTime, "auction is over"); require(block.timestamp >= myAuction.startTime, "auction is not started"); uint256 bidsLength = auctionBids[_auctionId].length; uint256 tempAmount = myAuction.startPrice; Bid memory lastBid; // there are previous bids if( bidsLength > 0 ) { lastBid = auctionBids[_auctionId][bidsLength - 1]; tempAmount = lastBid.bidPrice.mul(PERCENTS_DIVIDER + MIN_BID_INCREMENT_PERCENT).div(PERCENTS_DIVIDER); } // check if amount is greater than previous amount require(amount >= tempAmount, "too small amount"); require(msg.value >= amount, "too small balance"); // refund the last bidder if( bidsLength > 0 ) { payable(lastBid.from).transfer(lastBid.bidPrice); } // insert bid Bid memory newBid; newBid.from = msg.sender; newBid.bidPrice = amount; auctionBids[_auctionId].push(newBid); emit BidSuccess(msg.sender, _auctionId, newBid.bidPrice, bidsLength); } /** * @dev Gets the length of auctions * @return uint256 representing the auction count */ function getAuctionsLength() public view returns(uint) { return auctions.length; } /** * @dev Gets the bid counts of a given auction * @param _auctionId uint256 ID of the auction */ function getBidsAmount(uint256 _auctionId) public view returns(uint) { return auctionBids[_auctionId].length; } /** * @dev Gets an array of owned auctions * @param _owner address of the auction owner */ function getOwnedAuctions(address _owner) public view returns(uint[] memory) { uint[] memory ownedAllAuctions = ownedAuctions[_owner]; return ownedAllAuctions; } /** * @dev Gets an array of owned auctions * @param _auctionId uint256 of the auction owner * @return amount uint256, address of last bidder */ function getCurrentBids(uint256 _auctionId) public view returns(uint256, address) { uint256 bidsLength = auctionBids[_auctionId].length; // if there are bids refund the last bid if (bidsLength >= 0) { Bid memory lastBid = auctionBids[_auctionId][bidsLength - 1]; return (lastBid.bidPrice, lastBid.from); } return (0, address(0)); } /** * @dev Gets the total number of auctions owned by an address * @param _owner address of the owner * @return uint256 total number of auctions */ function getAuctionsAmount(address _owner) public view returns(uint) { return ownedAuctions[_owner].length; } modifier onlyAuctionOwner(uint256 _auctionId) { require(auctions[_auctionId].owner == msg.sender); _; } modifier onlyTokenOwner(address _collectionId, uint256 _tokenId) { address tokenOwner = IERC721(_collectionId).ownerOf(_tokenId); require(tokenOwner == msg.sender); _; } }
Bidder sends bid on an auction Auction should be active and not ended Refund previous bidder if a new bid is valid and placed. _auctionId uint256 ID of the created auction/ owner can't bid on their auctions if auction is expired there are previous bids refund the last bidder
function bidOnAuction(uint256 _auctionId, uint256 amount) external payable { require(_auctionId <= auctions.length && auctions[_auctionId].auctionId == _auctionId, "Could not find item"); Auction memory myAuction = auctions[_auctionId]; require(myAuction.owner != msg.sender, "owner can not bid"); require(myAuction.active, "not exist"); require(block.timestamp < myAuction.endTime, "auction is over"); require(block.timestamp >= myAuction.startTime, "auction is not started"); uint256 bidsLength = auctionBids[_auctionId].length; uint256 tempAmount = myAuction.startPrice; Bid memory lastBid; if( bidsLength > 0 ) { lastBid = auctionBids[_auctionId][bidsLength - 1]; tempAmount = lastBid.bidPrice.mul(PERCENTS_DIVIDER + MIN_BID_INCREMENT_PERCENT).div(PERCENTS_DIVIDER); } require(msg.value >= amount, "too small balance"); if( bidsLength > 0 ) { payable(lastBid.from).transfer(lastBid.bidPrice); } newBid.from = msg.sender; newBid.bidPrice = amount; auctionBids[_auctionId].push(newBid); emit BidSuccess(msg.sender, _auctionId, newBid.bidPrice, bidsLength); }
11,896,971
pragma solidity >=0.5.0 <0.6.0; library AdditiveMath { /** * Adds two numbers and returns the result * THROWS when the result overflows * @return The sum of the arguments */ function add(uint256 x, uint256 y) internal pure returns (uint256) { uint256 sum = x + y; require(sum >= x, "Results in overflow"); return sum; } /** * Subtracts two numbers and returns the result * THROWS when the result underflows * @return The difference of the arguments */ function subtract(uint256 x, uint256 y) internal pure returns (uint256) { require(y <= x, "Results in underflow"); return x - y; } /** * Multiplies two unsigned integers * THROWS when the result overflows * @return The product of the arguments */ function multiply(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 product = x * y; require(product / x == y); return product; } /** * Divides two unsigned integers * THROWS when the result underflows * @return The quotient of the arguments */ function divide(uint256 x, uint256 y) internal pure returns (uint256) { require(y > 0); return x / y; } }
Subtracts two numbers and returns the result THROWS when the result underflows return The difference of the arguments/
function subtract(uint256 x, uint256 y) internal pure returns (uint256) { require(y <= x, "Results in underflow"); return x - y; }
14,038,767
./partial_match/1/0x68592c5c98C4F4A8a4bC6dA2121E65Da3d1c0917/sources/src/upgradeability/AdminUpgradeabilityProxy.sol
Upgrade the backing implementation of the proxy and call a function on the new implementation. This is useful to initialize the proxied contract. newImplementation Address of the new implementation. data Data to send as msg.data in the low level call. It should include the signature and the parameters of the function to be called, as described in/ prettier-ignore solhint-disable-next-line avoid-low-level-calls solhint-disable-next-line reason-string
function upgradeToAndCall( address newImplementation, bytes calldata data ) external payable ifAdmin { _upgradeTo(newImplementation); require(success); }
16,019,558
./full_match/11297108109/0xfF67105819c3c3503b7D18e26Aa85F7901C2eD18/sources/contracts/NFT/PFPCollection.sol
Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) Prevent default sequence
function setStartingIndex() public { _onlyManager(); uint256 targetBlock = _startingIndexBlockNumber; require( targetBlock != 0, "Starting index block number has not been set" ); require(_startingIndex == 0, "Starting index has already been set"); if (block.number.sub(targetBlock) > 255) { targetBlock = block.number - 1; } if (startingIndex_ == 0) { startingIndex_ = startingIndex_.add(1); } emit StartingIndexSet(startingIndex_, targetBlock); _startingIndex = startingIndex_; }
13,236,599
//Address: 0x852de008100cbd305589d8d65850f864056148bd //Contract name: UseChainToken //Balance: 0 Ether //Verification Date: 2/2/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; // Owned contract // ----------------------------------------------------------------------------- contract Controlled { address public controller; function Controlled() public { controller = msg.sender; } modifier onlyController() { require(msg.sender == controller); _; } function changeController(address _newController) public onlyController { controller = _newController; } } // Safe maths, borrowed from OpenZeppelin // ---------------------------------------------------------------------------- library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } // tokenRecipient contract // ---------------------------------------------------------------------------- contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } // standard ERC20 Token interface // ---------------------------------------------------------------------------- contract ERC20Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant public returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant public returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // AddressLimit contract // ---------------------------------------------------------------------------- contract AddressLimit { modifier notContractAddress(address _addr) { require (!isContractAddress(_addr)); _; } function isContractAddress(address _addr) internal constant returns(bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } } // standard ERC20 Token // ---------------------------------------------------------------------------- contract standardToken is ERC20Token, AddressLimit { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; bool public tokenFrozen = true; /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf( address _owner) constant public returns (uint256) { return balances[_owner]; } /// @notice Send `_value` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer( address _to, uint256 _value) public notContractAddress(_to) returns (bool success) { require (!tokenFrozen); // Throw if token is frozen require (balances[msg.sender] >= _value); // Throw if sender has insufficient balance require (balances[_to] + _value >= balances[_to]); // Throw if owerflow detected balances[msg.sender] -= _value; // Deduct senders balance balances[_to] += _value; // Add recivers balance Transfer(msg.sender, _to, _value); // Raise Transfer event return true; } /// @notice `msg.sender` approves `_spender` to spend `_value` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve( address _spender, uint256 _value) public returns (bool success) { require (!tokenFrozen); // Throw if token is frozen allowances[msg.sender][_spender] = _value; // Set allowance Approval(msg.sender, _spender, _value); // Raise Approval event return true; } /// @notice `msg.sender` approves `_spender` to send `_value` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall( address _spender, uint256 _value, bytes _extraData) public returns (bool success) { require (!tokenFrozen); // Throw if token is frozen tokenRecipient spender = tokenRecipient(_spender); // Cast spender to tokenRecipient contract approve(_spender, _value); // Set approval to contract for _value spender.receiveApproval(msg.sender, _value, this, _extraData); // Raise method on _spender contract return true; } /// @notice Send `_value` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _value The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom( address _from, address _to, uint256 _value) public notContractAddress(_to) returns (bool success) { require (!tokenFrozen); // Throw if token is frozen require (balances[_from] >= _value); // Throw if sender does not have enough balance require (balances[_to] + _value >= balances[_to]); // Throw if overflow detected require (_value <= allowances[_from][msg.sender]); // Throw if you do not have allowance balances[_from] -= _value; // Deduct senders balance balances[_to] += _value; // Add recipient balance allowances[_from][msg.sender] -= _value; // Deduct allowance for this address Transfer(_from, _to, _value); // Raise Transfer event return true; } /// @dev This function makes it easy to read the `allowances[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed to spend function allowance( address _owner, address _spender) constant public returns (uint256) { return allowances[_owner][_spender]; } } contract UseChainToken is standardToken, Controlled { /// startCrowdsaleTime stopCrowdsaleTime /// |<private placement>| |<private presale>| |<public sale>| /// o-----------------------o----------------------o------------------------------o /// <10% OFF> <5% OFF> /// payment accepted: <BTC/ETH> <BTC/ETH> <BTC/ETH> using SafeMath for uint; string constant public name = "UseChainToken"; string constant public symbol = "UST"; uint constant public decimals = 18; uint256 public totalSupply = 0; uint256 constant public topTotalSupply = 2*10**7*10**decimals; uint public corporateSupply = percent(topTotalSupply, 20); uint public privatePlacementSupply = percent(topTotalSupply, 8); uint public privatePresaleSupply = percent(topTotalSupply, 12); uint public publicSaleSupply = percent(topTotalSupply, 10); uint public ecoFundSupply = percent(topTotalSupply, 50); uint public softCap = percent(topTotalSupply, 6); uint public startCrowdsaleTime; uint public stopCrowdsaleTime; address public walletAddress; bool public finalized; /// @notice Several stages enum stageAt { notStart, privatePlacement, privatePresale, publicSale, finalState } /// @notice only Wallet address modifier onlyWalletAddr() { require (walletAddress == msg.sender); _; } /// @dev Fallback to calling deposit when ether is sent directly to contract. function() public payable { require(!finalized); depositToken(msg.value); if(this.balance >= 10 ether) { walletAddress.transfer(this.balance); } } /// @notice Initial function function UseChainToken(uint _startCrowdsaleTime, uint _stopCrowdsaleTime, address _walletAddress) public { controller = msg.sender; startCrowdsaleTime = _startCrowdsaleTime; stopCrowdsaleTime = _stopCrowdsaleTime; walletAddress = _walletAddress; } /// @dev Buys tokens with Ether. function depositToken(uint _value) internal { require(_value >= minimalRequire()); uint tokenAlloc = buyPriceAt(exchangePrice * _value); require (tokenAlloc != 0); mintTokens(msg.sender, tokenAlloc); } /// @dev Issue new tokens function mintTokens(address _to, uint _amount) internal { require (balances[_to] + _amount >= balances[_to]); // Check for overflows totalSupply = totalSupply.add(_amount); require(totalSupply <= topTotalSupply); balances[_to] = balances[_to].add(_amount); // Set minted coins to target Transfer(0x0, _to, _amount); // Create Transfer event from 0x0 } /// @notice Minimal requirement function minimalRequire() internal constant returns(uint) { if (stageNow() == stageAt.publicSale) { return 1 ether; } if (stageNow() == stageAt.privatePresale) { return 10 ether; } if (stageNow() == stageAt.privatePlacement) { return 100 ether; } } uint public publicAllocatingToken; uint public privatePlacementAllocatingToken; uint public privatePresaleAllocatingToken; /// @notice Calculate exchange: /// private Placement Stage : 10% OFF /// private Presale Stage : 5% OFF function buyPriceAt(uint256 _tokenAllocWithoutDiscount) internal returns(uint) { if (stageNow() == stageAt.publicSale) { publicAllocatingToken = publicAllocatingToken.add(_tokenAllocWithoutDiscount); require(publicAllocatingToken <= publicSaleSupply); return _tokenAllocWithoutDiscount; } if (stageNow() == stageAt.privatePresale) { uint _privatePresaleAlloc = _tokenAllocWithoutDiscount + percent(_tokenAllocWithoutDiscount, 5); privatePresaleAllocatingToken = privatePresaleAllocatingToken.add(_privatePresaleAlloc); require(privatePresaleAllocatingToken <= privatePresaleSupply); return _privatePresaleAlloc; } if (stageNow() == stageAt.privatePlacement) { uint _privatePlacementAlloc = _tokenAllocWithoutDiscount + percent(_tokenAllocWithoutDiscount, 10); privatePlacementAllocatingToken = privatePlacementAllocatingToken.add(_privatePlacementAlloc); require(privatePlacementAllocatingToken <= privatePlacementSupply); return _privatePlacementAlloc; } if (stageNow() == stageAt.notStart) { return 0; } if (stageNow() == stageAt.finalState) { return 0; } } /// @dev Check the current stage function stageNow() constant internal returns (stageAt) { if (getTimestamp() < startCrowdsaleTime) { return stageAt.notStart; } else if(getTimestamp() < startCrowdsaleTime + 27 days) { return stageAt.privatePlacement; } else if(getTimestamp() < startCrowdsaleTime + 71 days) { return stageAt.privatePresale; } else if(getTimestamp() < stopCrowdsaleTime) { return stageAt.publicSale; } else { return stageAt.finalState; } } /// @dev calcute the tokens function percent(uint _token, uint _percentage) internal pure returns (uint) { return _percentage.mul(_token).div(100); } uint public exchangePrice = 90; /// @dev Set exchange Price function setExchangePrice( uint _price) public onlyController returns(uint) { exchangePrice = _price; } /// @dev Get current timestamp function getTimestamp() internal constant returns(uint) { return now; } function withDraw() public payable onlyController { require (walletAddress != address(0)); walletAddress.transfer(this.balance); } /// @notice unfreeze token transfer function unfreezeTokenTransfer(bool _freeze) public onlyController { tokenFrozen = !_freeze; } /// @notice only wallet address can set new wallet address function setWalletAddress(address _walletAddress) public onlyWalletAddr { walletAddress = _walletAddress; } /// @dev allocate private stage tokens function allocateTokens(address[] _owners, uint256[] _values) public onlyController { require (_owners.length == _values.length); for(uint i = 0; i < _owners.length ; i++){ address owner = _owners[i]; uint value = _values[i]; mintTokens(owner, value); } } function allocateCorporateToken(address _corAccount, uint256 _amount) public onlyController { require(_corAccount != address(0)); require(balances[_corAccount] + _amount <= corporateSupply); mintTokens(_corAccount, _amount); } uint public ecoFundingSupply; function allocateEcoFundToken(address[] _owners, uint256[] _values) public onlyController { require (_owners.length == _values.length); for(uint i = 0; i < _owners.length ; i++){ address owner = _owners[i]; uint256 value = _values[i]; ecoFundingSupply = ecoFundingSupply.add(value); require(ecoFundingSupply <= ecoFundSupply); mintTokens(owner, value); } } /// @notice finalize function finalize() public onlyController { // only after closed stage require(stageNow() == stageAt.finalState); require(totalSupply + ecoFundSupply >= softCap); finalized = true; } }
finalize only after closed stage
function finalize() public onlyController { require(stageNow() == stageAt.finalState); require(totalSupply + ecoFundSupply >= softCap); finalized = true; }
13,024,015
./partial_match/1/0x85F34416D65eE0a3A1376650802cC0447Fe19733/sources/CryptoCollect.sol
For querying owner of token _tokenId The tokenID for owner inquiry Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = collectibleIndexToOwner[_tokenId]; require(owner != address(0)); }
15,673,323
./full_match/3/0x81cef551356E11E5FD0Ca81f139Fec3752921287/sources/browser/PoolPortal.sol
get Bancor converter get converter as contract get connectors and amount approve from portal to converter
function testShit(IERC20 _poolToken, uint256 _amount)public view returns( address[] memory connectorsAddress, uint256[] memory connectorsAmount, uint tokenAmount, uint etherAmount ) { address converterAddress = getBacorConverterAddressByRelay(address(_poolToken)); BancorConverterInterface converter = BancorConverterInterface(converterAddress); (connectorsAddress, connectorsAmount) = getDataForBuyingPool(_poolToken, 0, _amount); for(uint8 i = 0; i < connectorsAddress.length; i++){ if(connectorsAddress[i] != address(ETH_TOKEN_ADDRESS)){ tokenAmount = connectorsAmount[i]; etherAmount = connectorsAmount[i]; } } }
14,191,004
// File: contracts\math\SafeMath.sol pragma solidity 0.5.4; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts\RedTokenAccessControl.sol pragma solidity 0.5.4; /* * @title RedTokenAccessControl * @notice This contract defines organizational roles and permissions. */ contract RedTokenAccessControl { event Paused(); event Unpaused(); event PausedUser(address indexed account); event UnpausedUser(address indexed account); /* * @notice CEO's address */ address public ceoAddress; /* * @notice CFO's address */ address public cfoAddress; /* * @notice COO's address */ address public cooAddress; bool public paused = false; /* * @notice paused users status */ mapping (address => bool) private pausedUsers; /* * @notice init constructor */ constructor () internal { ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; } /* * @dev Modifier to make a function only callable by the CEO */ modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /* * @dev Modifier to make a function only callable by the CFO */ modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /* * @dev Modifier to make a function only callable by the COO */ modifier onlyCOO() { require(msg.sender == cooAddress); _; } /* * @dev Modifier to make a function only callable by C-level execs */ modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /* * @dev Modifier to make a function only callable by CEO or CFO */ modifier onlyCEOOrCFO() { require( msg.sender == cfoAddress || msg.sender == ceoAddress ); _; } /* * @dev Modifier to make a function only callable by CEO or COO */ modifier onlyCEOOrCOO() { require( msg.sender == cooAddress || msg.sender == ceoAddress ); _; } /* * @notice Sets a new CEO * @param _newCEO - the address of the new CEO */ function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /* * @notice Sets a new CFO * @param _newCFO - the address of the new CFO */ function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /* * @notice Sets a new COO * @param _newCOO - the address of the new COO */ function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /* Pausable functionality adapted from OpenZeppelin **/ /* * @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); _; } /* * @notice called by any C-LEVEL to pause, triggers stopped state */ function pause() external onlyCLevel whenNotPaused { paused = true; emit Paused(); } /* * @notice called by any C-LEVEL to unpause, returns to normal state */ function unpause() external onlyCLevel whenPaused { paused = false; emit Unpaused(); } /* user Pausable functionality ref someting : openzeppelin/access/Roles.sol **/ /* * @dev Modifier to make a function callable only when the user is not paused. */ modifier whenNotPausedUser(address account) { require(account != address(0)); require(!pausedUsers[account]); _; } /* * @dev Modifier to make a function callable only when the user is paused. */ modifier whenPausedUser(address account) { require(account != address(0)); require(pausedUsers[account]); _; } /* * @dev check if an account has this pausedUsers * @return bool */ function has(address account) internal view returns (bool) { require(account != address(0)); return pausedUsers[account]; } /* * @notice _addPauseUser */ function _addPauseUser(address account) internal { require(account != address(0)); require(!has(account)); pausedUsers[account] = true; emit PausedUser(account); } /* * @notice _unpausedUser */ function _unpausedUser(address account) internal { require(account != address(0)); require(has(account)); pausedUsers[account] = false; emit UnpausedUser(account); } /* * @notice isPausedUser */ function isPausedUser(address account) external view returns (bool) { return has(account); } /* * @notice called by the COO to pauseUser, triggers stopped user state */ function pauseUser(address account) external onlyCOO whenNotPausedUser(account) { _addPauseUser(account); } /* * @notice called by any C-LEVEL to unpauseUser, returns to user state */ function unpauseUser(address account) external onlyCLevel whenPausedUser(account) { _unpausedUser(account); } } // File: contracts\RedTokenBase.sol pragma solidity 0.5.4; /* * @title RedTokenBase * @notice This contract defines the RedToken data structure and how to read from it / functions */ contract RedTokenBase is RedTokenAccessControl { using SafeMath for uint256; /* * @notice Product defines a RedToken */ struct RedToken { uint256 tokenId; string rmsBondNo; uint256 bondAmount; uint256 listingAmount; uint256 collectedAmount; uint createdTime; bool isValid; } /* * @notice tokenId for share users by listingAmount */ mapping (uint256 => mapping(address => uint256)) shareUsers; /* * @notice tokenid by share accounts in shareUsers list iterator. */ mapping (uint256 => address []) shareUsersKeys; /** events **/ event RedTokenCreated( address account, uint256 tokenId, string rmsBondNo, uint256 bondAmount, uint256 listingAmount, uint256 collectedAmount, uint createdTime ); /* * @notice All redTokens in existence. * @dev The ID of each redToken is an index in this array. */ RedToken[] redTokens; /* * @notice Get a redToken RmsBondNo * @param _tokenId the token id */ function redTokenRmsBondNo(uint256 _tokenId) external view returns (string memory) { return redTokens[_tokenId].rmsBondNo; } /* * @notice Get a redToken BondAmount * @param _tokenId the token id */ function redTokenBondAmount(uint256 _tokenId) external view returns (uint256) { return redTokens[_tokenId].bondAmount; } /* * @notice Get a redToken ListingAmount * @param _tokenId the token id */ function redTokenListingAmount(uint256 _tokenId) external view returns (uint256) { return redTokens[_tokenId].listingAmount; } /* * @notice Get a redToken CollectedAmount * @param _tokenId the token id */ function redTokenCollectedAmount(uint256 _tokenId) external view returns (uint256) { return redTokens[_tokenId].collectedAmount; } /* * @notice Get a redToken CreatedTime * @param _tokenId the token id */ function redTokenCreatedTime(uint256 _tokenId) external view returns (uint) { return redTokens[_tokenId].createdTime; } /* * @notice isValid a redToken * @param _tokenId the token id */ function isValidRedToken(uint256 _tokenId) public view returns (bool) { return redTokens[_tokenId].isValid; } /* * @notice info a redToken * @param _tokenId the token id */ function redTokenInfo(uint256 _tokenId) external view returns (uint256, string memory, uint256, uint256, uint256, uint) { require(isValidRedToken(_tokenId)); RedToken memory _redToken = redTokens[_tokenId]; return ( _redToken.tokenId, _redToken.rmsBondNo, _redToken.bondAmount, _redToken.listingAmount, _redToken.collectedAmount, _redToken.createdTime ); } /* * @notice info a token of share users * @param _tokenId the token id */ function redTokenInfoOfshareUsers(uint256 _tokenId) external view returns (address[] memory, uint256[] memory) { require(isValidRedToken(_tokenId)); uint256 keySize = shareUsersKeys[_tokenId].length; address[] memory addrs = new address[](keySize); uint256[] memory amounts = new uint256[](keySize); for (uint index = 0; index < keySize; index++) { addrs[index] = shareUsersKeys[_tokenId][index]; amounts[index] = shareUsers[_tokenId][addrs[index]]; } return (addrs, amounts); } } // File: contracts\interfaces\ERC721.sol pragma solidity 0.5.4; /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface ERC721 { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external payable; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @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 Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // File: contracts\interfaces\ERC721Metadata.sol pragma solidity 0.5.4; /* * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x5b5e139f */ interface ERC721Metadata /* is ERC721 */ { /* * @notice A descriptive name for a collection of NFTs in this contract */ function name() external pure returns (string memory _name); /* * @notice An abbreviated name for NFTs in this contract */ function symbol() external pure returns (string memory _symbol); /* * @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC * 3986. The URI may point to a JSON file that conforms to the "ERC721 * Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string memory); } // File: contracts\interfaces\ERC721Enumerable.sol pragma solidity 0.5.4; /* * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x780e9d63 */ interface ERC721Enumerable /* is ERC721 */ { /* * @notice Count NFTs tracked by this contract * @return A count of valid NFTs tracked by this contract, where each one of * them has an assigned and queryable owner not equal to the zero address */ function totalSupply() external view returns (uint256); /* * @notice Enumerate valid NFTs * @dev Throws if `_index` >= `totalSupply()`. * @param _index A counter less than `totalSupply()` * @return The token identifier for the `_index`th NFT, * (sort order not specified) */ function tokenByIndex(uint256 _index) external view returns (uint256); /* * @notice Enumerate NFTs assigned to an owner * @dev Throws if `_index` >= `balanceOf(_owner)` or if * `_owner` is the zero address, representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them * @param _index A counter less than `balanceOf(_owner)` * @return The token identifier for the `_index`th NFT assigned to `_owner`, * (sort order not specified) */ function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); } // File: contracts\interfaces\ERC165.sol pragma solidity 0.5.4; interface ERC165 { /* * @notice Query if a contract implements an interface * @param interfaceID The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. * @return `true` if the contract implements `interfaceID` and * `interfaceID` is not 0xffffffff, `false` otherwise */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: contracts\strings\Strings.sol pragma solidity 0.5.4; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } } // File: contracts\interfaces\ERC721TokenReceiver.sol pragma solidity 0.5.4; /* * @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba */ interface ERC721TokenReceiver { /* * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `transfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` * unless throwing */ function onERC721Received(address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4); } // File: contracts\RedTokenOwnership.sol pragma solidity 0.5.4; /* * @title RedTokenOwnership * @notice control by TokenBase. */ contract RedTokenOwnership is RedTokenBase, ERC721, ERC165, ERC721Metadata, ERC721Enumerable { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping (uint256 => uint256) internal ownedTokensIndex; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner address to operator address to approval mapping (address => mapping (address => bool)) internal operatorApprovals; /** events **/ event calculateShareUsers(uint256 tokenId, address owner, address from, address to, uint256 amount); event CollectedAmountUpdate(uint256 tokenId, address owner, uint256 amount); /** Constants **/ // Configure these for your own deployment string internal constant NAME = "RedToken"; string internal constant SYMBOL = "REDT"; string internal tokenMetadataBaseURI = "https://doc.reditus.co.kr/?docid="; /** structs **/ function supportsInterface( bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments external view returns (bool) { return interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x80ac58cd || // ERC-721 interfaceID == 0x780e9d63; // ERC721Enumerable } /* * @notice Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** external functions **/ /* * @notice token's name */ function name() external pure returns (string memory) { return NAME; } /* * @notice symbols's name */ function symbol() external pure returns (string memory) { return SYMBOL; } /* * @notice tokenURI * @dev do not checked in array and used function isValidRedToken value is not important, only check in redTokens array */ function tokenURI(uint256 _tokenId) external view returns (string memory infoUrl) { if ( isValidRedToken(_tokenId) ){ return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId)); }else{ return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId)); } } /* * @notice setTokenMetadataBaseURI */ function setTokenMetadataBaseURI(string calldata _newBaseURI) external onlyCOO { tokenMetadataBaseURI = _newBaseURI; } /* * @notice Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /* * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /* * @notice 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 ownedTokens[_owner].length; } /* * @notice Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[] memory) { require(_owner != address(0)); return ownedTokens[_owner]; } /* * @notice Enumerate valid NFTs * @dev Our Licenses are kept in an array and each new License-token is just * the next element in the array. This method is required for ERC721Enumerable * which may support more complicated storage schemes. However, in our case the * _index is the tokenId * @param _index A counter less than `totalSupply()` * @return The token identifier for the `_index`th NFT */ function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < totalSupply()); return _index; } /* * @notice Enumerate NFTs assigned to an owner * @dev Throws if `_index` >= `balanceOf(_owner)` or if * `_owner` is the zero address, representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them * @param _index A counter less than `balanceOf(_owner)` * @return The token identifier for the `_index`th NFT assigned to `_owner`, */ function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /* * @notice Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /* * @notice 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]; } /* * @notice Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) external payable whenNotPaused whenNotPausedUser(msg.sender) onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /* * @notice Enable or disable approval for a third party ("operator") to manage all your assets * @dev Emits the ApprovalForAll event * @param _to Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval */ function setApprovalForAll(address _to, bool _approved) external whenNotPaused whenNotPausedUser(msg.sender) { if(_approved) { approveAll(_to); } else { disapproveAll(_to); } } /* * @notice Approves another address to claim for the ownership of any tokens owned by this account * @param _to address to be approved for the given token ID */ function approveAll(address _to) public payable whenNotPaused whenNotPausedUser(msg.sender) { require(_to != msg.sender); require(_to != address(0)); operatorApprovals[msg.sender][_to] = true; emit ApprovalForAll(msg.sender, _to, true); } /* * @notice Removes approval for another address to claim for the ownership of any * tokens owned by this account. * @dev Note that this only removes the operator approval and * does not clear any independent, specific approvals of token transfers to this address * @param _to address to be disapproved for the given token ID */ function disapproveAll(address _to) public payable whenNotPaused whenNotPausedUser(msg.sender) { require(_to != msg.sender); delete operatorApprovals[msg.sender][_to]; emit ApprovalForAll(msg.sender, _to, false); } /* * @notice Transfer a token owned by another address, for which the calling address has * previously been granted transfer approval by the owner. * @param _from The address that owns the token * @param _to The address that will take ownership of the token. Can be any address, including the caller * @param _tokenId The ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public payable whenNotPaused { require(isSenderApprovedFor(_tokenId)); require(ownerOf(_tokenId) == _from); _clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId); } /* * @notice Transfers the ownership of an NFT from one address to another address * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. When transfer is complete, this function * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public payable whenNotPaused whenNotPausedUser(msg.sender) { require(_to != address(0)); require(isValidRedToken(_tokenId)); transferFrom(_from, _to, _tokenId); if (isContract(_to)) { bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)( _from, _tokenId, _data ); require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /* * @notice Tells whether the msg.sender is approved to transfer the given token ID or not * Checks both for specific approval and operator approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether transfer by msg.sender is approved for the given token ID or not */ function isSenderApprovedFor(uint256 _tokenId) public view returns (bool) { return ownerOf(_tokenId) == msg.sender || getApproved(_tokenId) == msg.sender || isApprovedForAll(ownerOf(_tokenId), msg.sender); } /* * @notice Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) external payable whenNotPaused onlyOwnerOf(_tokenId) { _clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /* * @notice Transfers the ownership of an NFT from one address to another address * @dev This works identically to the other function with an extra data parameter, * except this function just sets data to "" * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external payable { safeTransferFrom(_from, _to, _tokenId, ""); } /* * @notice send amount shareUsers */ function sendAmountShareUsers( uint256 _tokenId, address _to, uint256 _amount ) external onlyCOO returns (bool) { require(_to != address(0)); return _calculateShareUsers(_tokenId, ownerOf(_tokenId), _to, _amount); } /* * @notice send amount shareUsers */ function sendAmountShareUsersFrom( uint256 _tokenId, address _from, address _to, uint256 _amount ) external onlyCOO returns (bool) { require(_to != address(0)); return _calculateShareUsers(_tokenId, _from, _to, _amount); } /* * @notice update collectedAmount */ function updateCollectedAmount(uint256 _tokenId, uint256 _amount) external onlyCOO returns (bool) { require(isValidRedToken(_tokenId)); require(_amount > 0); address owner = ownerOf(_tokenId); redTokens[_tokenId].collectedAmount = redTokens[_tokenId].collectedAmount.add(_amount); emit CollectedAmountUpdate(_tokenId, owner, _amount); return true; } /* * @notice createRedToken */ function createRedToken( address _user, string calldata _rmsBondNo, uint256 _bondAmount, uint256 _listingAmount ) external onlyCOO returns (uint256) { return _createRedToken(_user,_rmsBondNo,_bondAmount,_listingAmount); } /* * @notice burn amount a token by share users */ function burnAmountByShareUser( uint256 _tokenId, address _from, uint256 _amount ) external onlyCOO returns (bool) { return _calculateShareUsers(_tokenId, _from, address(0), _amount); } /* * @notice burn RedToken */ function burn(address _owner, uint256 _tokenId) external onlyCOO returns(bool) { require(_owner != address(0)); return _burn(_owner, _tokenId); } /** internal function **/ function isContract(address _addr) internal view returns (bool) { uint size; assembly { size := extcodesize(_addr) } return size > 0; } /* * @notice checked shareUser by shareUsersKeys */ function isShareUser(uint256 _tokenId, address _from) internal onlyCOO view returns (bool) { bool chechedUser = false; for (uint index = 0; index < shareUsersKeys[_tokenId].length; index++) { if ( shareUsersKeys[_tokenId][index] == _from ){ chechedUser = true; break; } } return chechedUser; } /* * @notice Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function _clearApprovalAndTransfer( address _from, address _to, uint256 _tokenId ) whenNotPausedUser(msg.sender) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); require(isValidRedToken(_tokenId)); _clearApproval(_from, _tokenId); _removeToken(_from, _tokenId); _addToken(_to, _tokenId); _changeTokenShareUserByOwner(_from, _to, _tokenId); emit Transfer(_from, _to, _tokenId); } /* * @notice change token owner rate sending * @param _from address which you want to change rate from * @param _to address which you want to change rate the token to * @param _tokenId uint256 ID of the token to be change rate */ function _changeTokenShareUserByOwner( address _from, address _to, uint256 _tokenId ) internal onlyCOO { uint256 amount = shareUsers[_tokenId][_from]; delete shareUsers[_tokenId][_from]; shareUsers[_tokenId][_to] = shareUsers[_tokenId][_to].add(amount); if ( !isShareUser(_tokenId, _to) ) { shareUsersKeys[_tokenId].push(_to); } } /* * @notice remove shareUsers */ function _calculateShareUsers( uint256 _tokenId, address _from, address _to, uint256 _amount ) internal onlyCOO returns (bool) { require(_from != address(0)); require(_from != _to); require(_amount > 0); require(shareUsers[_tokenId][_from] >= _amount); require(isValidRedToken(_tokenId)); address owner = ownerOf(_tokenId); shareUsers[_tokenId][_from] = shareUsers[_tokenId][_from].sub(_amount); shareUsers[_tokenId][_to] = shareUsers[_tokenId][_to].add(_amount); if ( !isShareUser(_tokenId, _to) ) { shareUsersKeys[_tokenId].push(_to); } emit calculateShareUsers(_tokenId, owner, _from, _to, _amount); return true; } /* * @notice Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } function _createRedToken(address _user, string memory _rmsBondNo, uint256 _bondAmount, uint256 _listingAmount) private returns (uint256){ require(_user != address(0)); require(bytes(_rmsBondNo).length > 0); require(_bondAmount > 0); require(_listingAmount > 0); uint256 _newTokenId = redTokens.length; RedToken memory _redToken = RedToken({ tokenId: _newTokenId, rmsBondNo: _rmsBondNo, bondAmount: _bondAmount, listingAmount: _listingAmount, collectedAmount: 0, createdTime: now, isValid:true }); redTokens.push(_redToken) - 1; shareUsers[_newTokenId][_user] = shareUsers[_newTokenId][_user].add(_listingAmount); shareUsersKeys[_newTokenId].push(_user); _addToken(_user, _newTokenId); emit RedTokenCreated(_user, _redToken.tokenId, _redToken.rmsBondNo, _redToken.bondAmount, _redToken.listingAmount, _redToken.collectedAmount, _redToken.createdTime); return _newTokenId; } /* * @notice Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /* * @notice Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = address(0); ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } /* * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) private returns(bool) { require(ownerOf(_tokenId) == _owner); _clearApproval(_owner, _tokenId); _removeToken(_owner, _tokenId); redTokens[_tokenId].isValid = false; emit Transfer(_owner, address(0), _tokenId); return true; } } // File: contracts\RedTokenCore.sol pragma solidity 0.5.4; /* * @title RedTokenCore is the entry point of the contract * @notice RedTokenCore is the entry point and it controls the ability to set a new * contract address, in the case where an upgrade is required */ contract RedTokenCore is RedTokenOwnership{ constructor() public { ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; } function() external { assert(false); } }
isPausedUser/
function isPausedUser(address account) external view returns (bool) { return has(account); }
14,082,375
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { DataTypes } from "./DataTypes.sol"; import { RLPWriter } from "./RLPWriter.sol"; /** * @title TransactionParser */ library TransactionParser { /* * Internal Functions */ /** * Utility; computes the hash of a given transaction. * @param _transaction OVM transaction to hash. * @return Hash of the provided transaction. */ function getTransactionHash( DataTypes.OVMTransactionData memory _transaction ) internal pure returns (bytes32) { bytes memory encodedTransaction = encodeTransactionData(_transaction); return keccak256(encodedTransaction); } /** * Utility; RLP encodes an OVMTransactionData struct. * @dev Likely to be changed (if not moved to another contract). Currently * remaining here as to avoid modifying CanonicalTransactionChain. Unclear * whether or not this is the correct transaction structure, but it should * work for the meantime. * @param _transactionData Transaction data to encode. * @return RLP encoded transaction data. */ function encodeTransactionData( DataTypes.OVMTransactionData memory _transactionData ) internal pure returns (bytes memory) { bytes[] memory raw = new bytes[](8); raw[0] = RLPWriter.encodeUint(_transactionData.timestamp); raw[1] = RLPWriter.encodeUint(_transactionData.queueOrigin); raw[2] = RLPWriter.encodeAddress(_transactionData.ovmEntrypoint); raw[3] = RLPWriter.encodeBytes(_transactionData.callBytes); raw[4] = RLPWriter.encodeAddress(_transactionData.fromAddress); raw[5] = RLPWriter.encodeAddress(_transactionData.l1MsgSenderAddress); raw[6] = RLPWriter.encodeUint(_transactionData.gasLimit); raw[7] = RLPWriter.encodeBool(_transactionData.allowRevert); return RLPWriter.encodeList(raw); } }
Utility; RLP encodes an OVMTransactionData struct. Likely to be changed (if not moved to another contract). Currently remaining here as to avoid modifying CanonicalTransactionChain. Unclear whether or not this is the correct transaction structure, but it should work for the meantime. _transactionData Transaction data to encode. return RLP encoded transaction data./
function encodeTransactionData( DataTypes.OVMTransactionData memory _transactionData ) internal pure returns (bytes memory) { bytes[] memory raw = new bytes[](8); raw[0] = RLPWriter.encodeUint(_transactionData.timestamp); raw[1] = RLPWriter.encodeUint(_transactionData.queueOrigin); raw[2] = RLPWriter.encodeAddress(_transactionData.ovmEntrypoint); raw[3] = RLPWriter.encodeBytes(_transactionData.callBytes); raw[4] = RLPWriter.encodeAddress(_transactionData.fromAddress); raw[5] = RLPWriter.encodeAddress(_transactionData.l1MsgSenderAddress); raw[6] = RLPWriter.encodeUint(_transactionData.gasLimit); raw[7] = RLPWriter.encodeBool(_transactionData.allowRevert); return RLPWriter.encodeList(raw); }
6,406,763
/** *Submitted for verification at Etherscan.io on 2022-03-03 */ /** Contract is by captain ike and frens ,--. ,--. ,--.,--. ,---. ,--,--. ,---. ,-' '-. ,--,--.`--',--,--, `--'| |,-. ,---. | .--'' ,-. || .-. |'-. .-'' ,-. |,--.| \ ,--.| /| .-. : \ `--.\ '-' || '-' ' | | \ '-' || || || | | || \ \\ --. `---' `--`--'| |-' `--' `--`--'`--'`--''--' `--'`--'`--'`----' `--' */ // SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/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: @openzeppelin/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; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol 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/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: @openzeppelin/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: @openzeppelin/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: @openzeppelin/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/CaptainIke.sol pragma solidity ^0.8.4; contract CaptainIke is Ownable, ERC721 { event Mint(uint256 indexed _tokenId); uint256 public maxSupply = 6942; // Maximum tokens that can be minted uint256 public limitPerAccount = 69; // Maximum mints per wallet uint256 public mintFee = 0.069420 ether; // Price per mint uint256 public totalSupply = 0; // This is our mint counter as well mapping(uint256 => string) public tokenURIs; // Metadata location, updatable by owner mapping(address => uint256) public mintCounts; // Amount minted per user string public _baseTokenURI = "https://gateway.pinata.cloud/ipfs/QmQ5GQR8k8mBwGvWeAfeW2uYE4wHLPzRBAhnCPUZpRgSBX?preview=1"; // Same for all tokens mapping(address => bool) public canWithdraw; bool public paused = true; constructor() payable ERC721("CaptainIke", "Icarus") {} function mint(address to, uint256 quantity) external payable { require( totalSupply + quantity <= maxSupply, "maxSupply of mints already reached" ); if (msg.sender != owner()) { require(!paused, "Paused"); require( mintCounts[to] + quantity <= limitPerAccount, "max 69 mints per account" ); require( quantity * mintFee == msg.value, "Pay 0.069420 eth per mint" ); } mintCounts[to] += quantity; for (uint256 i = 0; i < quantity; i++) { totalSupply += 1; // 1-indexed instead of 0 _mint(to, totalSupply); emit Mint(totalSupply); } } /** * @dev Returns a URI for a given token ID's metadata */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId))); } // ADMIN FUNCTIONALITY /** * @dev Withdraw ETH */ function withdraw() public { require(msg.sender == owner() || canWithdraw[msg.sender], "Nice try!"); uint256 amount = address(this).balance; (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Failed to send ether"); } /** * @dev Pauses or unpauses the contract */ function setPaused(bool _paused) public onlyOwner { paused = _paused; } /** * @dev Adds an address to the withdraw whitelist */ function setWhitelist(address addr, bool val) public onlyOwner { canWithdraw[addr] = val; } /** * @dev Updates the base token URI for the metadata */ function setBaseTokenURI(string memory __baseTokenURI) public onlyOwner { _baseTokenURI = __baseTokenURI; } }
Replacement for Solidity's `transfer`: sends `amount` wei to `recipient`, forwarding all available gas and reverting on errors. 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. IMPORTANT: because control is transferred to `recipient`, care must be taken to not create reentrancy vulnerabilities. Consider using {ReentrancyGuard} or the/ solhint-disable-next-line avoid-low-level-calls, avoid-call-value
function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); require( success, "Address: unable to send value, recipient may have reverted" ); }
2,311,596
pragma solidity ^0.4.11; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { revert(); } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart 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 BasicToken, ERC20 { mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) revert(); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint64 time) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, uint64(now))) revert(); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint _value) canTransfer(msg.sender, _value) { super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) { super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { return balanceOf(holder); } } /** * @title Vested token * @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior if (_cliff < _start || _vesting < _cliff) { revert(); } if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) revert(); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint _grantId) public { TokenGrant grant = grants[_holder][_grantId]; if (!grant.revokable) { // Check if grant was revokable revert(); } if (grant.granter != msg.sender) { // Only granter can revoke it revert(); } address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint representing a holder's total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) constant public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint representing the total amount of grants. */ function tokenGrantsCount(address _holder) constant returns (uint index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) constant returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = SafeMath.div( SafeMath.mul( tokens, SafeMath.sub(time, start) ), SafeMath.sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = SafeMath.max64(grants[holder][i].vesting, date); } } } // QUESTIONS FOR AUDITORS: // - Considering we inherit from VestedToken, how much does that hit at our gas price? // - Ensure max supply is 98,000,000 // - Ensure that even if not totalSupply is sold, tokens would still be transferrable after (we will up to totalSupply by creating WPX tokens) // vesting: 365 days, 365 days / 4 vesting contract WPXToken is VestedToken { //FIELDS string public name = "WorkPress"; //(important input) string public symbol = "WPX"; //(important input) uint public decimals = 4; //(important input) // Multiplier for the decimals uint private constant DECIMALS = 10000; uint public totalSupply = 98000000*DECIMALS; //(important input) //CONSTANTS //Time limits uint public constant STAGE_ONE_TIME_END = 38 days; // first day bonus (important input) uint public constant STAGE_TWO_TIME_END = 58 days; // first week bonus (important input) uint public constant STAGE_THREE_TIME_END = 69 days; //(important input) //Prices of WPX uint public constant PRICE_STANDARD = 2000*DECIMALS; // WPX received per one ETH; Approximately $0.15 if ETH price $300. MAX_SUPPLY / (valuation / ethPrice) uint public constant PRICE_STAGE_ONE = PRICE_STANDARD * 150/100; // 1ETH = 100% Bonus 1.5X or 50% 1ETH = 3000 WPX ~ $0.10(important input) uint public constant PRICE_STAGE_TWO = PRICE_STANDARD * 125/100; // 1ETH = 25% ICO Bonus 1ETH = 2500 WPX ~ $0.125(important input) uint public constant PRICE_STAGE_THREE = PRICE_STANDARD; // Standard Price no bonus 1ETH = 2000 WPX ~ $0.15(important input) //WPX Token Limits uint public constant ALLOC_TEAM = 10000000*DECIMALS; // team + advisors to main address (important input) uint public constant ALLOC_BOUNTIES = 3000000*DECIMALS; // Reserved Address (important input) uint public constant ALLOC_WINGS = 5000000*DECIMALS; // Reserved Address (important input) uint public constant ALLOC_CROWDSALE = 80000000*DECIMALS; // Crowdsale to Main address (important input) uint public constant PREBUY_PORTION_MAX = 20000000*DECIMALS; // this is redundantly more than what will be pre-sold //ASSIGNED IN INITIALIZATION //Start and end times uint public publicStartTime; // Time in seconds public crowd fund starts. uint public privateStartTime; // Time in seconds - at this time there is no intention to do a private session. uint public publicEndTime; // Time in seconds crowdsale ends uint public hardcapInEth; //Special Addresses address public multisigAddress; // Address to which all ether flows. address public wpxTeamAddress; // Address to which ALLOC_TEAM, ALLOC_BOUNTIES, ALLOC_WINGS is (ultimately) sent to. address public ownerAddress; // Address of the contract owner. Can halt the crowdsale. address public preBuy1; // Address used by pre-buy address public preBuy2; // Address used by pre-buy address public preBuy3; // Address used by pre-buy uint public preBuyPrice1; // price for pre-buy uint public preBuyPrice2; // price for pre-buy uint public preBuyPrice3; // price for pre-buy //Running totals uint public etherRaised; // Total Ether raised. uint public WPXSold; // Total WPX created uint public prebuyPortionTotal; // Total of Tokens purchased by pre-buy. Not to exceed PREBUY_PORTION_MAX. //booleans bool public halted; // halts the crowd sale if true. // MODIFIERS //Is currently in the period after the private start time and before the public start time. modifier is_pre_crowdfund_period() { if (now >= publicStartTime || now < privateStartTime) revert(); _; } //Is currently the crowdfund period modifier is_crowdfund_period() { if (now < publicStartTime) revert(); if (isCrowdfundCompleted()) revert(); _; } // Is completed modifier is_crowdfund_completed() { if (!isCrowdfundCompleted()) revert(); _; } function isCrowdfundCompleted() internal returns (bool) { if (now > publicEndTime || WPXSold+50000*DECIMALS >= ALLOC_CROWDSALE || etherRaised >= hardcapInEth*1000000000000000000) {return true; } return false; } //May only be called by the owner address modifier only_owner() { if (msg.sender != ownerAddress) revert(); _; } //May only be called if the crowdfund has not been halted modifier is_not_halted() { if (halted) revert(); _; } // EVENTS event PreBuy(uint _amount); event Buy(address indexed _recipient, uint _amount); // Initialization contract assigns address of crowdfund contract and end time. function WPXToken( address _multisig, address _wpxTeam, uint _publicStartTime, uint _privateStartTime, uint _hardcapInEth, address _prebuy1, uint _preBuyPrice1, address _prebuy2, uint _preBuyPrice2, address _prebuy3, uint _preBuyPrice3 ) { ownerAddress = msg.sender; publicStartTime = _publicStartTime; privateStartTime = _privateStartTime; publicEndTime = _publicStartTime + 69 days; // (important input) multisigAddress = _multisig; wpxTeamAddress = _wpxTeam; hardcapInEth = _hardcapInEth; preBuy1 = _prebuy1; preBuyPrice1 = _preBuyPrice1; preBuy2 = _prebuy2; preBuyPrice2 = _preBuyPrice2; preBuy3 = _prebuy3; preBuyPrice3 = _preBuyPrice3; balances[wpxTeamAddress] += ALLOC_BOUNTIES; balances[wpxTeamAddress] += ALLOC_WINGS; balances[ownerAddress] += ALLOC_TEAM; balances[ownerAddress] += ALLOC_CROWDSALE; } // Transfer amount of tokens from sender account to recipient. // Only callable after the crowd fund is completed function transfer(address _to, uint _value) { if (_to == msg.sender) return; // no-op, allow even during crowdsale, in order to work around using grantVestedTokens() while in crowdsale if (!isCrowdfundCompleted()) revert(); super.transfer(_to, _value); } // Transfer amount of tokens from a specified address to a recipient. // Transfer amount of tokens from sender account to recipient. function transferFrom(address _from, address _to, uint _value) is_crowdfund_completed { super.transferFrom(_from, _to, _value); } //constant function returns the current WPX price. function getPriceRate() constant returns (uint o_rate) { uint delta = SafeMath.sub(now, publicStartTime); if (delta > STAGE_TWO_TIME_END) return PRICE_STAGE_THREE; if (delta > STAGE_ONE_TIME_END) return PRICE_STAGE_TWO; return (PRICE_STAGE_ONE); } // calculates wmount of WPX we get, given the wei and the rates we've defined per 1 eth function calcAmount(uint _wei, uint _rate) constant returns (uint) { return SafeMath.div(SafeMath.mul(_wei, _rate), 1 ether); } // Given the rate of a purchase and the remaining tokens in this tranche, it // will throw if the sale would take it past the limit of the tranche. // Returns `amount` in scope as the number of WPX tokens that it will purchase. function processPurchase(uint _rate, uint _remaining) internal returns (uint o_amount) { o_amount = calcAmount(msg.value, _rate); if (o_amount > _remaining) revert(); if (!multisigAddress.send(msg.value)) revert(); balances[ownerAddress] = balances[ownerAddress].sub(o_amount); balances[msg.sender] = balances[msg.sender].add(o_amount); WPXSold += o_amount; etherRaised += msg.value; } //Special Function can only be called by pre-buy and only during the pre-crowdsale period. function preBuy() payable is_pre_crowdfund_period is_not_halted { // Pre-buy participants would get the first-day price, as well as a bonus of vested tokens uint priceVested = 0; if (msg.sender == preBuy1) priceVested = preBuyPrice1; if (msg.sender == preBuy2) priceVested = preBuyPrice2; if (msg.sender == preBuy3) priceVested = preBuyPrice3; if (priceVested == 0) revert(); uint amount = processPurchase(PRICE_STAGE_ONE + priceVested, SafeMath.sub(PREBUY_PORTION_MAX, prebuyPortionTotal)); grantVestedTokens(msg.sender, calcAmount(msg.value, priceVested), uint64(now), uint64(now) + 91 days, uint64(now) + 365 days, false, false ); prebuyPortionTotal += amount; PreBuy(amount); } //Default function called by sending Ether to this address with no arguments. //Results in creation of new WPX Tokens if transaction would not exceed hard limit of WPX Token. function() payable is_crowdfund_period is_not_halted { uint amount = processPurchase(getPriceRate(), SafeMath.sub(ALLOC_CROWDSALE, WPXSold)); Buy(msg.sender, amount); } // To be called at the end of crowdfund period // WARNING: transfer(), which is called by grantVestedTokens(), wants a minimum message length function grantVested(address _wpxTeamAddress, address _wpxFundAddress) is_crowdfund_completed only_owner is_not_halted { // Grant tokens pre-allocated for the team grantVestedTokens( _wpxTeamAddress, ALLOC_TEAM, uint64(now), uint64(now) + 91 days , uint64(now) + 365 days, false, false ); // Grant tokens that remain after crowdsale to the WPX fund, vested for 2 years grantVestedTokens( _wpxFundAddress, balances[ownerAddress], uint64(now), uint64(now) + 182 days , uint64(now) + 730 days, false, false ); } //May be used by owner of contract to halt crowdsale and no longer except ether. function toggleHalt(bool _halted) only_owner { halted = _halted; } //failsafe drain function drain() only_owner { if (!ownerAddress.send(this.balance)) revert(); } }
Calculate the amount of non vested tokens at a specific time. grant TokenGrant The grant to be checked. time uint64 The time to be checked return An uint representing the amount of non vested tokens of a specifc grant on the passed time frame./
function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); }
5,424,902
./full_match/4/0x514fd962486337d597b43cbFC1F204Ca1EB8493B/sources/erc721a/ERC721A.sol
Returns the unpacked `TokenOwnership` struct from `packed`./
function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) { ownership.addr = address(uint160(packed)); ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP); ownership.burned = packed & _BITMASK_BURNED != 0; ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA); }
730,011
./full_match/1/0xBf7EE8D41fA851fa94D4E908209aD1A97E13EDD9/sources/POE/GovPOE.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), "POE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "POE::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "POE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
3,179,251
./full_match/42220/0x893Bf1159213B3E412f058631fb239C43b394976/sources/contracts/managed/CircuitBreakerStorageLib.sol
Sets the reference BPT price, normalized weight, and upper and lower bounds for a token. If a bound is zero, it means there is no circuit breaker in that direction for the given token. bptPrice: The BPT price of the token at the time the circuit breaker is set. The BPT Price of a token is generally given by: supply weight / balance. referenceWeight: This is the current normalized weight of the token. lowerBound: The value of the lower bound, expressed as a percentage. upperBound: The value of the upper bound, expressed as a percentage./ It's theoretically not required for the lower bound to be < 1, but it wouldn't make much sense otherwise: the circuit breaker would immediately trip. Note that this explicitly allows setting either to 0, disabling the circuit breaker for the token in that direction. Set the reference parameters: BPT price of the token, and the reference weight. Add the lower and upper percentage bounds. Compress by shifting right. Precompute and store the adjusted bounds, used to convert percentage bounds to BPT price bounds. If the weight has not changed since the breaker was set, we can use the precomputed values directly, and avoid a heavy computation. Finally, insert these computed adjusted bounds, and return the complete set of fields.
function setCircuitBreaker( uint256 bptPrice, uint256 referenceWeight, uint256 lowerBound, uint256 upperBound ) internal pure returns (bytes32) { _require( lowerBound == 0 || (lowerBound >= _MIN_BOUND_PERCENTAGE && lowerBound <= FixedPoint.ONE), Errors.INVALID_CIRCUIT_BREAKER_BOUNDS ); _require(upperBound <= _MAX_BOUND_PERCENTAGE, Errors.INVALID_CIRCUIT_BREAKER_BOUNDS); _require(upperBound == 0 || upperBound >= lowerBound, Errors.INVALID_CIRCUIT_BREAKER_BOUNDS); bytes32 circuitBreakerState = bytes32(0).insertUint(bptPrice, _BPT_PRICE_OFFSET, _BPT_PRICE_WIDTH).insertUint( referenceWeight, _REFERENCE_WEIGHT_OFFSET, _REFERENCE_WEIGHT_WIDTH ); circuitBreakerState = circuitBreakerState .insertUint(lowerBound >> _BOUND_SHIFT_BITS, _LOWER_BOUND_OFFSET, _BOUND_WIDTH) .insertUint(upperBound >> _BOUND_SHIFT_BITS, _UPPER_BOUND_OFFSET, _BOUND_WIDTH); uint256 adjustedLowerBound = CircuitBreakerLib.calcAdjustedBound(lowerBound, referenceWeight, true); uint256 adjustedUpperBound = CircuitBreakerLib.calcAdjustedBound(upperBound, referenceWeight, false); return circuitBreakerState .insertUint( adjustedLowerBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE), _ADJUSTED_LOWER_BOUND_OFFSET, _ADJUSTED_BOUND_WIDTH ) .insertUint( adjustedUpperBound.compress(_ADJUSTED_BOUND_WIDTH, _MAX_BOUND_PERCENTAGE), _ADJUSTED_UPPER_BOUND_OFFSET, _ADJUSTED_BOUND_WIDTH ); }
16,314,124
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public _totalSupply; function totalSupply() public constant returns (uint); function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is Ownable, ERC20Basic { using SafeMath for uint; mapping(address => uint) public balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(msg.sender, owner, fee); } Transfer(msg.sender, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(_from, owner, fee); } Transfer(_from, _to, sendAmount); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract BlackList is Ownable, BasicToken { /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded EUROQUINNToken) /////// function getBlackListStatus(address _maker) external constant returns (bool) { return isBlackListed[_maker]; } function getOwner() external constant returns (address) { return owner; } mapping (address => bool) public isBlackListed; function addBlackList (address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; AddedBlackList(_evilUser); } function removeBlackList (address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; RemovedBlackList(_clearedUser); } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); } contract UpgradedStandardToken is StandardToken{ // those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address function transferByLegacy(address from, address to, uint value) public; function transferFromByLegacy(address sender, address from, address spender, uint value) public; function approveByLegacy(address from, address spender, uint value) public; } contract EUROQUINNToken is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // The contract can be initialized with a number of tokens // All the tokens are deposited to the owner address // // @param _balance Initial supply of the contract // @param _name Token Name // @param _symbol Token symbol // @param _decimals Token decimals function EUROQUINNToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Forward ERC20 methods to upgraded contract if this one is deprecated function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // deprecate current contract in favour of a new one function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; Deprecate(_upgradedAddress); } // deprecate current contract if favour of a new one function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issuedi function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; Redeem(amount); } function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Ensure transparency by hardcoding limit beyond which fees can never be added require(newBasisPoints < 20); require(newMaxFee < 50); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); Params(basisPointsRate, maximumFee); } // Called when new token are issued event Issue(uint amount); // Called when tokens are redeemed event Redeem(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee); }
Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); return super.transferFrom(_from, _to, _value); } }
436,262
pragma solidity ^0.4.18; /** * @title ExampleDivisibleNFTs * @dev Exploring the need for a non-fungible token to have multiple owners with different shares * * @dev A 'unit' in this example is the minimum part of a token that an owner can have. * * @notice This is just an example for the Ethereum request for comments section * @notice This code is of course UNSAFE & NON SECURE */ contract ExampleDivisibleNFTs { // ------------------------------ Variables ------------------------------ // Percentage of ownership over a token mapping(address => mapping(uint => uint)) ownerToTokenShare; // How much owners have of a token mapping(uint => mapping(address => uint)) tokenToOwnersHoldings; // If a token has been created mapping(uint => bool) mintedToken; // Number of equal(fungible) units that constitute a token (that a token can be divised to) uint public divisibility = 1000; // All tokens have the same divisibility in our example // total of managed/tracked tokens by this smart contract uint public totalSupply; // ------------------------------ Modifiers ------------------------------ modifier onlyNonExistentToken(uint _tokenId) { require(mintedToken[_tokenId] == false); _; } modifier onlyExistentToken(uint _tokenId) { require(mintedToken[_tokenId] == true); _; } // ------------------------------ View functions ------------------------------ /// @dev The balance an owner have of a token function unitsOwnedOfAToken(address _owner, uint _tokenId) public view returns (uint _balance) { return ownerToTokenShare[_owner][_tokenId]; } // ------------------------------ Core public functions ------------------------------ /// @dev Anybody can create a token in our example /// @notice Minting grants 100% of the token to a new owner in our example function mint(address _owner, uint _tokenId) public onlyNonExistentToken (_tokenId) { mintedToken[_tokenId] = true; _addShareToNewOwner(_owner, _tokenId, divisibility); _addNewOwnerHoldingsToToken(_owner, _tokenId, divisibility); totalSupply = totalSupply + 1; //Minted(_owner, _tokenId); // emit event } /// @dev transfer parts of a token to another user function transfer(address _to, uint _tokenId, uint _units) public onlyExistentToken (_tokenId) { require(ownerToTokenShare[msg.sender][_tokenId] >= _units); // TODO should check _to address to avoid losing tokens units _removeShareFromLastOwner(msg.sender, _tokenId, _units); _removeLastOwnerHoldingsFromToken(msg.sender, _tokenId, _units); _addShareToNewOwner(_to, _tokenId, _units); _addNewOwnerHoldingsToToken(_to, _tokenId, _units); //Transfer(msg.sender, _to, _tokenId, _units); // emit event } // ------------------------------ Helper functions (internal functions) ------------------------------ // Remove token units from last owner function _removeShareFromLastOwner(address _owner, uint _tokenId, uint _units) internal { ownerToTokenShare[_owner][_tokenId] -= _units; } // Add token units to new owner function _addShareToNewOwner(address _owner, uint _tokenId, uint _units) internal { ownerToTokenShare[_owner][_tokenId] += _units; } // Remove units from last owner function _removeLastOwnerHoldingsFromToken(address _owner, uint _tokenId, uint _units) internal { tokenToOwnersHoldings[_tokenId][_owner] -= _units; } // Add the units to new owner function _addNewOwnerHoldingsToToken(address _owner, uint _tokenId, uint _units) internal { tokenToOwnersHoldings[_tokenId][_owner] += _units; } }
Anybody can create a token in our example Minting grants 100% of the token to a new owner in our exampleMinted(_owner, _tokenId); emit event
function mint(address _owner, uint _tokenId) public onlyNonExistentToken (_tokenId) { mintedToken[_tokenId] = true; _addShareToNewOwner(_owner, _tokenId, divisibility); _addNewOwnerHoldingsToToken(_owner, _tokenId, divisibility); totalSupply = totalSupply + 1; }
14,049,372
// SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } // File: @openzeppelin/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: @openzeppelin/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: @openzeppelin/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) { return msg.data; } } // File: @openzeppelin/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}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/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() { _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); } } // Contract: NikNames // TokenID: Cryptic Keys // Token Symbol: CRYPKEYS // Author: Sean Pentiboyina // ---- CONTRACT BEGINS HERE ---- pragma solidity ^0.8.0; contract NikNames is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; uint256 public cost = 0.05 ether; uint256 public maxSupply = 999; uint256 public maxMintAmount = 5; bool public paused = false; bool public whitelistOnly = false; uint256 public walletLimit = 5; mapping(address => bool) public whitelisted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); // To change the amount of Reserved Owner Tokens, // change the number in the mint(msg.sender, 100) method below // to any other number you want. The default is // 100 reserve tokens for the owner. mint(msg.sender, 3); maxMintAmount = 5; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); require((balanceOf(msg.sender) + _mintAmount) <= walletLimit, 'Wallet limit is reached.'); if (whitelistOnly == false) { if (msg.sender != owner()) { if(whitelisted[msg.sender] != true) { require(msg.value >= cost * _mintAmount); } } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } } else if (whitelistOnly == true) { require(whitelisted[msg.sender] == true, 'Address is not whitelisted.'); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, supply + i); } } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent CRYPKEYS" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } // // ONLY THE OWNER CAN CALL THE FUNCTIONS BELOW. // // This sets the minting price of each NFT. // Example: If you pass in 0.1, then you will need to pay 0.1 ETH + gas to mint 1 NFT. function setCost(uint256 _newCost) public onlyOwner() { cost = _newCost; } // This sets the amount users can mint at once. // Example: If you want your users to be able to mint 20 NFTs at once, // then you can set the setMaxMintAmount to 20. // // *THIS IS NOT A WALLET LIMIT. THERE IS ANOTHER FUNCTION FOR THAT BELOW* function setMaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } // This sets the wallet limit. // Example: If you set the setWalletLimit function to 5, then users can have AT MOST 5 NFTs in their wallet. // You can change this to adjust the pre-mint wallet limit vs. the main minting phase's wallet limit. function setWalletLimit(uint256 _newWalletLimit) public onlyOwner() { walletLimit = _newWalletLimit; } // If you want to save gas by setting the maxMintAmount and walletLimit // at the same time, you can use this function. // Simply pass in the new maxMintAmount first, and the newWalletLimit second. // Example: // If you want to set a pre-mint phase where users can only mint 3 NFTs at a time, // and have a wallet limit of 9 NFTs, you can pass in the arguments // 3 and 9 respectively. // Then, to activate full minting for your official launch phase, // simply pass in new arguments to change the maxMintAmount and walletLimit. // Example: // Now that you're fully launching, you can pass in 10 to the newMaxMintAmount argument // which would allow users to mint up to 10 at a time, and pass in 20 to the // newWalletLimit argument which would create a wallet limit of 20 NFTs. function setMaxMintAmountAndWalletLimit(uint256 _newmaxMintAmount, uint256 _newWalletLimit) public onlyOwner() { maxMintAmount = _newmaxMintAmount; walletLimit = _newWalletLimit; } // This sets the max supply. This will be set to 10,000 by default, although it is changable. function setMaxSupply(uint256 _newSupply) public onlyOwner() { maxSupply = _newSupply; } // This changes the baseURI. // Example: If you pass in "https://google.com/", then every new NFT that is minted // will have a URI corresponding to the baseURI you passed in. // The first NFT you mint would have a URI of "https://google.com/1", // The second NFT you mint would have a URI of "https://google.com/2", etc. function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // This sets the baseURI extension. // Example: If your database requires that the URI of each NFT // must have a .json at the end of the URI // (like https://google.com/1.json instead of just https://google.com/1) // then you can use this function to set the base extension. // For the above example, you would pass in ".json" to add the .json extension. function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } // This pauses or unpauses sales. // If paused, no NFTs can be minted, including by whitelisted users. // Must be set to false for NFTs to be minted. function pause(bool _state) public onlyOwner { paused = _state; } // This activates or deactivates the whitelist. // set to false = anyone can mint // set to true = only whitelisted users can mint function activateWhitelist(bool _state) public onlyOwner { whitelistOnly = _state; } // This whitelists users. // You MUST use an array for this function, and put quotes around the addresses you would like to whitelist. // Example: // If you want to whitelist 0x000000000000000000000000000000000000, // then pass in the argument: // ["0x000000000000000000000000000000000000"] // // If you want to whitelist multiple users, then pass in the argument with commas // seperating the user's addresses. // Example: // ["0x000000000000000000000000000000000000","0x111111111111111111111111111111111", "0x222222222222222222222222222222222"] function whitelistUser(address[] memory _user) public onlyOwner { uint256 x = 0; for (x = 0; x < _user.length; x++) { whitelisted[_user[x]] = true; } } // This removes whitelisted users. // It's arguments are the same as for whitelisting users. // You MUST use an array, and put quotes around the addresses you would like to remove from the whitelist. function removeWhitelistUser(address[] memory _user) public onlyOwner { uint256 x = 0; for (x = 0; x < _user.length; x++) { whitelisted[_user[x]] = false; } } // This withdraws the contract's balance of ETH to the Owner's (whoever launched the contract) address. function withdraw() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
This sets the max supply. This will be set to 10,000 by default, although it is changable.
function setMaxSupply(uint256 _newSupply) public onlyOwner() { maxSupply = _newSupply; }
50,501
pragma solidity ^0.4.21; /* ************************************************ */ /* ********** Zeppelin Solidity - v1.5.0 ********** */ /* ************************************************ */ /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /* *********************************** */ /* ********** Xmoneta Token ********** */ /* *********************************** */ /** * @title XmonetaToken * @author Xmoneta.com * * ERC20 Compatible token * Zeppelin Solidity - v1.5.0 */ contract XmonetaToken is StandardToken, Claimable { /* ********** Token Predefined Information ********** */ string public constant name = "Xmoneta Token"; string public constant symbol = "XMN"; uint256 public constant decimals = 18; /* ********** Defined Variables ********** */ // Total tokens supply 1 000 000 000 // For ethereum wallets we added decimals constant uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** decimals); // Vault where tokens are stored address public vault = msg.sender; // Sales agent who has permissions to manipulate with tokens address public salesAgent; /* ********** Events ********** */ event SalesAgentAppointed(address indexed previousSalesAgent, address indexed newSalesAgent); event SalesAgentRemoved(address indexed currentSalesAgent); event Burn(uint256 valueToBurn); /* ********** Functions ********** */ // Contract constructor function XmonetaToken() public { owner = msg.sender; totalSupply = INITIAL_SUPPLY; balances[vault] = totalSupply; } // Appoint sales agent of token function setSalesAgent(address newSalesAgent) onlyOwner public { SalesAgentAppointed(salesAgent, newSalesAgent); salesAgent = newSalesAgent; } // Remove sales agent from token function removeSalesAgent() onlyOwner public { SalesAgentRemoved(salesAgent); salesAgent = address(0); } // Transfer tokens from vault to account if sales agent is correct function transferTokensFromVault(address fromAddress, address toAddress, uint256 tokensAmount) public { require(salesAgent == msg.sender); balances[vault] = balances[vault].sub(tokensAmount); balances[toAddress] = balances[toAddress].add(tokensAmount); Transfer(fromAddress, toAddress, tokensAmount); } // Allow the owner to burn a specific amount of tokens from the vault function burn(uint256 valueToBurn) onlyOwner public { require(valueToBurn > 0); balances[vault] = balances[vault].sub(valueToBurn); totalSupply = totalSupply.sub(valueToBurn); Burn(valueToBurn); } } /* ************************************** */ /* ************ Xmoneta Sale ************ */ /* ************************************** */ /** * @title XmonetaSale * @author Xmoneta.com * * Zeppelin Solidity - v1.5.0 */ contract XmonetaSale { using SafeMath for uint256; /* ********** Defined Variables ********** */ // The token being sold XmonetaToken public token; // Crowdsale start timestamp - 03/13/2018 at 12:00pm (UTC) uint256 public startTime = 1520942400; // Crowdsale end timestamp - 05/31/2018 at 12:00pm (UTC) uint256 public endTime = 1527768000; // Addresses where ETH are collected address public wallet1 = 0x36A3c000f8a3dC37FCD261D1844efAF851F81556; address public wallet2 = 0x8beDBE45Aa345938d70388E381E2B6199A15B3C3; // How many token per wei uint256 public rate = 20000; // Cap in ethers uint256 public cap = 8000 * 1 ether; // Amount of raised wei uint256 public weiRaised; // Round B start timestamp - 05/04/2018 at 12:00pm (UTC) uint256 public round_b_begin_date = 1522929600; // Round B start timestamp - 30/04/2018 at 12:00pm (UTC) uint256 public round_c_begin_date = 1525089600; /* ********** Events ********** */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 weiAmount, uint256 tokens); /* ********** Functions ********** */ // Contract constructor function XmonetaSale() public { token = XmonetaToken(0x99705A8B60d0fE21A4B8ee54DB361B3C573D18bb); } // Fallback function to buy tokens function () public payable { buyTokens(msg.sender); } // Bonus calculation for transaction function bonus_calculation() internal returns (uint256, uint256) { // Round A Standard bonus & Extra bonus uint256 bonusPercent = 30; uint256 extraBonusPercent = 50; if (now >= round_c_begin_date) { // Round C Standard bonus & Extra bonus bonusPercent = 10; extraBonusPercent = 30; } else if (now >= round_b_begin_date) { // Round B Standard bonus & Extra bonus bonusPercent = 20; extraBonusPercent = 40; } return (bonusPercent, extraBonusPercent); } // Token purchase function function buyTokens(address beneficiary) public payable { require(validPurchase()); uint256 weiAmount = msg.value; // Send spare wei back if investor sent more that cap uint256 tempWeiRaised = weiRaised.add(weiAmount); if (tempWeiRaised > cap) { uint256 spareWeis = tempWeiRaised.sub(cap); weiAmount = weiAmount.sub(spareWeis); beneficiary.transfer(spareWeis); } // Define standard and extra bonus variables uint256 bonusPercent; uint256 extraBonusPercent; // Execute calculation (bonusPercent, extraBonusPercent) = bonus_calculation(); // Accept extra bonus if beneficiary send more that 1 ETH if (weiAmount >= 1 ether) { bonusPercent = extraBonusPercent; } // Token calculations with bonus uint256 additionalPercentInWei = rate.div(100).mul(bonusPercent); uint256 rateWithPercents = rate.add(additionalPercentInWei); // Calculate token amount to be sold uint256 tokens = weiAmount.mul(rateWithPercents); // Update state weiRaised = weiRaised.add(weiAmount); // Tranfer tokens from vault token.transferTokensFromVault(msg.sender, beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(weiAmount); } // Send wei to the fund collection wallets function forwardFunds(uint256 weiAmount) internal { uint256 value = weiAmount.div(2); // If buyer send amount of wei that can not be divided to 2 without float point, send all weis to first wallet if (value.mul(2) != weiAmount) { wallet1.transfer(weiAmount); } else { wallet1.transfer(value); wallet2.transfer(value); } } // Validate if the transaction can be success function validPurchase() internal constant returns (bool) { bool withinCap = weiRaised < cap; bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase && withinCap; } // Show if crowdsale has ended or no function hasEnded() public constant returns (bool) { return now > endTime || weiRaised >= cap; } }
Appoint sales agent of token
function setSalesAgent(address newSalesAgent) onlyOwner public { SalesAgentAppointed(salesAgent, newSalesAgent); salesAgent = newSalesAgent; }
10,655,887
./full_match/1/0x2846b7C57C0666203D694f464Fd876d9026ba9d2/sources/contracts/xSGT.sol
burn a token id Requirements: - caller must have burner role/ burn
function burn(uint256 tokenId) external { require(hasRole(BURNER_ROLE, msg.sender), "Caller is not a burner"); _burn(tokenId); }
8,309,716
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../abstract/MasterAware.sol"; import "../../interfaces/IClaims.sol"; import "../../interfaces/IClaimsData.sol"; import "../../interfaces/IClaimsReward.sol"; import "../../interfaces/IMemberRoles.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/IQuotation.sol"; import "../../interfaces/IQuotationData.sol"; import "../../interfaces/ITokenController.sol"; import "../../interfaces/ITokenData.sol"; import "./external/Governed.sol"; import "./external/OwnedUpgradeabilityProxy.sol"; contract NXMaster is INXMMaster, Governed { using SafeMath for uint; uint public _unused0; bytes2[] public contractCodes; mapping(address => bool) public contractsActive; mapping(bytes2 => address payable) public contractAddresses; mapping(bytes2 => bool) public isProxy; mapping(bytes2 => bool) public isReplaceable; address public tokenAddress; bool internal reentrancyLock; bool public masterInitialized; address public owner; uint public _unused1; address public emergencyAdmin; bool public paused; enum ContractType { Undefined, Replaceable, Proxy } event InternalContractAdded(bytes2 indexed code, address contractAddress, ContractType indexed contractType); event ContractUpgraded(bytes2 indexed code, address newAddress, address previousAddress, ContractType indexed contractType); event ContractRemoved(bytes2 indexed code, address contractAddress); event PauseConfigured(bool paused); function initializeEmergencyAdmin() external { if (emergencyAdmin == address(0)) { emergencyAdmin = 0x422D71fb8040aBEF53f3a05d21A9B85eebB2995D; } } modifier noReentrancy() { require(!reentrancyLock, "Reentrant call."); reentrancyLock = true; _; reentrancyLock = false; } modifier onlyEmergencyAdmin() { require(msg.sender == emergencyAdmin, "NXMaster: Not emergencyAdmin"); _; } function addNewInternalContracts( bytes2[] calldata newContractCodes, address payable[] calldata newAddresses, uint[] calldata _types ) external onlyAuthorizedToGovern { require(newContractCodes.length == newAddresses.length, "NXMaster: newContractCodes.length != newAddresses.length."); require(newContractCodes.length == _types.length, "NXMaster: newContractCodes.length != _types.length"); for (uint i = 0; i < newContractCodes.length; i++) { addNewInternalContract(newContractCodes[i], newAddresses[i], _types[i]); } } /// @dev Adds new internal contract /// @param contractCode contract code for new contract /// @param contractAddress contract address for new contract /// @param _type pass 1 if contract is replaceable, 2 if contract is proxy function addNewInternalContract( bytes2 contractCode, address payable contractAddress, uint _type ) internal { require(contractAddresses[contractCode] == address(0), "NXMaster: Code already in use"); require(contractAddress != address(0), "NXMaster: Contract address is 0"); contractCodes.push(contractCode); address newInternalContract; if (_type == uint(ContractType.Replaceable)) { newInternalContract = contractAddress; isReplaceable[contractCode] = true; } else if (_type == uint(ContractType.Proxy)) { newInternalContract = address(new OwnedUpgradeabilityProxy(contractAddress)); isProxy[contractCode] = true; } else { revert("NXMaster: Unsupported contract type"); } contractAddresses[contractCode] = address(uint160(newInternalContract)); contractsActive[newInternalContract] = true; MasterAware up = MasterAware(newInternalContract); up.changeMasterAddress(address(this)); up.changeDependentContractAddress(); emit InternalContractAdded(contractCode, contractAddress, ContractType(_type)); } /// @dev upgrades multiple contracts at a time function upgradeMultipleContracts( bytes2[] calldata _contractCodes, address payable[] calldata newAddresses ) external onlyAuthorizedToGovern { require(_contractCodes.length == newAddresses.length, "NXMaster: _contractCodes.length != newAddresses.length"); for (uint i = 0; i < _contractCodes.length; i++) { address payable newAddress = newAddresses[i]; bytes2 code = _contractCodes[i]; require(newAddress != address(0), "NXMaster: Contract address is 0"); if (isProxy[code]) { OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(contractAddresses[code]); address previousAddress = proxy.implementation(); proxy.upgradeTo(newAddress); emit ContractUpgraded(code, newAddress, previousAddress, ContractType.Proxy); continue; } if (isReplaceable[code]) { address previousAddress = getLatestAddress(code); replaceContract(code, newAddress); emit ContractUpgraded(code, newAddress, previousAddress, ContractType.Replaceable); continue; } revert("NXMaster: Non-existant or non-upgradeable contract code"); } updateAllDependencies(); } function replaceContract(bytes2 code, address payable newAddress) internal { if (code == "CR") { ITokenController tc = ITokenController(getLatestAddress("TC")); tc.addToWhitelist(newAddress); tc.removeFromWhitelist(contractAddresses["CR"]); IClaimsReward cr = IClaimsReward(contractAddresses["CR"]); cr.upgrade(newAddress); } else if (code == "P1") { IPool p1 = IPool(contractAddresses["P1"]); p1.upgradeCapitalPool(newAddress); } address payable oldAddress = contractAddresses[code]; contractsActive[oldAddress] = false; contractAddresses[code] = newAddress; contractsActive[newAddress] = true; MasterAware up = MasterAware(contractAddresses[code]); up.changeMasterAddress(address(this)); } function removeContracts(bytes2[] calldata contractCodesToRemove) external onlyAuthorizedToGovern { for (uint i = 0; i < contractCodesToRemove.length; i++) { bytes2 code = contractCodesToRemove[i]; address contractAddress = contractAddresses[code]; require(contractAddress != address(0), "NXMaster: Address is 0"); require(isInternal(contractAddress), "NXMaster: Contract not internal"); contractsActive[contractAddress] = false; contractAddresses[code] = address(0); if (isProxy[code]) { isProxy[code] = false; } if (isReplaceable[code]) { isReplaceable[code] = false; } emit ContractRemoved(code, contractAddress); } // delete elements from contractCodes for (uint i = 0; i < contractCodes.length; i++) { for (uint j = 0; j < contractCodesToRemove.length; j++) { if (contractCodes[i] == contractCodesToRemove[j]) { contractCodes[i] = contractCodes[contractCodes.length - 1]; contractCodes.pop(); i = i == 0 ? 0 : i - 1; } } } updateAllDependencies(); } function updateAllDependencies() internal { for (uint i = 0; i < contractCodes.length; i++) { MasterAware up = MasterAware(contractAddresses[contractCodes[i]]); up.changeDependentContractAddress(); } } /** * @dev set Emergency pause * @param _paused to toggle emergency pause ON/OFF */ function setEmergencyPause(bool _paused) public onlyEmergencyAdmin { paused = _paused; emit PauseConfigured(_paused); } /// @dev checks whether the address is an internal contract address. function isInternal(address _contractAddress) public view returns (bool) { return contractsActive[_contractAddress]; } /// @dev checks whether the address is the Owner or not. function isOwner(address _address) public view returns (bool) { return owner == _address; } /// @dev Checks whether emergency pause is on/not. function isPause() public view returns (bool) { return paused; } /// @dev checks whether the address is a member of the mutual or not. function isMember(address _add) public view returns (bool) { IMemberRoles mr = IMemberRoles(getLatestAddress("MR")); return mr.checkRole(_add, uint(IMemberRoles.Role.Member)); } /// @dev Gets current contract codes and their addresses /// @return contractCodes /// @return contractAddresses function getInternalContracts() public view returns ( bytes2[] memory _contractCodes, address[] memory _contractAddresses ) { _contractCodes = contractCodes; _contractAddresses = new address[](contractCodes.length); for (uint i = 0; i < _contractCodes.length; i++) { _contractAddresses[i] = contractAddresses[contractCodes[i]]; } } /** * @dev returns the address of token controller * @return address is returned */ function dAppLocker() public view returns (address) { return getLatestAddress("TC"); } /// @dev Gets latest contract address /// @param _contractName Contract name to fetch function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress) { contractAddress = contractAddresses[_contractName]; } /** * @dev to check if the address is authorized to govern or not * @param _add is the address in concern * @return the boolean status status for the check */ function checkIsAuthToGoverned(address _add) public view returns (bool) { return isAuthorizedToGovern(_add); } /** * @dev to update the owner parameters * @param code is the associated code * @param val is value to be set */ function updateOwnerParameters(bytes8 code, address payable val) public onlyAuthorizedToGovern { IQuotationData qd; if (code == "MSWALLET") { ITokenData td; td = ITokenData(getLatestAddress("TD")); td.changeWalletAddress(val); } else if (code == "OWNER") { IMemberRoles mr = IMemberRoles(getLatestAddress("MR")); mr.swapOwner(val); owner = val; } else if (code == "QUOAUTH") { qd = IQuotationData(getLatestAddress("QD")); qd.changeAuthQuoteEngine(val); } else if (code == "KYCAUTH") { qd = IQuotationData(getLatestAddress("QD")); qd.setKycAuthAddress(val); } else if (code == "EMADMIN") { emergencyAdmin = val; } else { revert("Invalid param code"); } } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.5.0; import "../interfaces/INXMMaster.sol"; contract MasterAware { INXMMaster public master; modifier onlyMember { require(master.isMember(msg.sender), "Caller is not a member"); _; } modifier onlyInternal { require(master.isInternal(msg.sender), "Caller is not an internal contract"); _; } modifier onlyMaster { if (address(master) != address(0)) { require(address(master) == msg.sender, "Not master"); } _; } modifier onlyGovernance { require( master.checkIsAuthToGoverned(msg.sender), "Caller is not authorized to govern" ); _; } modifier whenPaused { require(master.isPause(), "System is not paused"); _; } modifier whenNotPaused { require(!master.isPause(), "System is paused"); _; } function changeDependentContractAddress() external; function changeMasterAddress(address masterAddress) public onlyMaster { master = INXMMaster(masterAddress); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IClaims { function setClaimStatus(uint claimId, uint stat) external; function getCATokens(uint claimId, uint member) external view returns (uint tokens); function submitClaim(uint coverId) external; function submitClaimForMember(uint coverId, address member) external; function submitClaimAfterEPOff() external pure; function submitCAVote(uint claimId, int8 verdict) external; function submitMemberVote(uint claimId, int8 verdict) external; function pauseAllPendingClaimsVoting() external pure; function startAllPendingClaimsVoting() external pure; function checkVoteClosing(uint claimId) external view returns (int8 close); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IClaimsData { function pendingClaimStart() external view returns (uint); function claimDepositTime() external view returns (uint); function maxVotingTime() external view returns (uint); function minVotingTime() external view returns (uint); function payoutRetryTime() external view returns (uint); function claimRewardPerc() external view returns (uint); function minVoteThreshold() external view returns (uint); function maxVoteThreshold() external view returns (uint); function majorityConsensus() external view returns (uint); function pauseDaysCA() external view returns (uint); function userClaimVotePausedOn(address) external view returns (uint); function setpendingClaimStart(uint _start) external; function setRewardDistributedIndexCA(address _voter, uint caIndex) external; function setUserClaimVotePausedOn(address user) external; function setRewardDistributedIndexMV(address _voter, uint mvIndex) external; function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external; function setRewardClaimed(uint _voteid, bool claimed) external; function changeFinalVerdict(uint _claimId, int8 _verdict) external; function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external; function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external; function addClaimVoteCA(uint _claimId, uint _voteid) external; function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external; function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external; function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external; function addClaimVotemember(uint _claimId, uint _voteid) external; function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external; function updateState12Count(uint _claimId, uint _cnt) external; function setClaimStatus(uint _claimId, uint _stat) external; function setClaimdateUpd(uint _claimId, uint _dateUpd) external; function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external; function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external; function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external; function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external; function setPendingClaimVoteStatus(uint _claimId, bool _vote) external; function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external; function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external; function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external; function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val); function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns ( uint coverId, uint dateUpd, bool submit ); function getAllClaimsByIndex( uint _claimId ) external view returns ( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ); function getUserClaimVoteCA( address _add, uint _claimId ) external view returns (uint idVote); function getUserClaimVoteMember( address _add, uint _claimId ) external view returns (uint idVote); function getAllVoteLength() external view returns (uint voteCount); function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno); function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV); function getClaimState12Count(uint _claimId) external view returns (uint num); function getClaimDateUpd(uint _claimId) external view returns (uint dateupd); function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr); function getClaimsTokenCA( uint _claimId ) external view returns ( uint claimId, uint accept, uint deny ); function getClaimsTokenMV( uint _claimId ) external view returns ( uint claimId, uint accept, uint deny ); function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt); function getMemberClaimVotesToken( uint _claimId ) external view returns (uint claimId, uint cnt); function getVoteDetails(uint _voteid) external view returns ( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ); function getVoterVote(uint _voteid) external view returns (address voter); function getClaim( uint _claimId ) external view returns ( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ); function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns (uint claimId, uint len); function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns (int8 ver); function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns (uint tok); function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns (address voter); function getUserClaimCount(address _add) external view returns (uint len); function getClaimLength() external view returns (uint len); function actualClaimLength() external view returns (uint len); function getClaimFromNewStart( uint _index, address _add ) external view returns ( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ); function getUserClaimByIndex( uint _index, address _add ) external view returns ( uint status, uint coverid, uint claimId ); function getAllVotesForClaim( uint _claimId ) external view returns ( uint claimId, uint[] memory ca, uint[] memory mv ); function getTokensClaim( address _of, uint _claimId ) external view returns ( uint claimId, uint tokens ); function getRewardDistributedIndex( address _voter ) external view returns ( uint lastCAvoteIndex, uint lastMVvoteIndex ); function getClaimRewardDetail( uint claimid ) external view returns ( uint percCA, uint percMV, uint tokens ); function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid); function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token); function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token); function getVoteAddressCA(address _voter, uint index) external view returns (uint); function getVoteAddressMember(address _voter, uint index) external view returns (uint); function getVoteAddressCALength(address _voter) external view returns (uint); function getVoteAddressMemberLength(address _voter) external view returns (uint); function getFinalVerdict(uint _claimId) external view returns (int8 verdict); function getLengthOfClaimSubmittedAtEP() external view returns (uint len); function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit); function getLengthOfClaimVotingPause() external view returns (uint len); function getPendingClaimDetailsByIndex( uint _index ) external view returns ( uint claimId, uint pendingTime, bool voting ); function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IClaimsReward { /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) external; function getCurrencyAssetAddress(bytes4 currency) external view returns (address); function getRewardToBeGiven( uint check, uint voteid, uint flag ) external view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ); function upgrade(address _newAdd) external; function getRewardToBeDistributedByUser(address _add) external view returns (uint total); function getRewardAndClaimedStatus(uint check, uint claimId) external view returns (uint reward, bool claimed); function claimAllPendingReward(uint records) external; function getAllPendingRewardOfUser(address _add) external view returns (uint); function unlockCoverNote(uint coverId) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IMemberRoles { enum Role {UnAssigned, AdvisoryBoard, Member, Owner} function payJoiningFee(address _userAddress) external payable; function switchMembership(address _newAddress) external; function switchMembershipOf(address member, address _newAddress) external; function swapOwner(address _newOwnerAddress) external; function kycVerdict(address payable _userAddress, bool verdict) external; function getClaimPayoutAddress(address payable _member) external view returns (address payable); function setClaimPayoutAddress(address payable _address) external; function totalRoles() external view returns (uint256); function changeAuthorized(uint _roleId, address _newAuthorized) external; function members(uint _memberRoleId) external view returns (uint, address[] memory memberArray); function numberOfMembers(uint _memberRoleId) external view returns (uint); function authorized(uint _memberRoleId) external view returns (address); function roles(address _memberAddress) external view returns (uint[] memory); function checkRole(address _memberAddress, uint _roleId) external view returns (bool); function getMemberLengthForAllRoles() external view returns (uint[] memory totalMembers); function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool); function membersLength(uint _memberRoleId) external view returns (uint); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; import "./IPriceFeedOracle.sol"; interface IPool { function sellNXM(uint tokenAmount, uint minEthOut) external; function sellNXMTokens(uint tokenAmount) external returns (bool); function minPoolEth() external returns (uint); function transferAssetToSwapOperator(address asset, uint amount) external; function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external; function getAssetDetails(address _asset) external view returns ( uint112 min, uint112 max, uint32 lastAssetSwapTime, uint maxSlippageRatio ); function sendClaimPayout ( address asset, address payable payoutAddress, uint amount ) external returns (bool success); function transferAsset( address asset, address payable destination, uint amount ) external; function upgradeCapitalPool(address payable newPoolAddress) external; function priceFeedOracle() external view returns (IPriceFeedOracle); function getPoolValueInEth() external view returns (uint); function transferAssetFrom(address asset, address from, uint amount) external; function getEthForNXM(uint nxmAmount) external view returns (uint ethAmount); function calculateEthForNXM( uint nxmAmount, uint currentTotalAssetValue, uint mcrEth ) external pure returns (uint); function calculateMCRRatio(uint totalAssetValue, uint mcrEth) external pure returns (uint); function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) external pure returns (uint tokenPrice); function getTokenPrice(address asset) external view returns (uint tokenPrice); function getMCRRatio() external view returns (uint); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IQuotation { function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) external; function createCover( address payable from, address scAddress, bytes4 currency, uint[] calldata coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IQuotationData { function authQuoteEngine() external view returns (address); function stlp() external view returns (uint); function stl() external view returns (uint); function pm() external view returns (uint); function minDays() external view returns (uint); function tokensRetained() external view returns (uint); function kycAuthAddress() external view returns (address); function refundEligible(address) external view returns (bool); function holdedCoverIDStatus(uint) external view returns (uint); function timestampRepeated(uint) external view returns (bool); enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover} enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested} function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external; function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external; function subFromTotalSumAssured(bytes4 _curr, uint _amount) external; function addInTotalSumAssured(bytes4 _curr, uint _amount) external; function setTimestampRepeated(uint _timestamp) external; /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external; function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external; function setRefundEligible(address _add, bool status) external; function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external; function setKycAuthAddress(address _add) external; function changeAuthQuoteEngine(address _add) external; function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val); function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ); function getCoverLength() external view returns (uint len); function getAuthQuoteEngine() external view returns (address _add); function getTotalSumAssured(bytes4 _curr) external view returns (uint amount); function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover); function getUserCoverLength(address _add) external view returns (uint len); function getCoverStatusNo(uint _cid) external view returns (uint8); function getCoverPeriod(uint _cid) external view returns (uint32 cp); function getCoverSumAssured(uint _cid) external view returns (uint sa); function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr); function getValidityOfCover(uint _cid) external view returns (uint date); function getscAddressOfCover(uint _cid) external view returns (uint, address); function getCoverMemberAddress(uint _cid) external view returns (address payable _add); function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM); function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ); function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ); function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ); function getUserHoldedCoverLength(address _add) external view returns (uint); function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint); function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ); function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount); function changeCoverStatusNo(uint _cid, uint8 _stat) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface ITokenController { function coverInfo(uint id) external view returns (uint16 claimCount, bool hasOpenClaim, bool hasAcceptedClaim); function claimSubmissionGracePeriod() external view returns (uint); function withdrawCoverNote( address _of, uint[] calldata _coverIds, uint[] calldata _indexes ) external; function markCoverClaimOpen(uint coverId) external; function markCoverClaimClosed(uint coverId, bool isAccepted) external; function changeOperator(address _newOperator) external; function operatorTransfer(address _from, address _to, uint _value) external returns (bool); function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external; function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) external returns (bool); function mintCoverNote( address _of, bytes32 _reason, uint256 _amount, uint256 _time ) external; function extendClaimAssessmentLock(uint256 _time) external; function extendLockOf(address _of, bytes32 _reason, uint256 _time) external returns (bool); function increaseClaimAssessmentLock(uint256 _amount) external; function burnFrom(address _of, uint amount) external returns (bool); function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) external; function reduceLock(address _of, bytes32 _reason, uint256 _time) external; function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) external; function addToWhitelist(address _member) external; function removeFromWhitelist(address _member) external; function mint(address _member, uint _amount) external; function lockForMemberVote(address _of, uint _days) external; function withdrawClaimAssessmentTokens(address _of) external; function getLockReasons(address _of) external view returns (bytes32[] memory reasons); function getLockedTokensValidity(address _of, bytes32 reason) external view returns (uint256 validity); function getUnlockableTokens(address _of) external view returns (uint256 unlockableTokens); function tokensLocked(address _of, bytes32 _reason) external view returns (uint256 amount); function tokensLockedWithValidity(address _of, bytes32 _reason) external view returns (uint256 amount, uint256 validity); function tokensUnlockable(address _of, bytes32 _reason) external view returns (uint256 amount); function totalSupply() external view returns (uint256); function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) external view returns (uint256 amount); function totalBalanceOf(address _of) external view returns (uint256 amount); function totalLockedBalance(address _of) external view returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface ITokenData { function walletAddress() external view returns (address payable); function lockTokenTimeAfterCoverExp() external view returns (uint); function bookTime() external view returns (uint); function lockCADays() external view returns (uint); function lockMVDays() external view returns (uint); function scValidDays() external view returns (uint); function joiningFee() external view returns (uint); function stakerCommissionPer() external view returns (uint); function stakerMaxCommissionPer() external view returns (uint); function tokenExponent() external view returns (uint); function priceStep() external view returns (uint); function depositedCN(uint) external view returns (uint amount, bool isDeposited); function lastCompletedStakeCommission(address) external view returns (uint); function changeWalletAddress(address payable _address) external; function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) external view returns (address stakedContractAddress); function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) external view returns (uint burnedAmount); function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) external view returns (uint unlockable); function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) external view returns (uint scIndex); function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) external view returns (uint sIndex); function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) external view returns (uint amount); function getStakerStakedContractLength( address _stakerAddress ) external view returns (uint length); function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) external view returns (uint amount); function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) external; function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) external; function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) external; function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) external; function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) external; function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) external; function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) external view returns (uint); function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) external view returns (uint); function getStakerTotalEarnedStakeCommission( address _stakerAddress ) external view returns (uint totalCommissionEarned); function getStakerTotalReedmedStakeCommission( address _stakerAddress ) external view returns (uint totalCommissionRedeemed); function setDepositCN(uint coverId, bool flag) external; function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) external view returns (address stakerAddress); function getStakedContractStakersLength( address _stakedContractAddress ) external view returns (uint length); function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) external returns (uint scIndex); function bookCATokens(address _of) external; function isCATokensBooked(address _of) external view returns (bool res); function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) external; function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) external; function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) external; function setDepositCNAmount(uint coverId, uint amount) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.5.0; interface IMaster { function getLatestAddress(bytes2 _module) external view returns (address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns (bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.5.0; import "./UpgradeabilityProxy.sol"; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant PROXY_OWNER_POSITION = keccak256("org.govblocks.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; // solhint-disable-next-line no-inline-assembly assembly { owner := sload(position) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param _implementation representing the address of the new implementation to be set. */ function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } /** * @dev Sets the address of the owner */ function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; // solhint-disable-next-line no-inline-assembly assembly { sstore(position, _newProxyOwner) } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface INXMMaster { function tokenAddress() external view returns (address); function owner() external view returns (address); function masterInitialized() external view returns (bool); function isInternal(address _add) external view returns (bool); function isPause() external view returns (bool check); function isOwner(address _add) external view returns (bool); function isMember(address _add) external view returns (bool); function checkIsAuthToGoverned(address _add) external view returns (bool); function dAppLocker() external view returns (address _add); function getLatestAddress(bytes2 _contractName) external view returns (address payable contractAddress); function upgradeMultipleContracts( bytes2[] calldata _contractCodes, address payable[] calldata newAddresses ) external; function removeContracts(bytes2[] calldata contractCodesToRemove) external; function addNewInternalContracts( bytes2[] calldata _contractCodes, address payable[] calldata newAddresses, uint[] calldata _types ) external; function updateOwnerParameters(bytes8 code, address payable val) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IPriceFeedOracle { function daiAddress() external view returns (address); function stETH() external view returns (address); function ETH() external view returns (address); function getAssetToEthRate(address asset) external view returns (uint); function getAssetForEth(address asset, uint ethIn) external view returns (uint); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.5.0; import "./Proxy.sol"; /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant IMPLEMENTATION_POSITION = keccak256("org.govblocks.proxy.implementation"); /** * @dev Constructor function */ // solhint-disable-next-line no-empty-blocks constructor() public {} /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address impl) { bytes32 position = IMPLEMENTATION_POSITION; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param _newImplementation address representing the new implementation to be set */ function _setImplementation(address _newImplementation) internal { bytes32 position = IMPLEMENTATION_POSITION; // solhint-disable-next-line no-inline-assembly assembly { sstore(position, _newImplementation) } } /** * @dev Upgrades the implementation address * @param _newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address _newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != _newImplementation); _setImplementation(_newImplementation); emit Upgraded(_newImplementation); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.5.0; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ // solhint-disable-next-line no-complex-fallback function() external payable { address _impl = implementation(); require(_impl != address(0)); // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); }
to check if the address is authorized to govern or not _add is the address in concern return the boolean status status for the check/
function checkIsAuthToGoverned(address _add) public view returns (bool) { return isAuthorizedToGovern(_add); }
1,749,084
pragma solidity ^0.4.24; // File: contracts/libs/PointsCalculator.sol library PointsCalculator { uint8 constant MATCHES_NUMBER = 20; uint8 constant BONUS_MATCHES = 5; uint16 constant EXTRA_STATS_MASK = 65535; uint8 constant MATCH_UNDEROVER_MASK = 1; uint8 constant MATCH_RESULT_MASK = 3; uint8 constant MATCH_TOUCHDOWNS_MASK = 31; uint8 constant BONUS_STAT_MASK = 63; struct MatchResult{ uint8 result; /* 0-> draw, 1-> won 1, 2-> won 2 */ uint8 under49; uint8 touchdowns; } struct Extras { uint16 interceptions; uint16 missedFieldGoals; uint16 overtimes; uint16 sacks; uint16 fieldGoals; uint16 fumbles; } struct BonusMatch { uint16 bonus; } /** * @notice get points from a single match * @param matchIndex index of the match * @param matches token predictions * @return */ function getMatchPoints (uint256 matchIndex, uint160 matches, MatchResult[] matchResults, bool[] starMatches) private pure returns(uint16 matchPoints) { uint8 tResult = uint8(matches & MATCH_RESULT_MASK); uint8 tUnder49 = uint8((matches >> 2) & MATCH_UNDEROVER_MASK); uint8 tTouchdowns = uint8((matches >> 3) & MATCH_TOUCHDOWNS_MASK); uint8 rResult = matchResults[matchIndex].result; uint8 rUnder49 = matchResults[matchIndex].under49; uint8 rTouchdowns = matchResults[matchIndex].touchdowns; if (rResult == tResult) { matchPoints += 5; if(rResult == 0) { matchPoints += 5; } if(starMatches[matchIndex]) { matchPoints += 2; } } if(tUnder49 == rUnder49) { matchPoints += 1; } if(tTouchdowns == rTouchdowns) { matchPoints += 4; } } /** * @notice calculates points won by yellow and red cards predictions * @param extras token predictions * @return amount of points */ function getExtraPoints(uint96 extras, Extras extraStats) private pure returns(uint16 extraPoints){ uint16 interceptions = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 missedFieldGoals = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 overtimes = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 sacks = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 fieldGoals = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 fumbles = uint16(extras & EXTRA_STATS_MASK); if (interceptions == extraStats.interceptions){ extraPoints += 6; } if (missedFieldGoals == extraStats.missedFieldGoals){ extraPoints += 6; } if (overtimes == extraStats.overtimes){ extraPoints += 6; } if (sacks == extraStats.sacks){ extraPoints += 6; } if (fieldGoals == extraStats.fieldGoals){ extraPoints += 6; } if (fumbles == extraStats.fumbles){ extraPoints += 6; } } /** * * * */ function getBonusPoints (uint256 bonusId, uint32 bonuses, BonusMatch[] bonusMatches) private pure returns(uint16 bonusPoints) { uint8 bonus = uint8(bonuses & BONUS_STAT_MASK); if(bonusMatches[bonusId].bonus == bonus) { bonusPoints += 2; } } function calculateTokenPoints (uint160 tMatchResults, uint32 tBonusMatches, uint96 tExtraStats, MatchResult[] storage matchResults, Extras storage extraStats, BonusMatch[] storage bonusMatches, bool[] starMatches) external pure returns(uint16 points){ //Matches uint160 m = tMatchResults; for (uint256 i = 0; i < MATCHES_NUMBER; i++){ points += getMatchPoints(MATCHES_NUMBER - i - 1, m, matchResults, starMatches); m = m >> 8; } //BonusMatches uint32 b = tBonusMatches; for(uint256 j = 0; j < BONUS_MATCHES; j++) { points += getBonusPoints(BONUS_MATCHES - j - 1, b, bonusMatches); b = b >> 6; } //Extras points += getExtraPoints(tExtraStats, extraStats); } } // File: contracts/dataSource/DataSourceInterface.sol contract DataSourceInterface { function isDataSource() public pure returns (bool); function getMatchResults() external; function getExtraStats() external; function getBonusResults() external; } // File: contracts/game/GameStorage.sol // Matches // 0 Baltimore,Cleveland Bonus // 1 Denver,New York Bonus // 2 Atlanta,Pittsburgh // 3 New York,Carolina // 4 Minnesota,Philadelphia Bonus // 5 Arizona,San Francisco // 6 Los Angeles,Seattle // 7 Dallas,Houston Star contract GameStorage{ event LogTokenBuilt(address creatorAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b); event LogTokenGift(address creatorAddress, address giftedAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b); event LogPrepaidTokenBuilt(address creatorAddress, bytes32 secret); event LogPrepaidRedeemed(address redeemer, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b); uint256 constant STARTING_PRICE = 50 finney; uint256 constant FIRST_PHASE = 1540393200; uint256 constant EVENT_START = 1541084400; uint8 constant MATCHES_NUMBER = 20; uint8 constant BONUS_MATCHES = 5; //6, 12, 18 bool[] internal starMatches = [false, false, false, false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, true, false]; uint16 constant EXTRA_STATS_MASK = 65535; uint8 constant MATCH_UNDEROVER_MASK = 1; uint8 constant MATCH_RESULT_MASK = 3; uint8 constant MATCH_TOUCHDOWNS_MASK = 31; uint8 constant BONUS_STAT_MASK = 63; uint256 public prizePool = 0; uint256 public adminPool = 0; mapping (uint256 => uint16) public tokenToPointsMap; mapping (uint256 => uint256) public tokenToPayoutMap; mapping (bytes32 => uint8) public secretsMap; address public dataSourceAddress; DataSourceInterface internal dataSource; enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished } pointsValidationState public pValidationState = pointsValidationState.Unstarted; uint256 internal pointsLimit = 0; uint32 internal lastCalculatedToken = 0; uint32 internal lastCheckedToken = 0; uint32 internal winnerCounter = 0; uint32 internal lastAssigned = 0; uint32 internal payoutRange = 0; uint32 internal lastPrizeGiven = 0; uint16 internal superiorQuota; uint16[] internal payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500]; uint24[21] internal payoutDistribution; uint256[] internal sortedWinners; PointsCalculator.MatchResult[] public matchResults; PointsCalculator.BonusMatch[] public bonusMatches; PointsCalculator.Extras public extraStats; } // File: contracts/CryptocupStorage.sol contract CryptocupStorage is GameStorage { } // File: contracts/ticket/TicketInterface.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ interface TicketInterface { 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 getOwnedTokens(address _from) public view returns(uint256[]); 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 data) public; } // File: contracts/ticket/TicketStorage.sol contract TicketStorage is TicketInterface{ // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; struct Token { uint160 matches; uint32 bonusMatches; uint96 extraStats; uint64 timeStamp; string message; } // List of all tokens Token[] tokens; mapping (uint256 => address) public tokenOwner; mapping (uint256 => address) public tokenApprovals; mapping (address => uint256[]) internal ownedTokens; mapping (address => mapping (address => bool)) public operatorApprovals; } // File: contracts/libs/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/helpers/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * 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 _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/access/AccessStorage.sol contract AccessStorage{ bool public paused = false; bool public finalized = false; address public adminAddress; address public dataSourceAddress; address public marketplaceAddress; uint256 internal deploymentTime = 0; uint256 public gameFinishedTime = 0; uint256 public finalizedTime = 0; } // File: contracts/access/AccessRegistry.sol /** * @title AccessControlLayer * @author CryptoCup Team (https://cryptocup.io/about) * @dev Containes basic admin modifiers to restrict access to some functions. Allows * for pauseing, and setting emergency stops. */ contract AccessRegistry is AccessStorage { /** * @dev Main modifier to limit access to delicate functions. */ modifier onlyAdmin() { require(msg.sender == adminAddress, "Only admin."); _; } /** * @dev Main modifier to limit access to delicate functions. */ modifier onlyDataSource() { require(msg.sender == dataSourceAddress, "Only dataSource."); _; } /** * @dev Main modifier to limit access to delicate functions. */ modifier onlyMarketPlace() { require(msg.sender == marketplaceAddress, "Only marketplace."); _; } /** * @dev Modifier that checks that the contract is not paused */ modifier isNotPaused() { require(!paused, "Only if not paused."); _; } /** * @dev Modifier that checks that the contract is paused */ modifier isPaused() { require(paused, "Only if paused."); _; } /** * @dev Modifier that checks that the contract has finished successfully */ modifier hasFinished() { require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days)), "Only if game has finished."); _; } /** * @dev Modifier that checks that the contract has finalized */ modifier hasFinalized() { require(finalized, "Only if game has finalized."); _; } function setPause () internal { paused = true; } function unSetPause() internal { paused = false; } /** * @dev Transfer contract's ownership * @param _newAdmin Address to be set */ function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); adminAddress = _newAdmin; } /** * @dev Adds contract's mkt * @param _newMkt Address to be set */ function setMarketplaceAddress(address _newMkt) external onlyAdmin { require(_newMkt != address(0)); marketplaceAddress = _newMkt; } /** * @dev Sets the contract pause state * @param state True to pause */ function setPauseState(bool state) external onlyAdmin { paused = state; } /** * @dev Sets the contract to finalized * @param state True to finalize */ function setFinalized(bool state) external onlyAdmin { paused = state; finalized = state; if(finalized == true) finalizedTime = now; } } // File: contracts/ticket/TicketRegistry.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract TicketRegistry is TicketInterface, TicketStorage, AccessRegistry{ using SafeMath for uint256; using AddressUtils for address; /** * @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 ownedTokens[_owner].length; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Gets tokens of owner * @param _from address of the owner * @return array with token ids */ function getOwnedTokens(address _from) public view returns(uint256[]) { return ownedTokens[_from]; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @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 * @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) { 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 isNotPaused{ require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); require (_from != _to); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_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 { // solium-disable-next-line arg-overflow 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 _data) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow // require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @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); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace 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 by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); //emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokens[_to].push(_tokenId); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); require(ownedTokens[_from].length < 100); tokenOwner[_tokenId] = address(0); uint256[] storage tokenArray = ownedTokens[_from]; for (uint256 i = 0; i < tokenArray.length; i++){ if(tokenArray[i] == _tokenId){ tokenArray[i] = tokenArray[tokenArray.length-1]; } } delete tokenArray[tokenArray.length-1]; tokenArray.length--; } } // File: contracts/libs/PayoutDistribution.sol library PayoutDistribution { function getDistribution(uint256 tokenCount) external pure returns (uint24[21] payoutDistribution) { if(tokenCount < 101){ payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 201){ payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 301){ payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 501){ payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 1001){ payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 2001){ payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0]; }else if(tokenCount < 3001){ payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0]; }else if(tokenCount < 5001){ payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0]; }else if(tokenCount < 10001){ payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0]; }else if(tokenCount < 25001){ payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0]; } else { payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70]; } } function getSuperiorQuota(uint256 tokenCount) external pure returns (uint16 superiorQuota){ if(tokenCount < 101){ superiorQuota = 10; }else if(tokenCount < 201){ superiorQuota = 20; }else if(tokenCount < 301){ superiorQuota = 30; }else if(tokenCount < 501){ superiorQuota = 50; }else if(tokenCount < 1001){ superiorQuota = 100; }else if(tokenCount < 2001){ superiorQuota = 200; }else if(tokenCount < 3001){ superiorQuota = 300; }else if(tokenCount < 5001){ superiorQuota = 500; }else if(tokenCount < 10001){ superiorQuota = 1000; }else if(tokenCount < 25001){ superiorQuota = 2500; } else { superiorQuota = 5000; } } } // File: contracts/game/GameRegistry.sol contract GameRegistry is CryptocupStorage, TicketRegistry{ using PointsCalculator for PointsCalculator.MatchResult; using PointsCalculator for PointsCalculator.BonusMatch; using PointsCalculator for PointsCalculator.Extras; /** * @dev Checks if pValidationState is in the provided stats * @param state State required to run */ modifier checkState(pointsValidationState state){ require(pValidationState == state, "Points validation stage invalid."); _; } /** * @notice Gets current token price */ function _getTokenPrice() internal view returns(uint256 tokenPrice){ if (now >= FIRST_PHASE) { tokenPrice = (80 finney); } else { tokenPrice = STARTING_PRICE; } require(tokenPrice >= STARTING_PRICE && tokenPrice <= (80 finney)); } function _prepareMatchResultsArray() internal { matchResults.length = MATCHES_NUMBER; } function _prepareBonusResultsArray() internal { bonusMatches.length = BONUS_MATCHES; } /** * @notice Builds ERC721 token with the predictions provided by the user. * @param matches - Matches results (who wins, amount of points) * @param bonusMatches - Stats from bonus matches * @param extraStats - Total number of extra stats like touchdonws, etc. * @dev An automatic timestamp is added for internal use. */ function _createToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string userMessage) internal returns (uint256){ Token memory token = Token({ matches: matches, bonusMatches: bonusMatches, extraStats: extraStats, timeStamp: uint64(now), message: userMessage }); uint256 tokenId = tokens.push(token) - 1; require(tokenId == uint256(uint32(tokenId)), "Failed to convert tokenId to uint256."); return tokenId; } /** * @dev Sets the data source contract address * @param _address Address to be set */ function setDataSourceAddress(address _address) external onlyAdmin { DataSourceInterface c = DataSourceInterface(_address); require(c.isDataSource()); dataSource = c; dataSourceAddress = _address; } /** * @notice Called by the development team once the World Cup has ended (adminPool is set) * @dev Allows dev team to retrieve adminPool */ function adminWithdrawBalance() external onlyAdmin { uint256 adminPrize = adminPool; adminPool = 0; adminAddress.transfer(adminPrize); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function finishedGameWithdraw() external onlyAdmin hasFinished{ uint256 balance = address(this).balance; adminAddress.transfer(balance); } /** * @notice Let the admin cash-out the entire contract balance 10 days after game has finished. */ function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{ require(finalizedTime != 0 && now >= finalizedTime + 10 days ); msg.sender.transfer(address(this).balance); } function isDataSourceCallback() external pure returns (bool){ return true; } function dataSourceGetMatchesResults() external onlyAdmin { dataSource.getMatchResults(); } function dataSourceGetBonusResults() external onlyAdmin{ dataSource.getBonusResults(); } function dataSourceGetExtraStats() external onlyAdmin{ dataSource.getExtraStats(); } function dataSourceCallbackMatch(uint160 matches) external onlyDataSource{ uint160 m = matches; for(uint256 i = 0; i < MATCHES_NUMBER; i++) { matchResults[MATCHES_NUMBER - i - 1].result = uint8(m & MATCH_RESULT_MASK); matchResults[MATCHES_NUMBER - i - 1].under49 = uint8((m >> 2) & MATCH_UNDEROVER_MASK); matchResults[MATCHES_NUMBER - i - 1].touchdowns = uint8((m >> 3) & MATCH_TOUCHDOWNS_MASK); m = m >> 8; } } function dataSourceCallbackBonus(uint32 bonusResults) external onlyDataSource{ uint32 b = bonusResults; for(uint256 i = 0; i < BONUS_MATCHES; i++) { bonusMatches[BONUS_MATCHES - i - 1].bonus = uint8(b & BONUS_STAT_MASK); b = b >> 6; } } function dataSourceCallbackExtras(uint96 es) external onlyDataSource{ uint96 e = es; extraStats.interceptions = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.missedFieldGoals = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.overtimes = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.sacks = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.fieldGoals = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.fumbles = uint16(e & EXTRA_STATS_MASK); } /** * @notice Sets the points of all the tokens between the last chunk set and the amount given. * @dev This function uses all the data collected earlier by oraclize to calculate points. * @param amount The amount of tokens that should be analyzed. */ function calculatePointsBlock(uint32 amount) external{ require (gameFinishedTime == 0); require(amount + lastCheckedToken <= tokens.length); for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) { uint16 points = PointsCalculator.calculateTokenPoints(tokens[i].matches, tokens[i].bonusMatches, tokens[i].extraStats, matchResults, extraStats, bonusMatches, starMatches); tokenToPointsMap[i] = points; } lastCalculatedToken += amount; } /** * @notice Sets the structures for payout distribution, last position and superior quota. Payout distribution is the * percentage of the pot each position gets, last position is the percentage of the pot the last position gets, * and superior quota is the total amount OF winners that are given a prize. * @dev Each of this structures is dynamic and is assigned depending on the total amount of tokens in the game */ function setPayoutDistributionId () internal { uint24[21] memory auxArr = PayoutDistribution.getDistribution(tokens.length); for(uint256 i = 0; i < auxArr.length; i++){ payoutDistribution[i] = auxArr[i]; } superiorQuota = PayoutDistribution.getSuperiorQuota(tokens.length); } /** * @notice Sets the id of the last token that will be given a prize. * @dev This is done to offload some of the calculations needed for sorting, and to cap the number of sorts * needed to just the winners and not the whole array of tokens. * @param tokenId last token id */ function setLimit(uint256 tokenId) external onlyAdmin{ require(tokenId < tokens.length); require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet); pointsLimit = tokenId; pValidationState = pointsValidationState.LimitSet; lastCheckedToken = 0; lastCalculatedToken = 0; winnerCounter = 0; setPause(); setPayoutDistributionId(); } /** * @notice Sets the 10th percentile of the sorted array of points * @param amount tokens in a chunk */ function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){ require(amount + lastCheckedToken <= tokens.length); uint256 points = tokenToPointsMap[pointsLimit]; for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){ if(tokenToPointsMap[i] > points || (tokenToPointsMap[i] == points && i <= pointsLimit)){ winnerCounter++; } } lastCheckedToken += amount; if(lastCheckedToken == tokens.length){ require(superiorQuota == winnerCounter); pValidationState = pointsValidationState.LimitCalculated; } } /** * @notice Checks if the order given offchain coincides with the order of the actual previously calculated points * in the smart contract. * @dev the token sorting is done offchain so as to save on the huge amount of gas and complications that * could occur from doing all the sorting onchain. * @param sortedChunk chunk sorted by points */ function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ require(sortedChunk.length + sortedWinners.length <= winnerCounter); for(uint256 i = 0; i < sortedChunk.length - 1; i++){ uint256 id = sortedChunk[i]; uint256 sigId = sortedChunk[i+1]; require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] && id < sigId)); } if(sortedWinners.length != 0){ uint256 id2 = sortedWinners[sortedWinners.length-1]; uint256 sigId2 = sortedChunk[0]; require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] || (tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2)); } for(uint256 j = 0; j < sortedChunk.length; j++){ sortedWinners.push(sortedChunk[j]); } if(sortedWinners.length == winnerCounter){ require(sortedWinners[sortedWinners.length-1] == pointsLimit); pValidationState = pointsValidationState.OrderChecked; } } /** * @notice If anything during the point calculation and sorting part should fail, this function can reset * data structures to their initial position, so as to */ function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ sortedWinners.length = newLength; } /** * @notice Assigns prize percentage for the lucky top 30 winners. Each token will be assigned a uint256 inside * tokenToPayoutMap structure that represents the size of the pot that belongs to that token. If any tokens * tie inside of the first 30 tokens, the prize will be summed and divided equally. */ function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){ uint256 percent = 0; uint[] memory tokensEquals = new uint[](30); uint16 tokenEqualsCounter = 0; uint256 currentTokenId; uint256 currentTokenPoints; uint256 lastTokenPoints; uint32 counter = 0; uint256 maxRange = 13; if(tokens.length < 201){ maxRange = 10; } while(payoutRange < maxRange){ uint256 inRangecounter = payDistributionAmount[payoutRange]; while(inRangecounter > 0){ currentTokenId = sortedWinners[counter]; currentTokenPoints = tokenToPointsMap[currentTokenId]; inRangecounter--; //Special case for the last one if(inRangecounter == 0 && payoutRange == maxRange - 1){ if(currentTokenPoints == lastTokenPoints){ percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; } else { tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange]; } } //Fix second condition if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){ for(uint256 i = 0; i < tokenEqualsCounter; i++){ tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter); } percent = 0; tokensEquals = new uint[](30); tokenEqualsCounter = 0; } percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; counter++; lastTokenPoints = currentTokenPoints; } payoutRange++; } pValidationState = pointsValidationState.TopWinnersAssigned; lastPrizeGiven = counter; } /** * @notice Sets prize percentage to every address that wins from the position 30th onwards * @dev If there are less than 300 tokens playing, then this function will set nothing. * @param amount tokens in a chunk */ function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){ require(lastPrizeGiven + amount <= winnerCounter); uint16 inRangeCounter = payDistributionAmount[payoutRange]; for(uint256 i = 0; i < amount; i++){ if (inRangeCounter == 0){ payoutRange++; inRangeCounter = payDistributionAmount[payoutRange]; } uint256 tokenId = sortedWinners[i + lastPrizeGiven]; tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange]; inRangeCounter--; } //i + amount prize was not given yet, so amount -1 lastPrizeGiven += amount; payDistributionAmount[payoutRange] = inRangeCounter; if(lastPrizeGiven == winnerCounter){ pValidationState = pointsValidationState.WinnersAssigned; return; } } /** * @notice Sets prizes for last tokens and sets prize pool amount */ function setEnd() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){ uint256 balance = address(this).balance; adminPool = balance.mul(10).div(100); prizePool = balance.mul(90).div(100); pValidationState = pointsValidationState.Finished; gameFinishedTime = now; unSetPause(); } } // File: contracts/CryptocupNFL.sol contract CryptocupNFL is GameRegistry { constructor() public { adminAddress = msg.sender; deploymentTime = now; _prepareMatchResultsArray(); _prepareBonusResultsArray(); } /** * @dev Only accept eth from the admin */ function() external payable { require(msg.sender == adminAddress || msg.sender == marketplaceAddress); } function buildToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){ require(msg.value >= _getTokenPrice(), "Eth sent is not enough."); require(msg.sender != address(0), "Sender cannot be 0 address."); require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens."); require(now < EVENT_START, "Event already started."); //Event Start require (bytes(message).length <= 100); uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message); _mint(msg.sender, tokenId); emit LogTokenBuilt(msg.sender, tokenId, message, matches, extraStats, bonusMatches); return tokenId; } function giftToken(address giftedAddress, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){ require(msg.value >= _getTokenPrice(), "Eth sent is not enough."); require(msg.sender != address(0), "Sender cannot be 0 address."); require(ownedTokens[giftedAddress].length < 100, "Sender cannot have more than 100 tokens."); require(now < EVENT_START, "Event already started."); //Event Start require (bytes(message).length <= 100); uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message); _mint(giftedAddress, tokenId); emit LogTokenGift(msg.sender, giftedAddress, tokenId, message, matches, extraStats, bonusMatches); return tokenId; } function buildPrepaidToken(bytes32 secret) external payable onlyAdmin isNotPaused { require(msg.value >= _getTokenPrice(), "Eth sent is not enough."); require(msg.sender != address(0), "Sender cannot be 0 address."); require(now < EVENT_START, "Event already started."); //Event Start secretsMap[secret] = 1; emit LogPrepaidTokenBuilt(msg.sender, secret); } function redeemPrepaidToken(bytes32 preSecret, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external isNotPaused returns(uint256){ require(msg.sender != address(0), "Sender cannot be 0 address."); require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens."); require(now < EVENT_START, "Event already started."); //Event Start require (bytes(message).length <= 100); bytes32 secret = keccak256(preSecret); require (secretsMap[secret] == 1, "Invalid secret."); secretsMap[secret] = 0; uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message); _mint(msg.sender, tokenId); emit LogPrepaidRedeemed(msg.sender, tokenId, message, matches, extraStats, bonusMatches); return tokenId; } /** * @param tokenId - ID of token to get. * @return Returns all the valuable information about a specific token. */ function getToken(uint256 tokenId) external view returns (uint160 matches, uint32 bonusMatches, uint96 extraStats, uint64 timeStamp, string message) { Token storage token = tokens[tokenId]; matches = token.matches; bonusMatches = token.bonusMatches; extraStats = token.extraStats; timeStamp = token.timeStamp; message = token.message; } /** * @notice Allows any user to retrieve their asigned prize. This would be the sum of the price of all the tokens * owned by the caller of this function. * @dev If the caller has no prize, the function will revert costing no gas to the caller. */ function withdrawPrize() external checkState(pointsValidationState.Finished){ uint256 prize = 0; uint256[] memory tokenList = ownedTokens[msg.sender]; for(uint256 i = 0;i < tokenList.length; i++){ prize += tokenToPayoutMap[tokenList[i]]; tokenToPayoutMap[tokenList[i]] = 0; } require(prize > 0); msg.sender.transfer((prizePool.mul(prize)).div(1000000)); } //EMERGENCY CALLS //If something goes wrong or fails, these functions will allow retribution for token holders /** * @notice if there is an unresolvable problem, users can call to this function to get a refund. */ function emergencyWithdraw() external hasFinalized{ uint256 balance = STARTING_PRICE * ownedTokens[msg.sender].length; delete ownedTokens[msg.sender]; msg.sender.transfer(balance); } }
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 _from current owner of the token _to address to receive the ownership of the given token ID _tokenId uint256 ID of the token to be transferred/ solium-disable-next-line arg-overflow
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); }
12,723,284
pragma solidity ^0.5.0; import "./Services/DSRLending.sol"; // An implementation of handling automated listings contract ListingManager is DSRLending { struct Listing { uint256 price; // Token balance uint256 timestamp; // timestamp until listing is available again address renter; address owner; } // Event emitted when a listing is booked, canceled, created event listingCreated(uint256 _id, uint256 _price, bool _booked, address _renter, address _owner); event listingBooked(uint256 _id, uint256 _price, bool _booked, address _renter, address _owner); event listingClosed(uint256 _id, uint256 _price, bool _booked, address _renter, address _owner); mapping(uint256 => Listing) listings; // Users will need to stake 2 times the amount required to facilitate a payment uint256 stakeMultiplier = 2; //---Interface--- function _isBooked(uint256 _timestamp) internal view returns (bool) { return _timestamp > block.timestamp; } function getListing(uint256 _id) public view returns ( uint256 _price, // Price per day bool _booked, // Timestamp until listing is available address _renter, address _owner ) { Listing memory listing = listings[_id]; return ( listing.price, _isBooked(listing.timestamp), listing.renter, listing.owner ); } /** * Gets the total price of a listing * @param _listingPrice the price per day * @param _duration the duration of the stay in seconds */ function _getPrice(uint256 _listingPrice, uint256 _duration) internal pure returns (uint256) { return _listingPrice * (_duration / 86400); } //---Implementation--- // Creates a listing(uint256 _id) function createListing( uint256 _id, uint256 _price // Price per day ) public { Listing memory listing = Listing(_price, 0, address(0), msg.sender); listings[_id] = listing; emit listingCreated(_id, listing.price, _isBooked(listing.timestamp), listing.renter, listing.owner); } /** * Books a listing * @param _id The id of the listing * @param _duration The duration of the stay in seconds */ function bookListing(uint256 _id, uint256 _duration) public { Listing storage listing = listings[_id]; require( listing.timestamp < block.timestamp, "Cannot rent in a listing that is not open" ); require(listing.owner != address(0), "Ensure listing exists"); require(listing.owner != msg.sender, "Listing owner cannot be user"); // Get the price uint256 price = _getPrice(listing.price, _duration); require(price != 0, "Price should not be zero"); // Modify Listing listing.timestamp = getFutureTimestamp(_duration); listing.renter = msg.sender; // Stores the timelocked balance in the owner account _transfer(listing.owner, price, _duration); _transfer(msg.sender, price * stakeMultiplier, _duration); emit listingBooked(_id, price, _isBooked(listing.timestamp), listing.renter, listing.owner); } /** * Ends the listing * @param _id The id of the listing */ function endListing(uint256 _id) public { Listing storage listing = listings[_id]; require(listing.renter == msg.sender, "Listing renter is incorrect"); listing.renter = address(0); // Give back stake withdraw(); emit listingClosed(_id, listing.price, _isBooked(listing.timestamp), listing.renter, listing.owner); } }
Creates a listing(uint256 _id)
function createListing( uint256 _id, ) public { Listing memory listing = Listing(_price, 0, address(0), msg.sender); listings[_id] = listing; emit listingCreated(_id, listing.price, _isBooked(listing.timestamp), listing.renter, listing.owner); }
12,668,424
/** *Submitted for verification at Etherscan.io on 2021-07-16 */ /* *Website: https://www.coinmerge.io *Telegram: https://t.me/CoinMergeMain *Twitter: https://twitter.com/coinmerge?s=21 * *CoinMerge is the revolutionary new token and platform that not only rewards holders in Ethereum just for holding, * but is also building and expanding on a platform that combines all of the best charts and data from sites like DexTools * with all of the Community chat features offered by programs like Telegram, into a single, seamless, easy to use platform. * * Using FTPEthReflect * - FTPEthReflect is a contract as a service (CaaS). Let your traders earn rewards in ETH * * Withdraw at https://app.fairtokenproject.com * - Recommended wallet is Metamask. Support for additional wallets coming soon! * * ****USING FTPAntiBot**** * * Visit FairTokenProject.com to learn how to use FTPAntiBot and FTP Eth Redist with your project */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Ownable is Context { address private m_Owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); m_Owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return m_Owner; } function _transferOwnership(address _address) internal onlyOwner() { emit OwnershipTransferred(m_Owner, _address); m_Owner = _address; } modifier onlyOwner() { require(_msgSender() == m_Owner, "Ownable: caller is not the owner"); _; } // You will notice there is no renounceOwnership() This is an unsafe and unnecessary practice } // By renouncing ownership you lose control over your coin and open it up to potential attacks // This practice only came about because of the lack of understanding on how contracts work interface IUniswapV2Factory { // We advise not using a renounceOwnership() function. You can look up hacks of address(0) contracts. function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; 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); } interface FTPAntiBot { // Here we create the interface to interact with AntiBot function scanAddress(address _address, address _safeAddress, address _origin) external returns (bool); function registerBlock(address _recipient, address _sender, address _origin) external; } interface FTPEthReflect { function init(address _contract, uint256 _alloc, address _pair, address _pairCurrency, uint256 _liquidity, uint256 _supply) external; // function getAlloc() external view returns (uint256); function trackSell(address _holder, uint256 _newEth) external; function trackPurchase(address _holder) external; } interface FTPExternal { function owner() external returns(address); function deposit(uint256 _amount) external; } contract CoinMerge is Context, IERC20, Ownable { using SafeMath for uint256; uint256 private constant TOTAL_SUPPLY = 5000000000 * 10**9; string private m_Name = "Coin Merge"; string private m_Symbol = "CMERGE"; uint8 private m_Decimals = 9; uint256 private m_TxLimit = 24000000 * 10**9; uint256 private m_WalletLimit = m_TxLimit; uint256 private m_TXRelease; uint256 private m_PreviousBalance; uint8 private m_DevFee = 5; uint8 private m_RedistFee = 5; address payable private m_ProjectWallet; address private m_UniswapV2Pair; bool private m_Launched = false; bool private m_IsSwap = false; bool private m_Liquidity = false; mapping (address => bool) private m_Banned; mapping (address => bool) private m_TeamMember; mapping (address => bool) private m_ExcludedAddresses; mapping (address => uint256) private m_Balances; mapping (address => uint256) private m_IncomingEth; mapping (address => uint256) private m_TeamBalance; mapping (address => mapping (address => uint256)) private m_Allowances; // ETH REFLECT FTPEthReflect private EthReflect; address payable m_EthReflectSvcAddress = payable(0x574Fc478BC45cE144105Fa44D98B4B2e4BD442CB); uint256 m_EthReflectAlloc; uint256 m_EthReflectAmount; address payable private m_ExternalServiceAddress = payable(0x1Fc90cbA64722D5e70AF16783a2DFAcfD19F3beD); FTPExternal private External; FTPAntiBot private AntiBot; IUniswapV2Router02 private m_UniswapV2Router; event MaxOutTxLimit(uint MaxTransaction); event BanAddress(address Address, address Origin); modifier lockTheSwap { m_IsSwap = true; _; m_IsSwap = false; } receive() external payable { m_IncomingEth[msg.sender] += msg.value; } constructor () { AntiBot = FTPAntiBot(0xCD5312d086f078D1554e8813C27Cf6C9D1C3D9b3); External = FTPExternal(m_ExternalServiceAddress); EthReflect = FTPEthReflect(m_EthReflectSvcAddress); m_Balances[address(this)] = TOTAL_SUPPLY; m_ExcludedAddresses[address(this)] = true; m_ExcludedAddresses[owner()] = true; m_TeamBalance[0xbAAAaEb86551aB8f0C04Bb45C1BC10167E9377c7] = 0; m_TeamBalance[0xf101308187ef98d1acFa34b774CF3334Ec7279e4] = 0; m_TeamBalance[0x16E7451D072eA28f2952eefCd7cC4A30B1F6A557] = 0; m_TeamMember[0xbAAAaEb86551aB8f0C04Bb45C1BC10167E9377c7] = true; m_TeamMember[0xf101308187ef98d1acFa34b774CF3334Ec7279e4] = true; m_TeamMember[0x16E7451D072eA28f2952eefCd7cC4A30B1F6A557] = true; emit Transfer(address(0), address(this), TOTAL_SUPPLY); } // #################### // ##### DEFAULTS ##### // #################### function name() public view returns (string memory) { return m_Name; } function symbol() public view returns (string memory) { return m_Symbol; } function decimals() public view returns (uint8) { return m_Decimals; } // ##################### // ##### OVERRIDES ##### // ##################### function totalSupply() public pure override returns (uint256) { return TOTAL_SUPPLY; } function balanceOf(address _account) public view override returns (uint256) { return m_Balances[_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 m_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(), m_Allowances[_sender][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance")); return true; } // #################### // ##### PRIVATES ##### // #################### function _readyToTax(address _sender) private view returns(bool) { return !m_IsSwap && _sender != m_UniswapV2Pair; } function _pleb(address _sender, address _recipient) private view returns(bool) { return !(m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]); } function _isTrade(address _sender, address _recipient) private view returns(bool) { return _sender == m_UniswapV2Pair || _recipient == m_UniswapV2Pair; } function _senderNotUni(address _sender) private view returns(bool) { return _sender != m_UniswapV2Pair; } function _isBuy(address _sender) private view returns (bool) { return _sender == m_UniswapV2Pair; } function _txRestricted(address _sender, address _recipient) private view returns(bool) { return _sender == m_UniswapV2Pair && !m_ExcludedAddresses[_recipient]; } function _walletCapped(address _recipient) private view returns(bool) { return _recipient != m_UniswapV2Pair && !m_ExcludedAddresses[_recipient]; } function _checkTX() private view returns(uint256) { if(block.timestamp <= m_TXRelease) return m_TxLimit; else return TOTAL_SUPPLY; } 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"); m_Allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_amount > 0, "Transfer amount must be greater than zero"); require(!m_Banned[_sender] && !m_Banned[_recipient] && !m_Banned[tx.origin], "You were manually banned"); uint256 _devFee = _setFee(_sender, _recipient, m_DevFee); uint256 _redistFee = _setFee(_sender, _recipient, m_RedistFee); uint256 _totalFee = _devFee.add(_redistFee); uint256 _feeAmount = _amount.div(100).mul(_totalFee); uint256 _newAmount = _amount.sub(_feeAmount); if(_isTrade(_sender, _recipient)){ require(!AntiBot.scanAddress(_recipient, m_UniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); require(!AntiBot.scanAddress(_sender, m_UniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); AntiBot.registerBlock(_sender, _recipient, tx.origin); } if(_walletCapped(_recipient)) require(balanceOf(_recipient).add(_amount) <= _checkTX()); if (_pleb(_sender, _recipient)) { require(m_Launched); if (_txRestricted(_sender, _recipient)) require(_amount <= _checkTX()); _tax(_sender); } m_Balances[_sender] = m_Balances[_sender].sub(_amount); m_Balances[_recipient] = m_Balances[_recipient].add(_newAmount); m_Balances[address(this)] = m_Balances[address(this)].add(_feeAmount); emit Transfer(_sender, _recipient, _newAmount); _trackEthReflection(_sender, _recipient); } function _trackEthReflection(address _sender, address _recipient) private { if (_pleb(_sender, _recipient)) { if (_isBuy(_sender)) EthReflect.trackPurchase(_recipient); else if (m_EthReflectAmount > 0){ EthReflect.trackSell(_sender, m_EthReflectAmount); m_EthReflectAmount = 0; } } } function _setFee(address _sender, address _recipient,uint256 _amount) private view returns(uint256){ bool _takeFee = !(m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]); uint256 _fee = _amount; if(!_takeFee) _fee = 0; return _fee; } function _tax(address _sender) private { uint256 _tokenBalance = balanceOf(address(this)); if (_readyToTax(_sender)) { _swapTokensForETH(_tokenBalance); _disperseEth(); } } function _swapTokensForETH(uint256 _amount) private lockTheSwap { address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = m_UniswapV2Router.WETH(); _approve(address(this), address(m_UniswapV2Router), _amount); m_UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( _amount, 0, _path, address(this), block.timestamp ); } function _disperseEth() private { uint256 _currentAmount = m_IncomingEth[address(m_UniswapV2Router)].sub(m_PreviousBalance); uint256 _redistBalance = _currentAmount.div(2); uint256 _ethBalance = _currentAmount.sub(_redistBalance); uint256 _devBalance = _ethBalance.mul(1000).div(3333); uint256 _teamBalance = _ethBalance.mul(10).div(126).add(_ethBalance.div(10)).add(_ethBalance.mul(100).div(1666)); uint256 _projectBalance = _ethBalance.sub(_teamBalance).sub(_devBalance); m_EthReflectAmount = _redistBalance; m_TeamBalance[0xbAAAaEb86551aB8f0C04Bb45C1BC10167E9377c7] = m_TeamBalance[0xbAAAaEb86551aB8f0C04Bb45C1BC10167E9377c7].add(_ethBalance.mul(10).div(126)); m_TeamBalance[0xf101308187ef98d1acFa34b774CF3334Ec7279e4] = m_TeamBalance[0xf101308187ef98d1acFa34b774CF3334Ec7279e4].add(_ethBalance.div(10)); m_TeamBalance[0x16E7451D072eA28f2952eefCd7cC4A30B1F6A557] = m_TeamBalance[0x16E7451D072eA28f2952eefCd7cC4A30B1F6A557].add(_ethBalance.mul(100).div(1666)); payable(address(External)).transfer(_devBalance); External.deposit(_devBalance); payable(address(EthReflect)).transfer(_redistBalance); // m_ProjectWallet.transfer(_ethBalance.mul(1000).div(2173)); m_ProjectWallet.transfer(_projectBalance); // transfer remainder instead, incase rounding is off m_PreviousBalance = m_IncomingEth[address(m_UniswapV2Router)]; } // #################### // ##### EXTERNAL ##### // #################### // ###################### // ##### ONLY OWNER ##### // ###################### function addLiquidity() external onlyOwner() { require(!m_Liquidity,"trading is already open"); uint256 _ethBalance = address(this).balance; m_UniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY); m_UniswapV2Pair = IUniswapV2Factory(m_UniswapV2Router.factory()).createPair(address(this), m_UniswapV2Router.WETH()); m_UniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); EthReflect.init(address(this), 5000, m_UniswapV2Pair, m_UniswapV2Router.WETH(), _ethBalance, TOTAL_SUPPLY); IERC20(m_UniswapV2Pair).approve(address(m_UniswapV2Router), type(uint).max); m_Liquidity = true; } function launch() external onlyOwner() { m_Launched = true; m_TXRelease = block.timestamp + (7 minutes); } function transferOwnership(address _address) external onlyOwner() { m_ExcludedAddresses[owner()] = false; _transferOwnership(_address); m_ExcludedAddresses[_address] = true; } function addTaxWhitelist(address _address) external onlyOwner() { m_ExcludedAddresses[_address] = true; } function removeTaxWhitelist(address _address) external onlyOwner() { m_ExcludedAddresses[_address] = false; } function setTxLimit(uint256 _amount) external onlyOwner() { m_TxLimit = _amount.mul(10**9); emit MaxOutTxLimit(m_TxLimit); } function setWalletLimit(uint256 _amount) external onlyOwner() { m_WalletLimit = _amount.mul(10**9); } function manualBan(address _a) external onlyOwner() { m_Banned[_a] = true; } function removeBan(address _a) external onlyOwner() { m_Banned[_a] = false; } function teamWithdraw() external { require(m_TeamMember[_msgSender()]); require(m_TeamBalance[_msgSender()] > 0); payable(_msgSender()).transfer(m_TeamBalance[_msgSender()]); m_TeamBalance[_msgSender()] = 0; } function setProjectWallet(address payable _address) external onlyOwner() { m_ProjectWallet = _address; m_ExcludedAddresses[_address] = true; } }
This practice only came about because of the lack of understanding on how contracts work
modifier onlyOwner() { require(_msgSender() == m_Owner, "Ownable: caller is not the owner"); _; function createPair(address tokenA, address tokenB) external returns (address pair); }
7,930,529
./partial_match/1/0xE583C6ED8222265A4147362540aa7ACc5bc9634a/sources/DMEX_Base.sol
Changes the owner of the contract
function setOwner(address newOwner) public onlyOwner { emit SetOwner(owner, newOwner); owner = newOwner; }
3,655,452
./partial_match/1/0x5609FE6fDfE82e609E74C1a77B2155b34DFbAa51/sources/Crowdsourcer.sol
record contribution in accounting (will perform validations) actually transfer tokens and revert tx if any problem
function contribute( uint128 amount, uint128 feeNumerator ) external requiresInitialization beforeDisputeOnly { uint128 amountWithFees = m_accounting.addFeesOnTop(amount, feeNumerator); IERC20 rep = getREP(); require(rep.balanceOf(msg.sender) >= amountWithFees, "Not enough funds"); require( rep.allowance(msg.sender, this) >= amountWithFees, "Now enough allowance" ); uint128 deposited; uint128 depositedFees; (deposited, depositedFees) = m_accounting.contribute( msg.sender, amount, feeNumerator ); assert(deposited == amount); assert(deposited + depositedFees == amountWithFees); assert(rep.transferFrom(msg.sender, m_disputer, deposited)); assert(rep.transferFrom(msg.sender, this, depositedFees)); assertBalancesBeforeDispute(); emit ContributionAccepted(msg.sender, amount, feeNumerator); }
15,930,982
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "../interfaces/LinkTokenInterface.sol"; import "../interfaces/BlockhashStoreInterface.sol"; import "../interfaces/AggregatorV3Interface.sol"; import "../interfaces/VRFCoordinatorV2Interface.sol"; import "../interfaces/TypeAndVersionInterface.sol"; import "../interfaces/ERC677ReceiverInterface.sol"; import "./VRF.sol"; import "../ConfirmedOwner.sol"; import "../VRFConsumerBaseV2.sol"; contract VRFCoordinatorV2 is VRF, ConfirmedOwner, TypeAndVersionInterface, VRFCoordinatorV2Interface, ERC677ReceiverInterface { LinkTokenInterface public immutable LINK; AggregatorV3Interface public immutable LINK_ETH_FEED; BlockhashStoreInterface public immutable BLOCKHASH_STORE; // We need to maintain a list of consuming addresses. // This bound ensures we are able to loop over them as needed. // Should a user require more consumers, they can use multiple subscriptions. uint16 public constant MAX_CONSUMERS = 100; error TooManyConsumers(); error InsufficientBalance(); error InvalidConsumer(uint64 subId, address consumer); error InvalidSubscription(); error OnlyCallableFromLink(); error InvalidCalldata(); error MustBeSubOwner(address owner); error PendingRequestExists(); error MustBeRequestedOwner(address proposedOwner); error BalanceInvariantViolated(uint256 internalBalance, uint256 externalBalance); // Should never happen event FundsRecovered(address to, uint256 amount); // We use the subscription struct (1 word) // at fulfillment time. struct Subscription { // There are only 1e9*1e18 = 1e27 juels in existence, so the balance can fit in uint96 (2^96 ~ 7e28) uint96 balance; // Common link balance used for all consumer requests. uint64 reqCount; // For fee tiers } // We use the config for the mgmt APIs struct SubscriptionConfig { address owner; // Owner can fund/withdraw/cancel the sub. address requestedOwner; // For safely transferring sub ownership. // Maintains the list of keys in s_consumers. // We do this for 2 reasons: // 1. To be able to clean up all keys from s_consumers when canceling a subscription. // 2. To be able to return the list of all consumers in getSubscription. // Note that we need the s_consumers map to be able to directly check if a // consumer is valid without reading all the consumers from storage. address[] consumers; } // Note a nonce of 0 indicates an the consumer is not assigned to that subscription. mapping(address => mapping(uint64 => uint64)) /* consumer */ /* subId */ /* nonce */ private s_consumers; mapping(uint64 => SubscriptionConfig) /* subId */ /* subscriptionConfig */ private s_subscriptionConfigs; mapping(uint64 => Subscription) /* subId */ /* subscription */ private s_subscriptions; // We make the sub count public so that its possible to // get all the current subscriptions via getSubscription. uint64 private s_currentSubId; // s_totalBalance tracks the total link sent to/from // this contract through onTokenTransfer, cancelSubscription and oracleWithdraw. // A discrepancy with this contract's link balance indicates someone // sent tokens using transfer and so we may need to use recoverFunds. uint96 private s_totalBalance; event SubscriptionCreated(uint64 indexed subId, address owner); event SubscriptionFunded(uint64 indexed subId, uint256 oldBalance, uint256 newBalance); event SubscriptionConsumerAdded(uint64 indexed subId, address consumer); event SubscriptionConsumerRemoved(uint64 indexed subId, address consumer); event SubscriptionCanceled(uint64 indexed subId, address to, uint256 amount); event SubscriptionOwnerTransferRequested(uint64 indexed subId, address from, address to); event SubscriptionOwnerTransferred(uint64 indexed subId, address from, address to); // Set this maximum to 200 to give us a 56 block window to fulfill // the request before requiring the block hash feeder. uint16 public constant MAX_REQUEST_CONFIRMATIONS = 200; uint32 public constant MAX_NUM_WORDS = 500; // 5k is plenty for an EXTCODESIZE call (2600) + warm CALL (100) // and some arithmetic operations. uint256 private constant GAS_FOR_CALL_EXACT_CHECK = 5_000; error InvalidRequestConfirmations(uint16 have, uint16 min, uint16 max); error GasLimitTooBig(uint32 have, uint32 want); error NumWordsTooBig(uint32 have, uint32 want); error ProvingKeyAlreadyRegistered(bytes32 keyHash); error NoSuchProvingKey(bytes32 keyHash); error InvalidLinkWeiPrice(int256 linkWei); error InsufficientGasForConsumer(uint256 have, uint256 want); error NoCorrespondingRequest(); error IncorrectCommitment(); error BlockhashNotInStore(uint256 blockNum); error PaymentTooLarge(); error Reentrant(); struct RequestCommitment { uint64 blockNum; uint64 subId; uint32 callbackGasLimit; uint32 numWords; address sender; } mapping(bytes32 => address) /* keyHash */ /* oracle */ private s_provingKeys; bytes32[] private s_provingKeyHashes; mapping(address => uint96) /* oracle */ /* LINK balance */ private s_withdrawableTokens; mapping(uint256 => bytes32) /* requestID */ /* commitment */ private s_requestCommitments; event ProvingKeyRegistered(bytes32 keyHash, address indexed oracle); event ProvingKeyDeregistered(bytes32 keyHash, address indexed oracle); event RandomWordsRequested( bytes32 indexed keyHash, uint256 requestId, uint256 preSeed, uint64 indexed subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords, address indexed sender ); event RandomWordsFulfilled(uint256 indexed requestId, uint256 outputSeed, uint96 payment, bool success); struct Config { uint16 minimumRequestConfirmations; uint32 maxGasLimit; // Reentrancy protection. bool reentrancyLock; // stalenessSeconds is how long before we consider the feed price to be stale // and fallback to fallbackWeiPerUnitLink. uint32 stalenessSeconds; // Gas to cover oracle payment after we calculate the payment. // We make it configurable in case those operations are repriced. uint32 gasAfterPaymentCalculation; } int256 private s_fallbackWeiPerUnitLink; Config private s_config; FeeConfig private s_feeConfig; struct FeeConfig { // Flat fee charged per fulfillment in millionths of link // So fee range is [0, 2^32/10^6]. uint32 fulfillmentFlatFeeLinkPPMTier1; uint32 fulfillmentFlatFeeLinkPPMTier2; uint32 fulfillmentFlatFeeLinkPPMTier3; uint32 fulfillmentFlatFeeLinkPPMTier4; uint32 fulfillmentFlatFeeLinkPPMTier5; uint24 reqsForTier2; uint24 reqsForTier3; uint24 reqsForTier4; uint24 reqsForTier5; } event ConfigSet( uint16 minimumRequestConfirmations, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation, int256 fallbackWeiPerUnitLink, FeeConfig feeConfig ); constructor( address link, address blockhashStore, address linkEthFeed ) ConfirmedOwner(msg.sender) { LINK = LinkTokenInterface(link); LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); BLOCKHASH_STORE = BlockhashStoreInterface(blockhashStore); } /** * @notice Registers a proving key to an oracle. * @param oracle address of the oracle * @param publicProvingKey key that oracle can use to submit vrf fulfillments */ function registerProvingKey(address oracle, uint256[2] calldata publicProvingKey) external onlyOwner { bytes32 kh = hashOfKey(publicProvingKey); if (s_provingKeys[kh] != address(0)) { revert ProvingKeyAlreadyRegistered(kh); } s_provingKeys[kh] = oracle; s_provingKeyHashes.push(kh); emit ProvingKeyRegistered(kh, oracle); } /** * @notice Deregisters a proving key to an oracle. * @param publicProvingKey key that oracle can use to submit vrf fulfillments */ function deregisterProvingKey(uint256[2] calldata publicProvingKey) external onlyOwner { bytes32 kh = hashOfKey(publicProvingKey); address oracle = s_provingKeys[kh]; if (oracle == address(0)) { revert NoSuchProvingKey(kh); } delete s_provingKeys[kh]; for (uint256 i = 0; i < s_provingKeyHashes.length; i++) { if (s_provingKeyHashes[i] == kh) { bytes32 last = s_provingKeyHashes[s_provingKeyHashes.length - 1]; // Copy last element and overwrite kh to be deleted with it s_provingKeyHashes[i] = last; s_provingKeyHashes.pop(); } } emit ProvingKeyDeregistered(kh, oracle); } /** * @notice Returns the proving key hash key associated with this public key * @param publicKey the key to return the hash of */ function hashOfKey(uint256[2] memory publicKey) public pure returns (bytes32) { return keccak256(abi.encode(publicKey)); } /** * @notice Sets the configuration of the vrfv2 coordinator * @param minimumRequestConfirmations global min for request confirmations * @param maxGasLimit global max for request gas limit * @param stalenessSeconds if the eth/link feed is more stale then this, use the fallback price * @param gasAfterPaymentCalculation gas used in doing accounting after completing the gas measurement * @param fallbackWeiPerUnitLink fallback eth/link price in the case of a stale feed * @param feeConfig fee tier configuration */ function setConfig( uint16 minimumRequestConfirmations, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation, int256 fallbackWeiPerUnitLink, FeeConfig memory feeConfig ) external onlyOwner { if (minimumRequestConfirmations > MAX_REQUEST_CONFIRMATIONS) { revert InvalidRequestConfirmations( minimumRequestConfirmations, minimumRequestConfirmations, MAX_REQUEST_CONFIRMATIONS ); } if (fallbackWeiPerUnitLink <= 0) { revert InvalidLinkWeiPrice(fallbackWeiPerUnitLink); } s_config = Config({ minimumRequestConfirmations: minimumRequestConfirmations, maxGasLimit: maxGasLimit, stalenessSeconds: stalenessSeconds, gasAfterPaymentCalculation: gasAfterPaymentCalculation, reentrancyLock: false }); s_feeConfig = feeConfig; s_fallbackWeiPerUnitLink = fallbackWeiPerUnitLink; emit ConfigSet( minimumRequestConfirmations, maxGasLimit, stalenessSeconds, gasAfterPaymentCalculation, fallbackWeiPerUnitLink, s_feeConfig ); } function getConfig() external view returns ( uint16 minimumRequestConfirmations, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation ) { return ( s_config.minimumRequestConfirmations, s_config.maxGasLimit, s_config.stalenessSeconds, s_config.gasAfterPaymentCalculation ); } function getFeeConfig() external view returns ( uint32 fulfillmentFlatFeeLinkPPMTier1, uint32 fulfillmentFlatFeeLinkPPMTier2, uint32 fulfillmentFlatFeeLinkPPMTier3, uint32 fulfillmentFlatFeeLinkPPMTier4, uint32 fulfillmentFlatFeeLinkPPMTier5, uint24 reqsForTier2, uint24 reqsForTier3, uint24 reqsForTier4, uint24 reqsForTier5 ) { return ( s_feeConfig.fulfillmentFlatFeeLinkPPMTier1, s_feeConfig.fulfillmentFlatFeeLinkPPMTier2, s_feeConfig.fulfillmentFlatFeeLinkPPMTier3, s_feeConfig.fulfillmentFlatFeeLinkPPMTier4, s_feeConfig.fulfillmentFlatFeeLinkPPMTier5, s_feeConfig.reqsForTier2, s_feeConfig.reqsForTier3, s_feeConfig.reqsForTier4, s_feeConfig.reqsForTier5 ); } function getTotalBalance() external view returns (uint256) { return s_totalBalance; } function getFallbackWeiPerUnitLink() external view returns (int256) { return s_fallbackWeiPerUnitLink; } /** * @notice Owner cancel subscription, sends remaining link directly to the subscription owner. * @param subId subscription id * @dev notably can be called even if there are pending requests, outstanding ones may fail onchain */ function ownerCancelSubscription(uint64 subId) external onlyOwner { if (s_subscriptionConfigs[subId].owner == address(0)) { revert InvalidSubscription(); } cancelSubscriptionHelper(subId, s_subscriptionConfigs[subId].owner); } /** * @notice Recover link sent with transfer instead of transferAndCall. * @param to address to send link to */ function recoverFunds(address to) external onlyOwner { uint256 externalBalance = LINK.balanceOf(address(this)); uint256 internalBalance = uint256(s_totalBalance); if (internalBalance > externalBalance) { revert BalanceInvariantViolated(internalBalance, externalBalance); } if (internalBalance < externalBalance) { uint256 amount = externalBalance - internalBalance; LINK.transfer(to, amount); emit FundsRecovered(to, amount); } // If the balances are equal, nothing to be done. } /** * @inheritdoc VRFCoordinatorV2Interface */ function getRequestConfig() external view override returns ( uint16, uint32, bytes32[] memory ) { return (s_config.minimumRequestConfirmations, s_config.maxGasLimit, s_provingKeyHashes); } /** * @inheritdoc VRFCoordinatorV2Interface */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 requestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external override nonReentrant returns (uint256) { // Input validation using the subscription storage. if (s_subscriptionConfigs[subId].owner == address(0)) { revert InvalidSubscription(); } // Its important to ensure that the consumer is in fact who they say they // are, otherwise they could use someone else's subscription balance. // A nonce of 0 indicates consumer is not allocated to the sub. uint64 currentNonce = s_consumers[msg.sender][subId]; if (currentNonce == 0) { revert InvalidConsumer(subId, msg.sender); } // Input validation using the config storage word. if ( requestConfirmations < s_config.minimumRequestConfirmations || requestConfirmations > MAX_REQUEST_CONFIRMATIONS ) { revert InvalidRequestConfirmations( requestConfirmations, s_config.minimumRequestConfirmations, MAX_REQUEST_CONFIRMATIONS ); } // No lower bound on the requested gas limit. A user could request 0 // and they would simply be billed for the proof verification and wouldn't be // able to do anything with the random value. if (callbackGasLimit > s_config.maxGasLimit) { revert GasLimitTooBig(callbackGasLimit, s_config.maxGasLimit); } if (numWords > MAX_NUM_WORDS) { revert NumWordsTooBig(numWords, MAX_NUM_WORDS); } // Note we do not check whether the keyHash is valid to save gas. // The consequence for users is that they can send requests // for invalid keyHashes which will simply not be fulfilled. uint64 nonce = currentNonce + 1; (uint256 requestId, uint256 preSeed) = computeRequestId(keyHash, msg.sender, subId, nonce); s_requestCommitments[requestId] = keccak256( abi.encode(requestId, block.number, subId, callbackGasLimit, numWords, msg.sender) ); emit RandomWordsRequested( keyHash, requestId, preSeed, subId, requestConfirmations, callbackGasLimit, numWords, msg.sender ); s_consumers[msg.sender][subId] = nonce; return requestId; } /** * @notice Get request commitment * @param requestId id of request * @dev used to determine if a request is fulfilled or not */ function getCommitment(uint256 requestId) external view returns (bytes32) { return s_requestCommitments[requestId]; } function computeRequestId( bytes32 keyHash, address sender, uint64 subId, uint64 nonce ) private pure returns (uint256, uint256) { uint256 preSeed = uint256(keccak256(abi.encode(keyHash, sender, subId, nonce))); return (uint256(keccak256(abi.encode(keyHash, preSeed))), preSeed); } /** * @dev calls target address with exactly gasAmount gas and data as calldata * or reverts if at least gasAmount gas is not available. */ function callWithExactGas( uint256 gasAmount, address target, bytes memory data ) private returns (bool success) { // solhint-disable-next-line no-inline-assembly assembly { let g := gas() // Compute g -= GAS_FOR_CALL_EXACT_CHECK and check for underflow // The gas actually passed to the callee is min(gasAmount, 63//64*gas available). // We want to ensure that we revert if gasAmount > 63//64*gas available // as we do not want to provide them with less, however that check itself costs // gas. GAS_FOR_CALL_EXACT_CHECK ensures we have at least enough gas to be able // to revert if gasAmount > 63//64*gas available. if lt(g, GAS_FOR_CALL_EXACT_CHECK) { revert(0, 0) } g := sub(g, GAS_FOR_CALL_EXACT_CHECK) // if g - g//64 <= gasAmount, revert // (we subtract g//64 because of EIP-150) if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } // solidity calls check that a contract actually exists at the destination, so we do the same if iszero(extcodesize(target)) { revert(0, 0) } // call and return whether we succeeded. ignore return data // call(gas,addr,value,argsOffset,argsLength,retOffset,retLength) success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) } return success; } function getRandomnessFromProof(Proof memory proof, RequestCommitment memory rc) private view returns ( bytes32 keyHash, uint256 requestId, uint256 randomness ) { keyHash = hashOfKey(proof.pk); // Only registered proving keys are permitted. address oracle = s_provingKeys[keyHash]; if (oracle == address(0)) { revert NoSuchProvingKey(keyHash); } requestId = uint256(keccak256(abi.encode(keyHash, proof.seed))); bytes32 commitment = s_requestCommitments[requestId]; if (commitment == 0) { revert NoCorrespondingRequest(); } if ( commitment != keccak256(abi.encode(requestId, rc.blockNum, rc.subId, rc.callbackGasLimit, rc.numWords, rc.sender)) ) { revert IncorrectCommitment(); } bytes32 blockHash = blockhash(rc.blockNum); if (blockHash == bytes32(0)) { blockHash = BLOCKHASH_STORE.getBlockhash(rc.blockNum); if (blockHash == bytes32(0)) { revert BlockhashNotInStore(rc.blockNum); } } // The seed actually used by the VRF machinery, mixing in the blockhash uint256 actualSeed = uint256(keccak256(abi.encodePacked(proof.seed, blockHash))); randomness = VRF.randomValueFromVRFProof(proof, actualSeed); // Reverts on failure } /* * @notice Compute fee based on the request count * @param reqCount number of requests * @return feePPM fee in LINK PPM */ function getFeeTier(uint64 reqCount) public view returns (uint32) { FeeConfig memory fc = s_feeConfig; if (0 <= reqCount && reqCount <= fc.reqsForTier2) { return fc.fulfillmentFlatFeeLinkPPMTier1; } if (fc.reqsForTier2 < reqCount && reqCount <= fc.reqsForTier3) { return fc.fulfillmentFlatFeeLinkPPMTier2; } if (fc.reqsForTier3 < reqCount && reqCount <= fc.reqsForTier4) { return fc.fulfillmentFlatFeeLinkPPMTier3; } if (fc.reqsForTier4 < reqCount && reqCount <= fc.reqsForTier5) { return fc.fulfillmentFlatFeeLinkPPMTier4; } return fc.fulfillmentFlatFeeLinkPPMTier5; } /* * @notice Fulfill a randomness request * @param proof contains the proof and randomness * @param rc request commitment pre-image, committed to at request time * @return payment amount billed to the subscription * @dev simulated offchain to determine if sufficient balance is present to fulfill the request */ function fulfillRandomWords(Proof memory proof, RequestCommitment memory rc) external nonReentrant returns (uint96) { uint256 startGas = gasleft(); (bytes32 keyHash, uint256 requestId, uint256 randomness) = getRandomnessFromProof(proof, rc); uint256[] memory randomWords = new uint256[](rc.numWords); for (uint256 i = 0; i < rc.numWords; i++) { randomWords[i] = uint256(keccak256(abi.encode(randomness, i))); } delete s_requestCommitments[requestId]; VRFConsumerBaseV2 v; bytes memory resp = abi.encodeWithSelector(v.rawFulfillRandomWords.selector, requestId, randomWords); // Call with explicitly the amount of callback gas requested // Important to not let them exhaust the gas budget and avoid oracle payment. // Do not allow any non-view/non-pure coordinator functions to be called // during the consumers callback code via reentrancyLock. // Note that callWithExactGas will revert if we do not have sufficient gas // to give the callee their requested amount. s_config.reentrancyLock = true; bool success = callWithExactGas(rc.callbackGasLimit, rc.sender, resp); s_config.reentrancyLock = false; // Increment the req count for fee tier selection. uint64 reqCount = s_subscriptions[rc.subId].reqCount; s_subscriptions[rc.subId].reqCount += 1; // We want to charge users exactly for how much gas they use in their callback. // The gasAfterPaymentCalculation is meant to cover these additional operations where we // decrement the subscription balance and increment the oracles withdrawable balance. // We also add the flat link fee to the payment amount. // Its specified in millionths of link, if s_config.fulfillmentFlatFeeLinkPPM = 1 // 1 link / 1e6 = 1e18 juels / 1e6 = 1e12 juels. uint96 payment = calculatePaymentAmount( startGas, s_config.gasAfterPaymentCalculation, getFeeTier(reqCount), tx.gasprice ); if (s_subscriptions[rc.subId].balance < payment) { revert InsufficientBalance(); } s_subscriptions[rc.subId].balance -= payment; s_withdrawableTokens[s_provingKeys[keyHash]] += payment; // Include payment in the event for tracking costs. emit RandomWordsFulfilled(requestId, randomness, payment, success); return payment; } // Get the amount of gas used for fulfillment function calculatePaymentAmount( uint256 startGas, uint256 gasAfterPaymentCalculation, uint32 fulfillmentFlatFeeLinkPPM, uint256 weiPerUnitGas ) internal view returns (uint96) { int256 weiPerUnitLink; weiPerUnitLink = getFeedData(); if (weiPerUnitLink <= 0) { revert InvalidLinkWeiPrice(weiPerUnitLink); } // (1e18 juels/link) (wei/gas * gas) / (wei/link) = juels uint256 paymentNoFee = (1e18 * weiPerUnitGas * (gasAfterPaymentCalculation + startGas - gasleft())) / uint256(weiPerUnitLink); uint256 fee = 1e12 * uint256(fulfillmentFlatFeeLinkPPM); if (paymentNoFee > (1e27 - fee)) { revert PaymentTooLarge(); // Payment + fee cannot be more than all of the link in existence. } return uint96(paymentNoFee + fee); } function getFeedData() private view returns (int256) { uint32 stalenessSeconds = s_config.stalenessSeconds; bool staleFallback = stalenessSeconds > 0; uint256 timestamp; int256 weiPerUnitLink; (, weiPerUnitLink, , timestamp, ) = LINK_ETH_FEED.latestRoundData(); // solhint-disable-next-line not-rely-on-time if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { weiPerUnitLink = s_fallbackWeiPerUnitLink; } return weiPerUnitLink; } /* * @notice Oracle withdraw LINK earned through fulfilling requests * @param recipient where to send the funds * @param amount amount to withdraw */ function oracleWithdraw(address recipient, uint96 amount) external nonReentrant { if (s_withdrawableTokens[msg.sender] < amount) { revert InsufficientBalance(); } s_withdrawableTokens[msg.sender] -= amount; s_totalBalance -= amount; if (!LINK.transfer(recipient, amount)) { revert InsufficientBalance(); } } function onTokenTransfer( address, /* sender */ uint256 amount, bytes calldata data ) external override nonReentrant { if (msg.sender != address(LINK)) { revert OnlyCallableFromLink(); } if (data.length != 32) { revert InvalidCalldata(); } uint64 subId = abi.decode(data, (uint64)); if (s_subscriptionConfigs[subId].owner == address(0)) { revert InvalidSubscription(); } // We do not check that the msg.sender is the subscription owner, // anyone can fund a subscription. uint256 oldBalance = s_subscriptions[subId].balance; s_subscriptions[subId].balance += uint96(amount); s_totalBalance += uint96(amount); emit SubscriptionFunded(subId, oldBalance, oldBalance + amount); } function getCurrentSubId() external view returns (uint64) { return s_currentSubId; } /** * @inheritdoc VRFCoordinatorV2Interface */ function getSubscription(uint64 subId) external view override returns ( uint96 balance, uint64 reqCount, address owner, address[] memory consumers ) { if (s_subscriptionConfigs[subId].owner == address(0)) { revert InvalidSubscription(); } return ( s_subscriptions[subId].balance, s_subscriptions[subId].reqCount, s_subscriptionConfigs[subId].owner, s_subscriptionConfigs[subId].consumers ); } /** * @inheritdoc VRFCoordinatorV2Interface */ function createSubscription() external override nonReentrant returns (uint64) { s_currentSubId++; uint64 currentSubId = s_currentSubId; address[] memory consumers = new address[](0); s_subscriptions[currentSubId] = Subscription({balance: 0, reqCount: 0}); s_subscriptionConfigs[currentSubId] = SubscriptionConfig({ owner: msg.sender, requestedOwner: address(0), consumers: consumers }); emit SubscriptionCreated(currentSubId, msg.sender); return currentSubId; } /** * @inheritdoc VRFCoordinatorV2Interface */ function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external override onlySubOwner(subId) nonReentrant { // Proposing to address(0) would never be claimable so don't need to check. if (s_subscriptionConfigs[subId].requestedOwner != newOwner) { s_subscriptionConfigs[subId].requestedOwner = newOwner; emit SubscriptionOwnerTransferRequested(subId, msg.sender, newOwner); } } /** * @inheritdoc VRFCoordinatorV2Interface */ function acceptSubscriptionOwnerTransfer(uint64 subId) external override nonReentrant { if (s_subscriptionConfigs[subId].owner == address(0)) { revert InvalidSubscription(); } if (s_subscriptionConfigs[subId].requestedOwner != msg.sender) { revert MustBeRequestedOwner(s_subscriptionConfigs[subId].requestedOwner); } address oldOwner = s_subscriptionConfigs[subId].owner; s_subscriptionConfigs[subId].owner = msg.sender; s_subscriptionConfigs[subId].requestedOwner = address(0); emit SubscriptionOwnerTransferred(subId, oldOwner, msg.sender); } /** * @inheritdoc VRFCoordinatorV2Interface */ function removeConsumer(uint64 subId, address consumer) external override onlySubOwner(subId) nonReentrant { if (s_consumers[consumer][subId] == 0) { revert InvalidConsumer(subId, consumer); } // Note bounded by MAX_CONSUMERS address[] memory consumers = s_subscriptionConfigs[subId].consumers; uint256 lastConsumerIndex = consumers.length - 1; for (uint256 i = 0; i < consumers.length; i++) { if (consumers[i] == consumer) { address last = consumers[lastConsumerIndex]; // Storage write to preserve last element s_subscriptionConfigs[subId].consumers[i] = last; // Storage remove last element s_subscriptionConfigs[subId].consumers.pop(); break; } } delete s_consumers[consumer][subId]; emit SubscriptionConsumerRemoved(subId, consumer); } /** * @inheritdoc VRFCoordinatorV2Interface */ function addConsumer(uint64 subId, address consumer) external override onlySubOwner(subId) nonReentrant { // Already maxed, cannot add any more consumers. if (s_subscriptionConfigs[subId].consumers.length == MAX_CONSUMERS) { revert TooManyConsumers(); } if (s_consumers[consumer][subId] != 0) { // Idempotence - do nothing if already added. // Ensures uniqueness in s_subscriptions[subId].consumers. return; } // Initialize the nonce to 1, indicating the consumer is allocated. s_consumers[consumer][subId] = 1; s_subscriptionConfigs[subId].consumers.push(consumer); emit SubscriptionConsumerAdded(subId, consumer); } /** * @inheritdoc VRFCoordinatorV2Interface */ function cancelSubscription(uint64 subId, address to) external override onlySubOwner(subId) nonReentrant { if (pendingRequestExists(subId)) { revert PendingRequestExists(); } cancelSubscriptionHelper(subId, to); } function cancelSubscriptionHelper(uint64 subId, address to) private nonReentrant { SubscriptionConfig memory subConfig = s_subscriptionConfigs[subId]; Subscription memory sub = s_subscriptions[subId]; uint96 balance = sub.balance; // Note bounded by MAX_CONSUMERS; // If no consumers, does nothing. for (uint256 i = 0; i < subConfig.consumers.length; i++) { delete s_consumers[subConfig.consumers[i]][subId]; } delete s_subscriptionConfigs[subId]; delete s_subscriptions[subId]; s_totalBalance -= balance; if (!LINK.transfer(to, uint256(balance))) { revert InsufficientBalance(); } emit SubscriptionCanceled(subId, to, balance); } /** * @inheritdoc VRFCoordinatorV2Interface * @dev Looping is bounded to MAX_CONSUMERS*(number of keyhashes). * @dev Used to disable subscription canceling while outstanding request are present. */ function pendingRequestExists(uint64 subId) public view override returns (bool) { SubscriptionConfig memory subConfig = s_subscriptionConfigs[subId]; for (uint256 i = 0; i < subConfig.consumers.length; i++) { for (uint256 j = 0; j < s_provingKeyHashes.length; j++) { (uint256 reqId, ) = computeRequestId( s_provingKeyHashes[j], subConfig.consumers[i], subId, s_consumers[subConfig.consumers[i]][subId] ); if (s_requestCommitments[reqId] != 0) { return true; } } } return false; } modifier onlySubOwner(uint64 subId) { address owner = s_subscriptionConfigs[subId].owner; if (owner == address(0)) { revert InvalidSubscription(); } if (msg.sender != owner) { revert MustBeSubOwner(owner); } _; } modifier nonReentrant() { if (s_config.reentrancyLock) { revert Reentrant(); } _; } /** * @notice The type and version of this contract * @return Type and version string */ function typeAndVersion() external pure virtual override returns (string memory) { return "VRFCoordinatorV2 1.0.0"; } }
calls target address with exactly gasAmount gas and data as calldata or reverts if at least gasAmount gas is not available./ solhint-disable-next-line no-inline-assembly Compute g -= GAS_FOR_CALL_EXACT_CHECK and check for underflow The gas actually passed to the callee is min(gasAmount, 6364gas available). We want to ensure that we revert if gasAmount > 6364gas available as we do not want to provide them with less, however that check itself costs gas. GAS_FOR_CALL_EXACT_CHECK ensures we have at least enough gas to be able to revert if gasAmount > 6364gas available. if g - g64 <= gasAmount, revert (we subtract g64 because of EIP-150) solidity calls check that a contract actually exists at the destination, so we do the same
function callWithExactGas( uint256 gasAmount, address target, bytes memory data ) private returns (bool success) { assembly { let g := gas() if lt(g, GAS_FOR_CALL_EXACT_CHECK) { revert(0, 0) } g := sub(g, GAS_FOR_CALL_EXACT_CHECK) if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } if iszero(extcodesize(target)) { revert(0, 0) } } return success; }
922,671
./full_match/1/0xe5b9239A8be521C9A08ba9A4b925DFa86Ee19024/sources/contracts/CopyPasta.sol
Max tx check Buys Max wallet check Sells Don't check max wallet or you fuck up LP Check if last tx occurred this block - prevents sandwich attacks Sells No code to change transfer tax Still check max wallet
function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint32 _taxAmt; bool isSell = false; if ( from != owner() && to != owner() && from != address(this) && !mappedAddresses[to]._isExcludedFromFee && !mappedAddresses[from]._isExcludedFromFee ) { require(amount <= totalTokens / maxTxRatio, "Max tx exceeded."); require( !mappedAddresses[to]._bots && !mappedAddresses[from]._bots, "Blocklisted." ); if ( (mappedAddresses[from].isLPPair) && to != address(uniswapV2Router) ) { _taxAmt = buyTax; require( balanceOf(to) + amount <= totalTokens / maxWalletRatio, "Max wallet will be exceeded." ); } else if ( (mappedAddresses[to].isLPPair) && from != address(uniswapV2Router) ) { isSell = true; _taxAmt = sellTax; _taxAmt = 0; require( balanceOf(to) + amount <= totalTokens / maxWalletRatio, "Max wallet will be exceeded." ); } } _tokenTransfer(from, to, amount, _taxAmt, isSell); }
2,950,166
./full_match/5/0xaf5616126ABEF7313ad3F03C978dEccF80c97DF9/sources/contracts/library/erc721A/extentions/ERC721AVestable.sol
@inheritdoc IERC721AVestable
function clearVesting() external virtual override { delete s_vestingRange; }
1,890,552
./partial_match/1/0x613d6d6a81636D8707A7abf45374c4c560FA426C/sources/contracts/universal/OptimismMintableERC20Factory.sol
@custom:legacy Creates an instance of the OptimismMintableERC20 contract. Legacy version of the newer createOptimismMintableERC20 function, which has a more intuitive name. _remoteToken Address of the token on the remote chain. _name ERC20 name. _symbol ERC20 symbol. return Address of the newly created token./
function createStandardL2Token( address _remoteToken, string memory _name, string memory _symbol ) external returns (address) { return createOptimismMintableERC20(_remoteToken, _name, _symbol); }
2,708,264
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; /* ██████╗ ███████╗ █████╗ ██╗ ██╗████████╗██╗ ██╗ ██████╗ █████╗ ██████╗ ██████╗ ███████╗ ██╔══██╗██╔════╝██╔══██╗██║ ██║╚══██╔══╝╚██╗ ██╔╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝ ██████╔╝█████╗ ███████║██║ ██║ ██║ ╚████╔╝ ██║ ███████║██████╔╝██║ ██║███████╗ ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██║ ╚██╔╝ ██║ ██╔══██║██╔══██╗██║ ██║╚════██║ ██║ ██║███████╗██║ ██║███████╗██║ ██║ ██║ ╚██████╗██║ ██║██║ ██║██████╔╝███████║ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝ */ import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "hardhat/console.sol"; import "./lib/NativeMetaTransaction.sol"; import "./interfaces/IRCTreasury.sol"; import "./interfaces/IRCMarket.sol"; import "./interfaces/IRCOrderbook.sol"; import "./interfaces/IRCNftHubL2.sol"; import "./interfaces/IRCFactory.sol"; import "./interfaces/IRCBridge.sol"; /// @title Reality Cards Treasury /// @author Andrew Stanger & Daniel Chilvers /// @notice If you have found a bug, please contact andrew@realitycards.io- no hack pls!! contract RCTreasury is AccessControl, NativeMetaTransaction, IRCTreasury { using SafeERC20 for IERC20; /*╔═════════════════════════════════╗ ║ VARIABLES ║ ╚═════════════════════════════════╝*/ /// @dev orderbook instance, to remove users bids on foreclosure IRCOrderbook public override orderbook; /// @dev leaderboard instance IRCLeaderboard public override leaderboard; /// @dev token contract IERC20 public override erc20; /// @dev the Factory so only the Factory can add new markets IRCFactory public override factory; /// @dev address of (as yet non existent) Bridge for withdrawals to mainnet address public override bridgeAddress; /// @dev sum of all deposits uint256 public override totalDeposits; /// @dev the rental payments made in each market mapping(address => uint256) public override marketPot; /// @dev sum of all market pots uint256 public override totalMarketPots; /// @dev rent taken and allocated to a particular market uint256 public override marketBalance; /// @dev a quick check if a user is foreclosed mapping(address => bool) public override isForeclosed; /// @dev to keep track of the size of the rounding issue between rent collections uint256 public override marketBalanceTopup; /// @param deposit the users current deposit in wei /// @param rentalRate the daily cost of the cards the user current owns /// @param bidRate the sum total of all placed bids /// @param lastRentCalc The timestamp of the users last rent calculation /// @param lastRentalTime The timestamp the user last made a rental struct User { uint128 deposit; uint128 rentalRate; uint128 bidRate; uint64 lastRentCalc; uint64 lastRentalTime; } mapping(address => User) public user; /*╔═════════════════════════════════╗ ║ GOVERNANCE VARIABLES ║ ╚═════════════════════════════════╝*/ /// @dev only parameters that need to be are here, the rest are in the Factory /// @dev minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins) uint256 public override minRentalDayDivisor; /// @dev max deposit balance, to minimise funds at risk uint256 public override maxContractBalance; /// @dev whitelist to only allow certain addresses to deposit /// @dev intended for beta use only, will be disabled after launch mapping(address => bool) public isAllowed; bool public whitelistEnabled; /// @dev allow markets to be restricted to a certain role mapping(address => bytes32) public marketWhitelist; /// @dev to test if the uberOwner multisig all still have access they /// @dev .. will periodically be asked to update this variable. uint256 public override uberOwnerCheckTime; /*╔═════════════════════════════════╗ ║ SAFETY ║ ╚═════════════════════════════════╝*/ /// @dev if true, cannot deposit, withdraw or rent any cards across all events bool public override globalPause; /// @dev if true, cannot rent, claim or upgrade any cards for specific market mapping(address => bool) public override marketPaused; /// @dev if true, owner has locked the market pause (Governors are locked out) mapping(address => bool) public override lockMarketPaused; /*╔═════════════════════════════════╗ ║ Access Control ║ ╚═════════════════════════════════╝*/ bytes32 public constant UBER_OWNER = keccak256("UBER_OWNER"); bytes32 public constant OWNER = keccak256("OWNER"); bytes32 public constant GOVERNOR = keccak256("GOVERNOR"); bytes32 public constant FACTORY = keccak256("FACTORY"); bytes32 public constant MARKET = keccak256("MARKET"); bytes32 public constant TREASURY = keccak256("TREASURY"); bytes32 public constant ORDERBOOK = keccak256("ORDERBOOK"); bytes32 public constant WHITELIST = keccak256("WHITELIST"); bytes32 public constant ARTIST = keccak256("ARTIST"); bytes32 public constant AFFILIATE = keccak256("AFFILIATE"); bytes32 public constant CARD_AFFILIATE = keccak256("CARD_AFFILIATE"); /*╔═════════════════════════════════╗ ║ EVENTS ║ ╚═════════════════════════════════╝*/ event LogUserForeclosed(address indexed user, bool indexed foreclosed); event LogAdjustDeposit( address indexed user, uint256 indexed amount, bool increase ); event LogMarketPaused(address market, bool paused); event LogGlobalPause(bool paused); event LogMarketWhitelist(address _market, bytes32 role); /*╔═════════════════════════════════╗ ║ CONSTRUCTOR ║ ╚═════════════════════════════════╝*/ constructor(address _tokenAddress) { // initialise MetaTransactions _initializeEIP712("RealityCardsTreasury", "1"); /* setup AccessControl UBER_OWNER ┌───────────┬────┴─────┬────────────┐ │ │ │ │ OWNER FACTORY ORDERBOOK TREASURY │ │ GOVERNOR MARKET │ WHITELIST | ARTIST | AFFILIATE | CARD_AFFILIATE */ _setupRole(DEFAULT_ADMIN_ROLE, msgSender()); _setupRole(UBER_OWNER, msgSender()); _setupRole(OWNER, msgSender()); _setupRole(GOVERNOR, msgSender()); _setupRole(WHITELIST, msgSender()); _setupRole(TREASURY, address(this)); _setRoleAdmin(UBER_OWNER, UBER_OWNER); _setRoleAdmin(OWNER, UBER_OWNER); _setRoleAdmin(FACTORY, UBER_OWNER); _setRoleAdmin(ORDERBOOK, UBER_OWNER); _setRoleAdmin(TREASURY, UBER_OWNER); _setRoleAdmin(GOVERNOR, OWNER); _setRoleAdmin(WHITELIST, GOVERNOR); _setRoleAdmin(ARTIST, GOVERNOR); _setRoleAdmin(AFFILIATE, GOVERNOR); _setRoleAdmin(CARD_AFFILIATE, GOVERNOR); _setRoleAdmin(MARKET, FACTORY); // initialise adjustable parameters setMinRental(24 * 6); // MinRental is a divisor of 1 day(86400 seconds), 24*6 will set to 10 minutes setMaxContractBalance(1_000_000 ether); // 1m setTokenAddress(_tokenAddress); whitelistEnabled = true; } /*╔═════════════════════════════════╗ ║ MODIFIERS ║ ╚═════════════════════════════════╝*/ /// @notice check that funds haven't gone missing during this function call modifier balancedBooks() { _; /// @dev using >= not == in case anyone sends tokens direct to contract require( erc20.balanceOf(address(this)) >= totalDeposits + marketBalance + totalMarketPots, "Books are unbalanced!" ); } /*╔═════════════════════════════════╗ ║ GOVERNANCE - OWNER ║ ╚═════════════════════════════════╝*/ /// @dev all functions should be onlyRole(OWNER) // min rental event emitted by market. Nothing else need be emitted. /*┌────────────────────────────────────┐ │ CALLED WITHIN CONSTRUCTOR - PUBLIC │ └────────────────────────────────────┘*/ /// @notice minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins) /// @param _newDivisor the divisor to set function setMinRental(uint256 _newDivisor) public override onlyRole(OWNER) { minRentalDayDivisor = _newDivisor; } /// @notice set max deposit balance, to minimise funds at risk /// @dev this is only a soft check, it is possible to exceed this limit /// @param _newBalanceLimit the max balance to set in wei function setMaxContractBalance(uint256 _newBalanceLimit) public override onlyRole(OWNER) { maxContractBalance = _newBalanceLimit; } /*┌──────────────────────────────────────────┐ │ NOT CALLED WITHIN CONSTRUCTOR - EXTERNAL │ └──────────────────────────────────────────┘*/ /// @notice if true, cannot deposit, withdraw or rent any cards function changeGlobalPause() external override onlyRole(OWNER) { globalPause = !globalPause; emit LogGlobalPause(globalPause); } /// @notice if true, cannot make a new rental, or claim the NFT for a specific market /// @param _market The function changePauseMarket(address _market, bool _paused) external override onlyRole(OWNER) { require(hasRole(MARKET, _market), "This isn't a market"); marketPaused[_market] = _paused; lockMarketPaused[_market] = marketPaused[_market]; emit LogMarketPaused(_market, marketPaused[_market]); } /// @notice allow governance (via the factory) to approve and un pause the market if the owner hasn't paused it function unPauseMarket(address _market) external override onlyRole(FACTORY) { require(hasRole(MARKET, _market), "This isn't a market"); require(!lockMarketPaused[_market], "Owner has paused market"); marketPaused[_market] = false; emit LogMarketPaused(_market, marketPaused[_market]); } /*╔═════════════════════════════════╗ ║ WHITELIST FUNCTIONS ║ ╚═════════════════════════════════╝*/ // There are 2 whitelist functionalities here, // 1. a whitelist for users to enter the system, restrict deposits. // 2. a market specific whitelist, restrict rentals on certain markets to certain users. /// @notice if true, users must be on the whitelist to deposit function toggleWhitelist() external override onlyRole(OWNER) { whitelistEnabled = !whitelistEnabled; } /// @notice Add/Remove multiple users to the whitelist /// @param _users an array of users to add or remove /// @param add true to add the users function batchWhitelist(address[] calldata _users, bool add) external override onlyRole(GOVERNOR) { if (add) { for (uint256 index = 0; index < _users.length; index++) { RCTreasury.grantRole(WHITELIST, _users[index]); } } else { for (uint256 index = 0; index < _users.length; index++) { RCTreasury.revokeRole(WHITELIST, _users[index]); } } } /// @notice to implement (or remove) a market specific whitelist /// @param _market the market to affect /// @param _role the role required for this market /// @dev it'd be nice to pass the role as a string but then we couldn't reset this function updateMarketWhitelist(address _market, bytes32 _role) external onlyRole(GOVERNOR) { marketWhitelist[_market] = _role; emit LogMarketWhitelist(_market, _role); } /// @notice Some markets may be restricted to certain roles, /// @notice This function checks if the user has the role required for a given market /// @dev Used for the markets to check themselves /// @param _user The user to check function marketWhitelistCheck(address _user) external view override returns (bool) { bytes32 requiredRole = marketWhitelist[msgSender()]; if (requiredRole == bytes32(0)) { return true; } else { return hasRole(requiredRole, _user); } } /*╔═════════════════════════════════╗ ║ GOVERNANCE - UBER OWNER ║ ╠═════════════════════════════════╣ ║ ******** DANGER ZONE ******** ║ ╚═════════════════════════════════╝*/ /// @dev uber owner required for upgrades /// @dev deploying and setting a new factory is effectively an upgrade /// @dev this is separate so owner so can be set to multisig, or burn address to relinquish upgrade ability /// @dev ... while maintaining governance over other governance functions /// @notice Simply updates a variable with the current block.timestamp used /// @notice .. to check the uberOwner multisig controllers all still have access. function uberOwnerTest() external override onlyRole(UBER_OWNER) { uberOwnerCheckTime = block.timestamp; } function setFactoryAddress(address _newFactory) external override onlyRole(UBER_OWNER) { require(_newFactory != address(0), "Must set an address"); // factory is also an OWNER and GOVERNOR to use the proxy functions revokeRole(FACTORY, address(factory)); revokeRole(OWNER, address(factory)); revokeRole(GOVERNOR, address(factory)); factory = IRCFactory(_newFactory); grantRole(FACTORY, address(factory)); grantRole(OWNER, address(factory)); grantRole(GOVERNOR, address(factory)); } /// @notice To set the orderbook address /// @dev changing this while markets are active could prove disastrous function setOrderbookAddress(address _newOrderbook) external override onlyRole(UBER_OWNER) { require(_newOrderbook != address(0), "Must set an address"); revokeRole(ORDERBOOK, address(orderbook)); orderbook = IRCOrderbook(_newOrderbook); grantRole(ORDERBOOK, address(orderbook)); factory.setOrderbookAddress(orderbook); } /// @notice To set the leaderboard address /// @dev The treasury doesn't need the leaderboard, just setting /// @dev .. here to keep the setters in the same place. function setLeaderboardAddress(address _newLeaderboard) external override onlyRole(UBER_OWNER) { require(_newLeaderboard != address(0), "Must set an address"); leaderboard = IRCLeaderboard(_newLeaderboard); factory.setLeaderboardAddress(leaderboard); } /// @notice To change the ERC20 token. /// @dev changing this while tokens have been deposited could prove disastrous function setTokenAddress(address _newToken) public override onlyRole(UBER_OWNER) { require(_newToken != address(0), "Must set an address"); erc20 = IERC20(_newToken); } /// @notice To set the bridge address and approve token transfers function setBridgeAddress(address _newBridge) external override onlyRole(UBER_OWNER) { require(_newBridge != address(0), "Must set an address"); bridgeAddress = _newBridge; erc20.approve(_newBridge, type(uint256).max); } /// @notice Disaster recovery, pulls all funds from the Treasury to the UberOwner function globalExit() external onlyRole(UBER_OWNER) { uint256 _balance = erc20.balanceOf(address(this)); /// @dev using msg.sender instead of msgSender as a precaution should Meta-Tx be compromised erc20.safeTransfer(msg.sender, _balance); } /*╔═════════════════════════════════╗ ║ DEPOSIT AND WITHDRAW FUNCTIONS ║ ╚═════════════════════════════════╝*/ /// @notice deposit tokens into RealityCards /// @dev it is passed the user instead of using msg.sender because might be called /// @dev ... via contract or Layer1->Layer2 bot /// @param _user the user to credit the deposit to /// @param _amount the amount to deposit, must be approved function deposit(uint256 _amount, address _user) external override balancedBooks returns (bool) { require(!globalPause, "Deposits are disabled"); require( erc20.allowance(msgSender(), address(this)) >= _amount, "User not approved to send this amount" ); require( (erc20.balanceOf(address(this)) + _amount) <= maxContractBalance, "Limit hit" ); require(_amount > 0, "Must deposit something"); if (whitelistEnabled) { require(hasRole(WHITELIST, _user), "Not in whitelist"); } // do some cleaning up, it might help cancel their foreclosure orderbook.removeOldBids(_user); user[_user].deposit += SafeCast.toUint128(_amount); totalDeposits += _amount; erc20.safeTransferFrom(msgSender(), address(this), _amount); emit LogAdjustDeposit(_user, _amount, true); // this deposit could cancel the users foreclosure assessForeclosure(_user); return true; } /// @notice withdraw a users deposit either directly or over the bridge to the mainnet /// @dev this is the only function where funds leave the contract /// @param _amount the amount to withdraw /// @param _localWithdrawal if true then withdraw to the users address, otherwise to the bridge function withdrawDeposit(uint256 _amount, bool _localWithdrawal) external override balancedBooks { require(!globalPause, "Withdrawals are disabled"); address _msgSender = msgSender(); require(user[_msgSender].deposit > 0, "Nothing to withdraw"); // only allow withdraw if they have no bids, // OR they've had their cards for at least the minimum rental period require( user[_msgSender].bidRate == 0 || block.timestamp - (user[_msgSender].lastRentalTime) > uint256(1 days) / minRentalDayDivisor, "Too soon" ); // step 1: collect rent on owned cards collectRentUser(_msgSender, block.timestamp); // step 2: process withdrawal if (_amount > user[_msgSender].deposit) { _amount = user[_msgSender].deposit; } emit LogAdjustDeposit(_msgSender, _amount, false); user[_msgSender].deposit -= SafeCast.toUint128(_amount); totalDeposits -= _amount; if (_localWithdrawal) { erc20.safeTransfer(_msgSender, _amount); } else { IRCBridge bridge = IRCBridge(bridgeAddress); bridge.withdrawToMainnet(_msgSender, _amount); } // step 3: remove bids if insufficient deposit // do some cleaning up first, it might help avoid their foreclosure orderbook.removeOldBids(_msgSender); if ( user[_msgSender].bidRate != 0 && user[_msgSender].bidRate / (minRentalDayDivisor) > user[_msgSender].deposit ) { // foreclose user, this is requred to remove them from the orderbook isForeclosed[_msgSender] = true; // remove them from the orderbook orderbook.removeUserFromOrderbook(_msgSender); } } /// @notice to increase the market balance /// @dev not strictly required but prevents markets being short-changed due to rounding issues function topupMarketBalance(uint256 _amount) external override balancedBooks { marketBalanceTopup += _amount; marketBalance += _amount; erc20.safeTransferFrom(msgSender(), address(this), _amount); } /*╔═════════════════════════════════╗ ║ ERC20 helpers ║ ╚═════════════════════════════════╝*/ /// @notice allow and balance check /// @dev used for the Factory to check before spending too much gas function checkSponsorship(address sender, uint256 _amount) external view override { require( erc20.allowance(sender, address(this)) >= _amount, "Insufficient Allowance" ); require(erc20.balanceOf(sender) >= _amount, "Insufficient Balance"); } /*╔═════════════════════════════════╗ ║ MARKET CALLABLE ║ ╚═════════════════════════════════╝*/ // only markets can call these functions /// @notice a rental payment is equivalent to moving from user's deposit to market pot, /// @notice ..called by _collectRent in the market /// @param _amount amount of rent to pay in wei function payRent(uint256 _amount) external override balancedBooks onlyRole(MARKET) returns (uint256) { require(!globalPause, "Rentals are disabled"); if (marketBalance < _amount) { uint256 discrepancy = _amount - marketBalance; if (discrepancy > marketBalanceTopup) { marketBalanceTopup = 0; } else { marketBalanceTopup -= discrepancy; } _amount = marketBalance; } address _market = msgSender(); marketBalance -= _amount; marketPot[_market] += _amount; totalMarketPots += _amount; /// @dev return the amount just in case it was adjusted return _amount; } /// @notice a payout is equivalent to moving from market pot to user's deposit (the opposite of payRent) /// @param _user the user to query /// @param _amount amount to payout in wei function payout(address _user, uint256 _amount) external override balancedBooks onlyRole(MARKET) returns (bool) { require(!globalPause, "Payouts are disabled"); user[_user].deposit += SafeCast.toUint128(_amount); marketPot[msgSender()] -= _amount; totalMarketPots -= _amount; totalDeposits += _amount; assessForeclosure(_user); emit LogAdjustDeposit(_user, _amount, true); return true; } /// @dev called by _collectRentAction() in the market in situations where collectRentUser() collected too much rent function refundUser(address _user, uint256 _refund) external override balancedBooks onlyRole(MARKET) { marketBalance -= _refund; user[_user].deposit += SafeCast.toUint128(_refund); totalDeposits += _refund; emit LogAdjustDeposit(_user, _refund, true); assessForeclosure(_user); } /// @notice ability to add liquidity to the pot without being able to win (called by market sponsor function). function sponsor(address _sponsor, uint256 _amount) external override balancedBooks onlyRole(MARKET) { require(!globalPause, "Global Pause is Enabled"); address _market = msgSender(); require(!lockMarketPaused[_market], "Market is paused"); require( erc20.allowance(_sponsor, address(this)) >= _amount, "Not approved to send this amount" ); marketPot[_market] += _amount; totalMarketPots += _amount; erc20.safeTransferFrom(_sponsor, address(this), _amount); } /// @notice tracks when the user last rented- so they cannot rent and immediately withdraw, /// @notice ..thus bypassing minimum rental duration /// @param _user the user to query function updateLastRentalTime(address _user) external override onlyRole(MARKET) { // update the last rental time user[_user].lastRentalTime = SafeCast.toUint64(block.timestamp); // check if this is their first rental (no previous rental calculation) if (user[_user].lastRentCalc == 0) { // we need to start their clock ticking, update their last rental calculation time user[_user].lastRentCalc = SafeCast.toUint64(block.timestamp); } } /*╔═════════════════════════════════╗ ║ MARKET HELPERS ║ ╚═════════════════════════════════╝*/ /// @notice Allows the factory to add a new market to AccessControl /// @dev Also controls the default paused state /// @param _market The market address to add /// @param _paused If the market should be paused or not function addMarket(address _market, bool _paused) external override { require(hasRole(FACTORY, msgSender()), "Not Authorised"); marketPaused[_market] = _paused; AccessControl.grantRole(MARKET, _market); emit LogMarketPaused(_market, marketPaused[_market]); } /// @notice provides the sum total of a users bids across all markets (whether active or not) /// @param _user the user address to query function userTotalBids(address _user) external view override returns (uint256) { return user[_user].bidRate; } /// @notice provide the users remaining deposit /// @param _user the user address to query function userDeposit(address _user) external view override returns (uint256) { return uint256(user[_user].deposit); } /*╔═════════════════════════════════╗ ║ ORDERBOOK CALLABLE ║ ╚═════════════════════════════════╝*/ /// @notice updates users rental rates when ownership changes /// @dev rentalRate = sum of all active bids /// @param _oldOwner the address of the user losing ownership /// @param _newOwner the address of the user gaining ownership /// @param _oldPrice the price the old owner was paying /// @param _newPrice the price the new owner will be paying /// @param _timeOwnershipChanged the timestamp of this event function updateRentalRate( address _oldOwner, address _newOwner, uint256 _oldPrice, uint256 _newPrice, uint256 _timeOwnershipChanged ) external override onlyRole(ORDERBOOK) { if ( _timeOwnershipChanged != user[_newOwner].lastRentCalc && !hasRole(MARKET, _newOwner) ) { // The new owners rent must be collected before adjusting their rentalRate // See if the new owner has had a rent collection before or after this ownership change if (_timeOwnershipChanged < user[_newOwner].lastRentCalc) { // the new owner has a more recent rent collection uint256 _additionalRentOwed = rentOwedBetweenTimestamps( user[_newOwner].lastRentCalc, _timeOwnershipChanged, _newPrice ); // they have enough funds, just collect the extra // we can be sure of this because it was checked they can cover the minimum rental _increaseMarketBalance(_additionalRentOwed, _newOwner); emit LogAdjustDeposit(_newOwner, _additionalRentOwed, false); } else { // the new owner has an old rent collection, do they own anything else? if (user[_newOwner].rentalRate != 0) { // rent collect up-to ownership change time collectRentUser(_newOwner, _timeOwnershipChanged); } else { // first card owned, set start time user[_newOwner].lastRentCalc = SafeCast.toUint64( _timeOwnershipChanged ); // send an event for the UI to have a timestamp emit LogAdjustDeposit(_newOwner, 0, false); } } } // Must add before subtract, to avoid underflow in the case a user is only updating their price. user[_newOwner].rentalRate += SafeCast.toUint128(_newPrice); user[_oldOwner].rentalRate -= SafeCast.toUint128(_oldPrice); } /// @dev increase bidRate when new bid entered function increaseBidRate(address _user, uint256 _price) external override onlyRole(ORDERBOOK) { user[_user].bidRate += SafeCast.toUint128(_price); } /// @dev decrease bidRate when bid removed function decreaseBidRate(address _user, uint256 _price) external override onlyRole(ORDERBOOK) { user[_user].bidRate -= SafeCast.toUint128(_price); } /*╔═════════════════════════════════╗ ║ RENT CALC HELPERS ║ ╚═════════════════════════════════╝*/ /// @notice returns the rent due between the users last rent calculation and /// @notice ..the current block.timestamp for all cards a user owns /// @param _user the user to query /// @param _timeOfCollection calculate up to a given time function rentOwedUser(address _user, uint256 _timeOfCollection) internal view returns (uint256 rentDue) { return (user[_user].rentalRate * (_timeOfCollection - user[_user].lastRentCalc)) / (1 days); } /// @notice calculates the rent owed between the given timestamps /// @param _time1 one of the timestamps /// @param _time2 the second timestamp /// @param _price the rental rate for this time period /// @return _rent the rent due for this time period /// @dev the timestamps can be given in any order function rentOwedBetweenTimestamps( uint256 _time1, uint256 _time2, uint256 _price ) internal pure returns (uint256 _rent) { if (_time1 < _time2) { (_time1, _time2) = (_time2, _time1); } _rent = (_price * (_time1 - _time2)) / (1 days); } /// @notice returns the current estimate of the users foreclosure time /// @param _user the user to query /// @param _newBid calculate foreclosure including a new card /// @param _timeOfNewBid timestamp of when a new card was gained function foreclosureTimeUser( address _user, uint256 _newBid, uint256 _timeOfNewBid ) external view override returns (uint256) { uint256 totalUserDailyRent = user[_user].rentalRate; if (totalUserDailyRent > 0) { uint256 timeLeftOfDeposit = (user[_user].deposit * 1 days) / totalUserDailyRent; uint256 foreclosureTimeWithoutNewCard = user[_user].lastRentCalc + timeLeftOfDeposit; if ( foreclosureTimeWithoutNewCard > _timeOfNewBid && _timeOfNewBid != 0 ) { // calculate how long they can own the new card for uint256 _rentDifference = rentOwedBetweenTimestamps( user[_user].lastRentCalc, _timeOfNewBid, totalUserDailyRent ); uint256 _depositAtTimeOfNewBid = 0; if (user[_user].lastRentCalc < _timeOfNewBid) { // new bid is after user rent calculation _depositAtTimeOfNewBid = user[_user].deposit - _rentDifference; } else { // new bid is before user rent calculation _depositAtTimeOfNewBid = user[_user].deposit + _rentDifference; } uint256 _timeLeftOfDepositWithNewBid = (_depositAtTimeOfNewBid * 1 days) / (totalUserDailyRent + _newBid); uint256 _foreclosureTimeWithNewCard = _timeOfNewBid + _timeLeftOfDepositWithNewBid; if (_foreclosureTimeWithNewCard > user[_user].lastRentCalc) { return _foreclosureTimeWithNewCard; } else { // The user couldn't afford to own the new card up to their last // .. rent calculation, we can't rewind their rent calculation because // .. of gas limits (there could be many markets having taken rent). // Therefore unfortunately we can't give any ownership to this user as // .. this could mean getting caught in a loop we may not be able to // .. exit because of gas limits (there could be many users in this // .. situation and we can't leave any unaccounted for). // This means we return 0 to signify that the user can't afford this // .. new ownership. return 0; } } else { return user[_user].lastRentCalc + timeLeftOfDeposit; } } else { if (_newBid == 0) { // if no rentals they'll foreclose after the heat death of the universe return type(uint256).max; } else { return _timeOfNewBid + ((user[_user].deposit * 1 days) / _newBid); } } } /// @notice call for a rent collection on the given user /// @notice IF the user doesn't have enough deposit, returns foreclosure time /// @notice ..otherwise returns zero /// @param _user the user to query /// @param _timeToCollectTo the timestamp to collect rent up-to /// @return newTimeLastCollectedOnForeclosure the time the user foreclosed if they foreclosed in this calculation function collectRentUser(address _user, uint256 _timeToCollectTo) public override returns (uint256 newTimeLastCollectedOnForeclosure) { require(!globalPause, "Global pause is enabled"); require(_timeToCollectTo != 0, "Must set collection time"); require( _timeToCollectTo <= block.timestamp, "Can't collect future rent" ); if (user[_user].lastRentCalc < _timeToCollectTo) { uint256 rentOwedByUser = rentOwedUser(_user, _timeToCollectTo); if (rentOwedByUser > 0 && rentOwedByUser > user[_user].deposit) { // The User has run out of deposit already. uint256 previousCollectionTime = user[_user].lastRentCalc; /* timeTheirDepositLasted = timeSinceLastUpdate * (usersDeposit/rentOwed) = (now - previousCollectionTime) * (usersDeposit/rentOwed) */ uint256 timeUsersDepositLasts = ((_timeToCollectTo - previousCollectionTime) * uint256(user[_user].deposit)) / rentOwedByUser; /* Users last collection time = previousCollectionTime + timeTheirDepositLasted */ rentOwedByUser = uint256(user[_user].deposit); newTimeLastCollectedOnForeclosure = previousCollectionTime + timeUsersDepositLasts; _increaseMarketBalance(rentOwedByUser, _user); user[_user].lastRentCalc = SafeCast.toUint64( newTimeLastCollectedOnForeclosure ); assert(user[_user].deposit == 0); isForeclosed[_user] = true; emit LogUserForeclosed(_user, true); } else { // User has enough deposit to pay rent. _increaseMarketBalance(rentOwedByUser, _user); user[_user].lastRentCalc = SafeCast.toUint64(_timeToCollectTo); } emit LogAdjustDeposit(_user, rentOwedByUser, false); } } /// moving from the user deposit to the markets available balance function _increaseMarketBalance(uint256 rentCollected, address _user) internal { marketBalance += rentCollected; user[_user].deposit -= SafeCast.toUint128(rentCollected); totalDeposits -= rentCollected; } /// @notice checks if the user should still be foreclosed function assessForeclosure(address _user) public override { if (user[_user].deposit > (user[_user].bidRate / minRentalDayDivisor)) { isForeclosed[_user] = false; emit LogUserForeclosed(_user, false); } else { isForeclosed[_user] = true; emit LogUserForeclosed(_user, true); } } /// @dev can't be called hasRole also because AccessControl.hasRole isn't virtual function checkPermission(bytes32 role, address account) external view override returns (bool) { return AccessControl.hasRole(role, account); } /// @notice To grant a role (string) to an address /// @param role the role to grant, this is a string and will be converted to bytes32 /// @param account the account to grant the role to /// @dev Not necessary but makes granting roles easier /// @dev not called grantRole as overloading a string and bytes32 causes issues with tools like remix function grantRoleString(string memory role, address account) external override { bytes32 _role = keccak256(abi.encodePacked(role)); RCTreasury.grantRole(_role, account); } /// @notice To grant a role (bytes32) to an address /// @param role the role to grant /// @param account the account to grant the role to function grantRole(bytes32 role, address account) public override(AccessControl, IRCTreasury) { AccessControl.grantRole(role, account); } /// @notice To check is a particular account has a certain role /// @param role The role (string) to query about /// @param account the address which may have this role /// @return Bool, True if the account has role /// @dev needed because we can't override hasRole (it's not virtual) and /// @dev .. without this the contract wouldn't fully implement the interface /// @dev Similar to checkPermissions except using string instead of bytes32 function checkRole(string memory role, address account) external view override returns (bool) { bytes32 _role = keccak256(abi.encodePacked(role)); return hasRole(_role, account); } /// @notice To revoke a role (string) from an address /// @param role the role to revoke, this is a string and will be converted to bytes32 /// @param account the account to revoke the role from /// @dev Not necessary but makes revoking roles easier /// @dev not called revokeRole as overloading a string and bytes32 causes issues with tools like remix function revokeRoleString(string memory role, address account) external override { bytes32 _role = keccak256(abi.encodePacked(role)); RCTreasury.revokeRole(_role, account); } /// @notice To revoke a role (bytes32) from an address /// @param role the role to revoke /// @param account the account to revoke the role from function revokeRole(bytes32 role, address account) public override(AccessControl, IRCTreasury) { AccessControl.revokeRole(role, account); } /* ▲ ▲ ▲ */ }
minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins) _newDivisor the divisor to set
function setMinRental(uint256 _newDivisor) public override onlyRole(OWNER) { minRentalDayDivisor = _newDivisor; }
979,345
./partial_match/3/0xE5dD5466314a590680d107B2Dea8114cd694BBfd/sources/Strategy.sol
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"); }
5,277,432
// SPDX-License-Identifier: AGPL-3.0-or-later // hevm: flattened sources of src/DssSpell.sol pragma solidity =0.6.12 >=0.6.11 <0.7.0; ////// lib/dss-exec-lib/src/CollateralOpts.sol /* pragma solidity ^0.6.11; */ struct CollateralOpts { bytes32 ilk; address gem; address join; address flip; address pip; bool isLiquidatable; bool isOSM; bool whitelistOSM; uint256 ilkDebtCeiling; uint256 minVaultAmount; uint256 maxLiquidationAmount; uint256 liquidationPenalty; uint256 ilkStabilityFee; uint256 bidIncrease; uint256 bidDuration; uint256 auctionDuration; uint256 liquidationRatio; } ////// lib/dss-exec-lib/src/DssExecLib.sol // // DssExecLib.sol -- MakerDAO Executive Spellcrafting Library // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.11; */ interface Initializable { function init(bytes32) external; } interface Authorizable { function rely(address) external; function deny(address) external; } interface Fileable { function file(bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, address) external; } interface Drippable { function drip() external returns (uint256); function drip(bytes32) external returns (uint256); } interface Pricing { function poke(bytes32) external; } interface ERC20 { function decimals() external returns (uint8); } interface DssVat { function hope(address) external; function nope(address) external; function ilks(bytes32) external returns (uint256 Art, uint256 rate, uint256 spot, uint256 line, uint256 dust); function Line() external view returns (uint256); function suck(address, address, uint) external; } interface AuctionLike { function vat() external returns (address); function cat() external returns (address); // Only flip function beg() external returns (uint256); function pad() external returns (uint256); // Only flop function ttl() external returns (uint256); function tau() external returns (uint256); function ilk() external returns (bytes32); // Only flip function gem() external returns (bytes32); // Only flap/flop } interface JoinLike { function vat() external returns (address); function ilk() external returns (bytes32); function gem() external returns (address); function dec() external returns (uint256); function join(address, uint) external; function exit(address, uint) external; } // Includes Median and OSM functions interface OracleLike_2 { function src() external view returns (address); function lift(address[] calldata) external; function drop(address[] calldata) external; function setBar(uint256) external; function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; } interface MomLike { function setOsm(bytes32, address) external; } interface RegistryLike { function add(address) external; function info(bytes32) external view returns ( string memory, string memory, uint256, address, address, address, address ); function ilkData(bytes32) external view returns ( uint256 pos, address gem, address pip, address join, address flip, uint256 dec, string memory name, string memory symbol ); } // https://github.com/makerdao/dss-chain-log interface ChainlogLike { function setVersion(string calldata) external; function setIPFS(string calldata) external; function setSha256sum(string calldata) external; function getAddress(bytes32) external view returns (address); function setAddress(bytes32, address) external; function removeAddress(bytes32) external; } interface IAMLike { function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48); function setIlk(bytes32,uint256,uint256,uint256) external; function remIlk(bytes32) external; function exec(bytes32) external returns (uint256); } library DssExecLib { /*****************/ /*** Constants ***/ /*****************/ address constant public LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F; uint256 constant internal WAD = 10 ** 18; uint256 constant internal RAY = 10 ** 27; uint256 constant internal RAD = 10 ** 45; uint256 constant internal THOUSAND = 10 ** 3; uint256 constant internal MILLION = 10 ** 6; uint256 constant internal BPS_ONE_PCT = 100; uint256 constant internal BPS_ONE_HUNDRED_PCT = 100 * BPS_ONE_PCT; uint256 constant internal RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027; /**********************/ /*** Math Functions ***/ /**********************/ function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } /****************************/ /*** Core Address Helpers ***/ /****************************/ function dai() public view returns (address) { return getChangelogAddress("MCD_DAI"); } function mkr() public view returns (address) { return getChangelogAddress("MCD_GOV"); } function vat() public view returns (address) { return getChangelogAddress("MCD_VAT"); } function cat() public view returns (address) { return getChangelogAddress("MCD_CAT"); } function jug() public view returns (address) { return getChangelogAddress("MCD_JUG"); } function pot() public view returns (address) { return getChangelogAddress("MCD_POT"); } function vow() public view returns (address) { return getChangelogAddress("MCD_VOW"); } function end() public view returns (address) { return getChangelogAddress("MCD_END"); } function reg() public view returns (address) { return getChangelogAddress("ILK_REGISTRY"); } function spotter() public view returns (address) { return getChangelogAddress("MCD_SPOT"); } function flap() public view returns (address) { return getChangelogAddress("MCD_FLAP"); } function flop() public view returns (address) { return getChangelogAddress("MCD_FLOP"); } function osmMom() public view returns (address) { return getChangelogAddress("OSM_MOM"); } function govGuard() public view returns (address) { return getChangelogAddress("GOV_GUARD"); } function flipperMom() public view returns (address) { return getChangelogAddress("FLIPPER_MOM"); } function pauseProxy() public view returns (address) { return getChangelogAddress("MCD_PAUSE_PROXY"); } function autoLine() public view returns (address) { return getChangelogAddress("MCD_IAM_AUTO_LINE"); } function daiJoin() public view returns (address) { return getChangelogAddress("MCD_JOIN_DAI"); } function flip(bytes32 ilk) public view returns (address _flip) { (,,,, _flip,,,) = RegistryLike(reg()).ilkData(ilk); } function getChangelogAddress(bytes32 key) public view returns (address) { return ChainlogLike(LOG).getAddress(key); } /****************************/ /*** Changelog Management ***/ /****************************/ /** @dev Set an address in the MCD on-chain changelog. @param _key Access key for the address (e.g. "MCD_VAT") @param _val The address associated with the _key */ function setChangelogAddress(bytes32 _key, address _val) public { ChainlogLike(LOG).setAddress(_key, _val); } /** @dev Set version in the MCD on-chain changelog. @param _version Changelog version (e.g. "1.1.2") */ function setChangelogVersion(string memory _version) public { ChainlogLike(LOG).setVersion(_version); } /** @dev Set IPFS hash of IPFS changelog in MCD on-chain changelog. @param _ipfsHash IPFS hash (e.g. "QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW") */ function setChangelogIPFS(string memory _ipfsHash) public { ChainlogLike(LOG).setIPFS(_ipfsHash); } /** @dev Set SHA256 hash in MCD on-chain changelog. @param _SHA256Sum SHA256 hash (e.g. "e42dc9d043a57705f3f097099e6b2de4230bca9a020c797508da079f9079e35b") */ function setChangelogSHA256(string memory _SHA256Sum) public { ChainlogLike(LOG).setSha256sum(_SHA256Sum); } /**********************/ /*** Authorizations ***/ /**********************/ /** @dev Give an address authorization to perform auth actions on the contract. @param _base The address of the contract where the authorization will be set @param _ward Address to be authorized */ function authorize(address _base, address _ward) public { Authorizable(_base).rely(_ward); } /** @dev Revoke contract authorization from an address. @param _base The address of the contract where the authorization will be revoked @param _ward Address to be deauthorized */ function deauthorize(address _base, address _ward) public { Authorizable(_base).deny(_ward); } /** @dev Delegate vat authority to the specified address. @param _usr Address to be authorized */ function delegateVat(address _usr) public { DssVat(vat()).hope(_usr); } /** @dev Revoke vat authority to the specified address. @param _usr Address to be deauthorized */ function undelegateVat(address _usr) public { DssVat(vat()).nope(_usr); } /**************************/ /*** Accumulating Rates ***/ /**************************/ /** @dev Update rate accumulation for the Dai Savings Rate (DSR). */ function accumulateDSR() public { Drippable(pot()).drip(); } /** @dev Update rate accumulation for the stability fees of a given collateral type. @param _ilk Collateral type */ function accumulateCollateralStabilityFees(bytes32 _ilk) public { Drippable(jug()).drip(_ilk); } /*********************/ /*** Price Updates ***/ /*********************/ /** @dev Update price of a given collateral type. @param _ilk Collateral type */ function updateCollateralPrice(bytes32 _ilk) public { Pricing(spotter()).poke(_ilk); } /****************************/ /*** System Configuration ***/ /****************************/ /** @dev Set a contract in another contract, defining the relationship (ex. set a new Cat contract in the Vat) @param _base The address of the contract where the new contract address will be filed @param _what Name of contract to file @param _addr Address of contract to file */ function setContract(address _base, bytes32 _what, address _addr) public { Fileable(_base).file(_what, _addr); } /** @dev Set a contract in another contract, defining the relationship (ex. set a new Cat contract in the Vat) @param _base The address of the contract where the new contract address will be filed @param _ilk Collateral type @param _what Name of contract to file @param _addr Address of contract to file */ function setContract(address _base, bytes32 _ilk, bytes32 _what, address _addr) public { Fileable(_base).file(_ilk, _what, _addr); } /******************************/ /*** System Risk Parameters ***/ /******************************/ // function setGlobalDebtCeiling(uint256 _amount) public { setGlobalDebtCeiling(vat(), _amount); } /** @dev Set the global debt ceiling. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setGlobalDebtCeiling(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-global-Line-precision" Fileable(vat()).file("Line", _amount * RAD); } /** @dev Increase the global debt ceiling by a specific amount. Amount will be converted to the correct internal precision. @param _amount The amount to add in DAI (ex. 10m DAI amount == 10000000) */ function increaseGlobalDebtCeiling(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-Line-increase-precision" address _vat = vat(); Fileable(_vat).file("Line", add(DssVat(_vat).Line(), _amount * RAD)); } /** @dev Decrease the global debt ceiling by a specific amount. Amount will be converted to the correct internal precision. @param _amount The amount to reduce in DAI (ex. 10m DAI amount == 10000000) */ function decreaseGlobalDebtCeiling(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-Line-decrease-precision" address _vat = vat(); Fileable(_vat).file("Line", sub(DssVat(_vat).Line(), _amount * RAD)); } /** @dev Set the Dai Savings Rate. See: docs/rates.txt @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) */ function setDSR(uint256 _rate) public { require((_rate >= RAY) && (_rate <= RATES_ONE_HUNDRED_PCT)); // "LibDssExec/dsr-out-of-bounds" Fileable(pot()).file("dsr", _rate); } /** @dev Set the DAI amount for system surplus auctions. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setSurplusAuctionAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-bump-precision" Fileable(vow()).file("bump", _amount * RAD); } /** @dev Set the DAI amount for system surplus buffer, must be exceeded before surplus auctions start. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setSurplusBuffer(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-hump-precision" Fileable(vow()).file("hump", _amount * RAD); } /** @dev Set minimum bid increase for surplus auctions. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setMinSurplusAuctionBidIncrease(uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-flap-beg-precision" Fileable(flap()).file("beg", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set bid duration for surplus auctions. @param _duration Amount of time for bids. */ function setSurplusAuctionBidDuration(uint256 _duration) public { Fileable(flap()).file("ttl", _duration); } /** @dev Set total auction duration for surplus auctions. @param _duration Amount of time for auctions. */ function setSurplusAuctionDuration(uint256 _duration) public { Fileable(flap()).file("tau", _duration); } /** @dev Set the number of seconds that pass before system debt is auctioned for MKR tokens. @param _duration Duration in seconds */ function setDebtAuctionDelay(uint256 _duration) public { Fileable(vow()).file("wait", _duration); } /** @dev Set the DAI amount for system debt to be covered by each debt auction. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setDebtAuctionDAIAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-sump-precision" Fileable(vow()).file("sump", _amount * RAD); } /** @dev Set the starting MKR amount to be auctioned off to cover system debt in debt auctions. Amount will be converted to the correct internal precision. @param _amount The amount to set in MKR (ex. 250 MKR amount == 250) */ function setDebtAuctionMKRAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-dump-precision" Fileable(vow()).file("dump", _amount * WAD); } /** @dev Set minimum bid increase for debt auctions. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setMinDebtAuctionBidIncrease(uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-flap-beg-precision" Fileable(flop()).file("beg", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set bid duration for debt auctions. @param _duration Amount of time for bids. */ function setDebtAuctionBidDuration(uint256 _duration) public { Fileable(flop()).file("ttl", _duration); } /** @dev Set total auction duration for debt auctions. @param _duration Amount of time for auctions. */ function setDebtAuctionDuration(uint256 _duration) public { Fileable(flop()).file("tau", _duration); } /** @dev Set the rate of increasing amount of MKR out for auction during debt auctions. Amount will be converted to the correct internal precision. @dev MKR amount is increased by this rate every "tick" (if auction duration has passed and no one has bid on the MKR) @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setDebtAuctionMKRIncreaseRate(uint256 _pct_bps) public { Fileable(flop()).file("pad", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set the maximum total DAI amount that can be out for liquidation in the system at any point. Amount will be converted to the correct internal precision. @param _amount The amount to set in DAI (ex. 250,000 DAI amount == 250000) */ function setMaxTotalDAILiquidationAmount(uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-vow-dump-precision" Fileable(cat()).file("box", _amount * RAD); } /** @dev Set the duration of time that has to pass during emergency shutdown before collateral can start being claimed by DAI holders. @param _duration Time in seconds to set for ES processing time */ function setEmergencyShutdownProcessingTime(uint256 _duration) public { Fileable(end()).file("wait", _duration); } /** @dev Set the global stability fee (is not typically used, currently is 0). Many of the settings that change weekly rely on the rate accumulator described at https://docs.makerdao.com/smart-contract-modules/rates-module To check this yourself, use the following rate calculation (example 8%): $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' A table of rates can also be found at: https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) */ function setGlobalStabilityFee(uint256 _rate) public { require((_rate >= RAY) && (_rate <= RATES_ONE_HUNDRED_PCT)); // "LibDssExec/global-stability-fee-out-of-bounds" Fileable(jug()).file("base", _rate); } /** @dev Set the value of DAI in the reference asset (e.g. $1 per DAI). Value will be converted to the correct internal precision. @dev Equation used for conversion is value * RAY / 1000 @param _value The value to set as integer (x1000) (ex. $1.025 == 1025) */ function setDAIReferenceValue(uint256 _value) public { require(_value < WAD); // "LibDssExec/incorrect-ilk-dunk-precision" Fileable(spotter()).file("par", rdiv(_value, 1000)); } /*****************************/ /*** Collateral Management ***/ /*****************************/ /** @dev Set a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkDebtCeiling(bytes32 _ilk, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" Fileable(vat()).file(_ilk, "line", _amount * RAD); } /** @dev Increase a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to increase in DAI (ex. 10m DAI amount == 10000000) @param _global If true, increases the global debt ceiling by _amount */ function increaseIlkDebtCeiling(bytes32 _ilk, uint256 _amount, bool _global) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" address _vat = vat(); (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk); Fileable(_vat).file(_ilk, "line", add(line_, _amount * RAD)); if (_global) { increaseGlobalDebtCeiling(_amount); } } /** @dev Decrease a collateral debt ceiling. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to decrease in DAI (ex. 10m DAI amount == 10000000) @param _global If true, decreases the global debt ceiling by _amount */ function decreaseIlkDebtCeiling(bytes32 _ilk, uint256 _amount, bool _global) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" address _vat = vat(); (,,,uint256 line_,) = DssVat(_vat).ilks(_ilk); Fileable(_vat).file(_ilk, "line", sub(line_, _amount * RAD)); if (_global) { decreaseGlobalDebtCeiling(_amount); } } /** @dev Set the parameters for an ilk in the "MCD_IAM_AUTO_LINE" auto-line @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The Maximum value (ex. 100m DAI amount == 100000000) @param _gap The amount of Dai per step (ex. 5m Dai == 5000000) @param _ttl The amount of time (in seconds) */ function setIlkAutoLineParameters(bytes32 _ilk, uint256 _amount, uint256 _gap, uint256 _ttl) public { require(_amount < WAD); // "LibDssExec/incorrect-auto-line-amount-precision" require(_gap < WAD); // "LibDssExec/incorrect-auto-line-gap-precision" IAMLike(autoLine()).setIlk(_ilk, _amount * RAD, _gap * RAD, _ttl); } /** @dev Set the debt ceiling for an ilk in the "MCD_IAM_AUTO_LINE" auto-line without updating the time values @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to decrease in DAI (ex. 10m DAI amount == 10000000) */ function setIlkAutoLineDebtCeiling(bytes32 _ilk, uint256 _amount) public { address _autoLine = autoLine(); (, uint256 gap, uint48 ttl,,) = IAMLike(_autoLine).ilks(_ilk); require(gap != 0 && ttl != 0); // "LibDssExec/auto-line-not-configured" IAMLike(_autoLine).setIlk(_ilk, _amount * RAD, uint256(gap), uint256(ttl)); } /** @dev Remove an ilk in the "MCD_IAM_AUTO_LINE" auto-line @param _ilk The ilk to remove (ex. bytes32("ETH-A")) */ function removeIlkFromAutoLine(bytes32 _ilk) public { IAMLike(autoLine()).remIlk(_ilk); } /** @dev Set a collateral minimum vault amount. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkMinVaultAmount(bytes32 _ilk, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-dust-precision" Fileable(vat()).file(_ilk, "dust", _amount * RAD); } /** @dev Set a collateral liquidation penalty. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 10.25% = 10.25 * 100 = 1025) */ function setIlkLiquidationPenalty(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-ilk-chop-precision" Fileable(cat()).file(_ilk, "chop", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set max DAI amount for liquidation per vault for collateral. Amount will be converted to the correct internal precision. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _amount The amount to set in DAI (ex. 10m DAI amount == 10000000) */ function setIlkMaxLiquidationAmount(bytes32 _ilk, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-dunk-precision" Fileable(cat()).file(_ilk, "dunk", _amount * RAD); } /** @dev Set a collateral liquidation ratio. Amount will be converted to the correct internal precision. @dev Equation used for conversion is pct * RAY / 10,000 @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 150% = 150 * 100 = 15000) */ function setIlkLiquidationRatio(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < 10 * BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-ilk-mat-precision" // Fails if pct >= 1000% require(_pct_bps >= BPS_ONE_HUNDRED_PCT); // the liquidation ratio has to be bigger or equal to 100% Fileable(spotter()).file(_ilk, "mat", rdiv(_pct_bps, BPS_ONE_HUNDRED_PCT)); } /** @dev Set minimum bid increase for collateral. Amount will be converted to the correct internal precision. @dev Equation used for conversion is (1 + pct / 10,000) * WAD @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _pct_bps The pct, in basis points, to set in integer form (x100). (ex. 5% = 5 * 100 = 500) */ function setIlkMinAuctionBidIncrease(bytes32 _ilk, uint256 _pct_bps) public { require(_pct_bps < BPS_ONE_HUNDRED_PCT); // "LibDssExec/incorrect-ilk-chop-precision" Fileable(flip(_ilk)).file("beg", add(WAD, wdiv(_pct_bps, BPS_ONE_HUNDRED_PCT))); } /** @dev Set bid duration for a collateral type. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _duration Amount of time for bids. */ function setIlkBidDuration(bytes32 _ilk, uint256 _duration) public { Fileable(flip(_ilk)).file("ttl", _duration); } /** @dev Set auction duration for a collateral type. @param _ilk The ilk to update (ex. bytes32("ETH-A")) @param _duration Amount of time for auctions. */ function setIlkAuctionDuration(bytes32 _ilk, uint256 _duration) public { Fileable(flip(_ilk)).file("tau", _duration); } /** @dev Set the stability fee for a given ilk. Many of the settings that change weekly rely on the rate accumulator described at https://docs.makerdao.com/smart-contract-modules/rates-module To check this yourself, use the following rate calculation (example 8%): $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' A table of rates can also be found at: https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW @param _ilk The ilk to update (ex. bytes32("ETH-A") ) @param _rate The accumulated rate (ex. 4% => 1000000001243680656318820312) @param _doDrip `true` to accumulate stability fees for the collateral */ function setIlkStabilityFee(bytes32 _ilk, uint256 _rate, bool _doDrip) public { require((_rate >= RAY) && (_rate <= RATES_ONE_HUNDRED_PCT)); // "LibDssExec/ilk-stability-fee-out-of-bounds" address _jug = jug(); if (_doDrip) Drippable(_jug).drip(_ilk); Fileable(_jug).file(_ilk, "duty", _rate); } /*************************/ /*** Oracle Management ***/ /*************************/ /** @dev Adds oracle feeds to the Median's writer whitelist, allowing the feeds to write prices. @param _median Median core contract address @param _feeds Array of oracle feed addresses to add to whitelist */ function addWritersToMedianWhitelist(address _median, address[] memory _feeds) public { OracleLike_2(_median).lift(_feeds); } /** @dev Removes oracle feeds to the Median's writer whitelist, disallowing the feeds to write prices. @param _median Median core contract address @param _feeds Array of oracle feed addresses to remove from whitelist */ function removeWritersFromMedianWhitelist(address _median, address[] memory _feeds) public { OracleLike_2(_median).drop(_feeds); } /** @dev Adds addresses to the Median's reader whitelist, allowing the addresses to read prices from the median. @param _median Median core contract address @param _readers Array of addresses to add to whitelist */ function addReadersToMedianWhitelist(address _median, address[] memory _readers) public { OracleLike_2(_median).kiss(_readers); } /** @dev Adds an address to the Median's reader whitelist, allowing the address to read prices from the median. @param _median Median core contract address @param _reader Address to add to whitelist */ function addReaderToMedianWhitelist(address _median, address _reader) public { OracleLike_2(_median).kiss(_reader); } /** @dev Removes addresses from the Median's reader whitelist, disallowing the addresses to read prices from the median. @param _median Median core contract address @param _readers Array of addresses to remove from whitelist */ function removeReadersFromMedianWhitelist(address _median, address[] memory _readers) public { OracleLike_2(_median).diss(_readers); } /** @dev Removes an address to the Median's reader whitelist, disallowing the address to read prices from the median. @param _median Median core contract address @param _reader Address to remove from whitelist */ function removeReaderFromMedianWhitelist(address _median, address _reader) public { OracleLike_2(_median).diss(_reader); } /** @dev Sets the minimum number of valid messages from whitelisted oracle feeds needed to update median price. @param _median Median core contract address @param _minQuorum Minimum number of valid messages from whitelisted oracle feeds needed to update median price (NOTE: MUST BE ODD NUMBER) */ function setMedianWritersQuorum(address _median, uint256 _minQuorum) public { OracleLike_2(_median).setBar(_minQuorum); } /** @dev Adds an address to the Median's reader whitelist, allowing the address to read prices from the OSM. @param _osm Oracle Security Module (OSM) core contract address @param _reader Address to add to whitelist */ function addReaderToOSMWhitelist(address _osm, address _reader) public { OracleLike_2(_osm).kiss(_reader); } /** @dev Removes an address to the Median's reader whitelist, disallowing the address to read prices from the OSM. @param _osm Oracle Security Module (OSM) core contract address @param _reader Address to remove from whitelist */ function removeReaderFromOSMWhitelist(address _osm, address _reader) public { OracleLike_2(_osm).diss(_reader); } /** @dev Add OSM address to OSM mom, allowing it to be frozen by governance. @param _osm Oracle Security Module (OSM) core contract address @param _ilk Collateral type using OSM */ function allowOSMFreeze(address _osm, bytes32 _ilk) public { MomLike(osmMom()).setOsm(_ilk, _osm); } /*****************************/ /*** Collateral Onboarding ***/ /*****************************/ /** @dev Performs basic functions and sanity checks to add a new collateral type to the MCD system @param _ilk Collateral type key code [Ex. "ETH-A"] @param _gem Address of token contract @param _join Address of join adapter @param _flip Address of flipper @param _pip Address of price feed */ function addCollateralBase( bytes32 _ilk, address _gem, address _join, address _flip, address _pip ) public { // Sanity checks address _vat = vat(); address _cat = cat(); require(JoinLike(_join).vat() == _vat); // "join-vat-not-match" require(JoinLike(_join).ilk() == _ilk); // "join-ilk-not-match" require(JoinLike(_join).gem() == _gem); // "join-gem-not-match" require(JoinLike(_join).dec() == ERC20(_gem).decimals()); // "join-dec-not-match" require(AuctionLike(_flip).vat() == _vat); // "flip-vat-not-match" require(AuctionLike(_flip).cat() == _cat); // "flip-cat-not-match" require(AuctionLike(_flip).ilk() == _ilk); // "flip-ilk-not-match" // Set the token PIP in the Spotter setContract(spotter(), _ilk, "pip", _pip); // Set the ilk Flipper in the Cat setContract(_cat, _ilk, "flip", _flip); // Init ilk in Vat & Jug Initializable(_vat).init(_ilk); // Vat Initializable(jug()).init(_ilk); // Jug // Allow ilk Join to modify Vat registry authorize(_vat, _join); // Allow the ilk Flipper to reduce the Cat litterbox on deal() authorize(_cat, _flip); // Allow Cat to kick auctions in ilk Flipper authorize(_flip, _cat); // Allow End to yank auctions in ilk Flipper authorize(_flip, end()); // Add new ilk to the IlkRegistry RegistryLike(reg()).add(_join); } /***************/ /*** Payment ***/ /***************/ /** @dev Send a payment in ERC20 DAI from the surplus buffer. @param _target The target address to send the DAI to. @param _amount The amount to send in DAI (ex. 10m DAI amount == 10000000) */ function sendPaymentFromSurplusBuffer(address _target, uint256 _amount) public { require(_amount < WAD); // "LibDssExec/incorrect-ilk-line-precision" DssVat(vat()).suck(vow(), address(this), _amount * RAD); JoinLike(daiJoin()).exit(_target, _amount * WAD); } } ////// lib/dss-exec-lib/src/DssAction.sol // // DssAction.sol -- DSS Executive Spell Actions // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.11; */ /* import "./CollateralOpts.sol"; */ /* import { DssExecLib } from "./DssExecLib.sol"; */ interface OracleLike_1 { function src() external view returns (address); } abstract contract DssAction { using DssExecLib for *; // Office Hours defaults to true by default. // To disable office hours, override this function and // return false in the inherited action. function officeHours() public virtual returns (bool) { return true; } // DssExec calls execute. We limit this function subject to officeHours modifier. function execute() external limited { actions(); } // DssAction developer must override `actions()` and place all actions to be called inside. // The DssExec function will call this subject to the officeHours limiter // By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time. function actions() public virtual; // Modifier required to modifier limited { if (officeHours()) { uint day = (block.timestamp / 1 days + 3) % 7; require(day < 5, "Can only be cast on a weekday"); uint hour = block.timestamp / 1 hours % 24; require(hour >= 14 && hour < 21, "Outside office hours"); } _; } /*****************************/ /*** Collateral Onboarding ***/ /*****************************/ // Complete collateral onboarding logic. function addNewCollateral(CollateralOpts memory co) internal { // Add the collateral to the system. DssExecLib.addCollateralBase(co.ilk, co.gem, co.join, co.flip, co.pip); // Allow FlipperMom to access to the ilk Flipper address _flipperMom = DssExecLib.flipperMom(); DssExecLib.authorize(co.flip, _flipperMom); // Disallow Cat to kick auctions in ilk Flipper if(!co.isLiquidatable) { DssExecLib.deauthorize(_flipperMom, co.flip); } if(co.isOSM) { // If pip == OSM // Allow OsmMom to access to the TOKEN OSM DssExecLib.authorize(co.pip, DssExecLib.osmMom()); if (co.whitelistOSM) { // If median is src in OSM // Whitelist OSM to read the Median data (only necessary if it is the first time the token is being added to an ilk) DssExecLib.addReaderToMedianWhitelist(address(OracleLike_1(co.pip).src()), co.pip); } // Whitelist Spotter to read the OSM data (only necessary if it is the first time the token is being added to an ilk) DssExecLib.addReaderToOSMWhitelist(co.pip, DssExecLib.spotter()); // Whitelist End to read the OSM data (only necessary if it is the first time the token is being added to an ilk) DssExecLib.addReaderToOSMWhitelist(co.pip, DssExecLib.end()); // Set TOKEN OSM in the OsmMom for new ilk DssExecLib.allowOSMFreeze(co.pip, co.ilk); } // Increase the global debt ceiling by the ilk ceiling DssExecLib.increaseGlobalDebtCeiling(co.ilkDebtCeiling); // Set the ilk debt ceiling DssExecLib.setIlkDebtCeiling(co.ilk, co.ilkDebtCeiling); // Set the ilk dust DssExecLib.setIlkMinVaultAmount(co.ilk, co.minVaultAmount); // Set the dunk size DssExecLib.setIlkMaxLiquidationAmount(co.ilk, co.maxLiquidationAmount); // Set the ilk liquidation penalty DssExecLib.setIlkLiquidationPenalty(co.ilk, co.liquidationPenalty); // Set the ilk stability fee DssExecLib.setIlkStabilityFee(co.ilk, co.ilkStabilityFee, true); // Set the ilk percentage between bids DssExecLib.setIlkMinAuctionBidIncrease(co.ilk, co.bidIncrease); // Set the ilk time max time between bids DssExecLib.setIlkBidDuration(co.ilk, co.bidDuration); // Set the ilk max auction duration DssExecLib.setIlkAuctionDuration(co.ilk, co.auctionDuration); // Set the ilk min collateralization ratio DssExecLib.setIlkLiquidationRatio(co.ilk, co.liquidationRatio); // Update ilk spot value in Vat DssExecLib.updateCollateralPrice(co.ilk); } } ////// lib/dss-exec-lib/src/DssExec.sol // // DssExec.sol -- MakerDAO Executive Spell Template // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.11; */ interface PauseAbstract { function delay() external view returns (uint256); function plot(address, bytes32, bytes calldata, uint256) external; function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory); } interface Changelog { function getAddress(bytes32) external view returns (address); } interface SpellAction { function officeHours() external view returns (bool); } contract DssExec { Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F); uint256 public eta; bytes public sig; bool public done; bytes32 immutable public tag; address immutable public action; uint256 immutable public expiration; PauseAbstract immutable public pause; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" string public description; function officeHours() external view returns (bool) { return SpellAction(action).officeHours(); } function nextCastTime() external view returns (uint256 castTime) { require(eta != 0, "DssExec/spell-not-scheduled"); castTime = block.timestamp > eta ? block.timestamp : eta; // Any day at XX:YY if (SpellAction(action).officeHours()) { uint256 day = (castTime / 1 days + 3) % 7; uint256 hour = castTime / 1 hours % 24; uint256 minute = castTime / 1 minutes % 60; uint256 second = castTime % 60; if (day >= 5) { castTime += (6 - day) * 1 days; // Go to Sunday XX:YY castTime += (24 - hour + 14) * 1 hours; // Go to 14:YY UTC Monday castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } else { if (hour >= 21) { if (day == 4) castTime += 2 days; // If Friday, fast forward to Sunday XX:YY castTime += (24 - hour + 14) * 1 hours; // Go to 14:YY UTC next day castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } else if (hour < 14) { castTime += (14 - hour) * 1 hours; // Go to 14:YY UTC same day castTime -= minute * 1 minutes + second; // Go to 14:00 UTC } } } } // @param _description A string description of the spell // @param _expiration The timestamp this spell will expire. (Ex. now + 30 days) // @param _spellAction The address of the spell action constructor(string memory _description, uint256 _expiration, address _spellAction) public { pause = PauseAbstract(log.getAddress("MCD_PAUSE")); description = _description; expiration = _expiration; action = _spellAction; sig = abi.encodeWithSignature("execute()"); bytes32 _tag; // Required for assembly access address _action = _spellAction; // Required for assembly access assembly { _tag := extcodehash(_action) } tag = _tag; } function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + PauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } } ////// src/DssSpell.sol // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity 0.6.12; */ /* import "dss-exec-lib/DssExec.sol"; */ /* import "dss-exec-lib/DssAction.sol"; */ // https://github.com/makerdao/ilk-registry/blob/master/src/IlkRegistry.sol interface IlkRegistryLike { function list() external view returns (bytes32[] memory); } contract DssSpellAction is DssAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/e0a37c7b58a98566ba637793a804179b4666b4c7/governance/votes/Executive%20vote%20-%20March%2019%2C%202021.md -q -O - 2>/dev/null)" string public constant description = "2021-03-19 MakerDAO Executive Spell | Hash: 0xa7979ce287cd7df9ecbf25251f2b41a52c27a47567721d7c5ddfc6f85885d4d7"; // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // // A table of rates can be found at // https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW // uint256 constant MILLION = 10**6; uint256 constant BILLION = 10**9; // Disable Office Hours function officeHours() public override returns (bool) { return false; } function actions() public override { bytes32[] memory ilks = IlkRegistryLike(DssExecLib.reg()).list(); // Increase Dust Parameter for most Ilks // // Loop over all ilks for (uint256 i = 0; i < ilks.length; i++) { // skip the rest of the loop for the following ilks: // // RWA001-A ilk is not included in the ilk registry if (ilks[i] == "ETH-B" || ilks[i] == "PSM-USDC-A" ) { continue; } // Increase Dust Paramater // DssExecLib.setIlkMinVaultAmount(ilks[i], 5000); } // Increase Debt Ceiling DssExecLib.setIlkAutoLineDebtCeiling("ETH-A", 15 * BILLION); DssExecLib.setIlkAutoLineDebtCeiling("WBTC-A", 750 * MILLION); } } contract DssSpell is DssExec { DssSpellAction internal action_ = new DssSpellAction(); constructor() DssExec(action_.description(), block.timestamp + 30 days, address(action_)) public {} }
/ Constants /// Math Functions //
function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); }
10,172,899
//Address: 0x22a1ed2f03206be150ede2a7ffa909f7be033d99 //Contract name: AuthenticationManager //Balance: 0 Ether //Verification Date: 10/24/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } /* The authentication manager details user accounts that have access to certain priviledges and keeps a permanent ledger of who has and has had these rights. */ contract AuthenticationManager { /* Map addresses to admins */ mapping (address => bool) adminAddresses; /* Map addresses to account readers */ mapping (address => bool) accountReaderAddresses; /* Details of all admins that have ever existed */ address[] adminAudit; /* Details of all account readers that have ever existed */ address[] accountReaderAudit; /* Fired whenever an admin is added to the contract. */ event AdminAdded(address addedBy, address admin); /* Fired whenever an admin is removed from the contract. */ event AdminRemoved(address removedBy, address admin); /* Fired whenever an account-reader contract is added. */ event AccountReaderAdded(address addedBy, address account); /* Fired whenever an account-reader contract is removed. */ event AccountReaderRemoved(address removedBy, address account); /* When this contract is first setup we use the creator as the first admin */ function AuthenticationManager() { /* Set the first admin to be the person creating the contract */ adminAddresses[msg.sender] = true; AdminAdded(0, msg.sender); adminAudit.length++; adminAudit[adminAudit.length - 1] = msg.sender; } /* Gets whether or not the specified address is currently an admin */ function isCurrentAdmin(address _address) constant returns (bool) { return adminAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAdmin(address _address) constant returns (bool) { for (uint256 i = 0; i < adminAudit.length; i++) if (adminAudit[i] == _address) return true; return false; } /* Gets whether or not the specified address is currently an account reader */ function isCurrentAccountReader(address _address) constant returns (bool) { return accountReaderAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAccountReader(address _address) constant returns (bool) { for (uint256 i = 0; i < accountReaderAudit.length; i++) if (accountReaderAudit[i] == _address) return true; return false; } /* Adds a user to our list of admins */ function addAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already admin if (adminAddresses[_address]) throw; // Add the user adminAddresses[_address] = true; AdminAdded(msg.sender, _address); adminAudit.length++; adminAudit[adminAudit.length - 1] = _address; } /* Removes a user from our list of admins but keeps them in the history audit */ function removeAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; /* Don't allow removal of self */ if (_address == msg.sender) throw; // Fail if this account is already non-admin if (!adminAddresses[_address]) throw; /* Remove this admin user */ adminAddresses[_address] = false; AdminRemoved(msg.sender, _address); } /* Adds a user/contract to our list of account readers */ function addAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already in the list if (accountReaderAddresses[_address]) throw; // Add the user accountReaderAddresses[_address] = true; AccountReaderAdded(msg.sender, _address); accountReaderAudit.length++; accountReaderAudit[adminAudit.length - 1] = _address; } /* Removes a user/contracts from our list of account readers but keeps them in the history audit */ function removeAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already not in the list if (!accountReaderAddresses[_address]) throw; /* Remove this admin user */ accountReaderAddresses[_address] = false; AccountReaderRemoved(msg.sender, _address); } } /* The XWIN Token itself is a simple extension of the ERC20 that allows for granting other XWIN Token contracts special rights to act on behalf of all transfers. */ contract XWinToken { using SafeMath for uint256; /* Map all our our balances for issued tokens */ mapping (address => uint256) balances; /* Map between users and their approval addresses and amounts */ mapping(address => mapping (address => uint256)) allowed; /* List of all token holders */ address[] allTokenHolders; /* The name of the contract */ string public name; /* The symbol for the contract */ string public symbol; /* How many DPs are in use in this contract */ uint8 public decimals; /* Defines the current supply of the token in its own units */ uint256 totalSupplyAmount = 0; /* Defines the address of the ICO contract which is the only contract permitted to mint tokens. */ address public icoContractAddress; /* Defines whether or not the fund is closed. */ bool public isClosed; /* Defines the contract handling the ICO phase. */ IcoPhaseManagement icoPhaseManagement; /* Defines the admin contract we interface with for credentails. */ AuthenticationManager authenticationManager; /* Fired when the fund is eventually closed. */ event FundClosed(); /* Our transfer event to fire whenever we shift SMRT around */ event Transfer(address indexed from, address indexed to, uint256 value); /* Our approval event when one user approves another to control */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /* Create a new instance of this fund with links to other contracts that are required. */ function XWinToken(address _icoContractAddress, address _authenticationManagerAddress) { // Setup defaults name = "XWin CryptoBet"; symbol = "XWIN"; decimals = 8; /* Setup access to our other contracts and validate their versions */ icoPhaseManagement = IcoPhaseManagement(_icoContractAddress); authenticationManager = AuthenticationManager(_authenticationManagerAddress); /* Store our special addresses */ icoContractAddress = _icoContractAddress; } modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /* This modifier allows a method to only be called by account readers */ modifier accountReaderOnly { if (!authenticationManager.isCurrentAccountReader(msg.sender)) throw; _; } modifier fundSendablePhase { // If it's in ICO phase, forbid it //if (icoPhaseManagement.icoPhase()) // throw; // If it's abandoned, forbid it if (icoPhaseManagement.icoAbandoned()) throw; // We're good, funds can now be transferred _; } /* Transfer funds between two addresses that are not the current msg.sender - this requires approval to have been set separately and follows standard ERC20 guidelines */ function transferFrom(address _from, address _to, uint256 _amount) fundSendablePhase onlyPayloadSize(3) returns (bool) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]) { bool isNew = balances[_to] == 0; balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); if (isNew) tokenOwnerAdd(_to); if (balances[_from] == 0) tokenOwnerRemove(_from); Transfer(_from, _to, _amount); return true; } return false; } /* Returns the total number of holders of this currency. */ function tokenHolderCount() constant returns (uint256) { return allTokenHolders.length; } /* Gets the token holder at the specified index. */ function tokenHolder(uint256 _index) constant returns (address) { return allTokenHolders[_index]; } /* Adds an approval for the specified account to spend money of the message sender up to the defined limit */ function approve(address _spender, uint256 _amount) fundSendablePhase onlyPayloadSize(2) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /* Gets the current allowance that has been approved for the specified spender of the owner address */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* Gets the total supply available of this token */ function totalSupply() constant returns (uint256) { return totalSupplyAmount; } /* Gets the balance of a specified account */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /* Transfer the balance from owner's account to another account */ function transfer(address _to, uint256 _amount) fundSendablePhase onlyPayloadSize(2) returns (bool) { /* Check if sender has balance and for overflows */ if (balances[msg.sender] < _amount || balances[_to].add(_amount) < balances[_to]) return false; /* Do a check to see if they are new, if so we'll want to add it to our array */ bool isRecipientNew = balances[_to] == 0; /* Add and subtract new balances */ balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); /* Consolidate arrays if they are new or if sender now has empty balance */ if (isRecipientNew) tokenOwnerAdd(_to); if (balances[msg.sender] == 0) tokenOwnerRemove(msg.sender); /* Fire notification event */ Transfer(msg.sender, _to, _amount); return true; } /* If the specified address is not in our owner list, add them - this can be called by descendents to ensure the database is kept up to date. */ function tokenOwnerAdd(address _addr) internal { /* First check if they already exist */ uint256 tokenHolderCount = allTokenHolders.length; for (uint256 i = 0; i < tokenHolderCount; i++) if (allTokenHolders[i] == _addr) /* Already found so we can abort now */ return; /* They don't seem to exist, so let's add them */ allTokenHolders.length++; allTokenHolders[allTokenHolders.length - 1] = _addr; } /* If the specified address is in our owner list, remove them - this can be called by descendents to ensure the database is kept up to date. */ function tokenOwnerRemove(address _addr) internal { /* Find out where in our array they are */ uint256 tokenHolderCount = allTokenHolders.length; uint256 foundIndex = 0; bool found = false; uint256 i; for (i = 0; i < tokenHolderCount; i++) if (allTokenHolders[i] == _addr) { foundIndex = i; found = true; break; } /* If we didn't find them just return */ if (!found) return; /* We now need to shuffle down the array */ for (i = foundIndex; i < tokenHolderCount - 1; i++) allTokenHolders[i] = allTokenHolders[i + 1]; allTokenHolders.length--; } /* Mint new tokens - this can only be done by special callers (i.e. the ICO management) during the ICO phase. */ function mintTokens(address _address, uint256 _amount) onlyPayloadSize(2) { /* Ensure we are the ICO contract calling */ if (msg.sender != icoContractAddress || !icoPhaseManagement.icoPhase()) throw; /* Mint the tokens for the new address*/ bool isNew = balances[_address] == 0; totalSupplyAmount = totalSupplyAmount.add(_amount); balances[_address] = balances[_address].add(_amount); if (isNew) tokenOwnerAdd(_address); Transfer(0, _address, _amount); } } contract IcoPhaseManagement { using SafeMath for uint256; /* Defines whether or not we are in the ICO phase */ bool public icoPhase = true; /* Defines whether or not the ICO has been abandoned */ bool public icoAbandoned = false; /* Defines whether or not the XWIN Token contract address has yet been set. */ bool xwinContractDefined = false; /* Defines the sale price during ICO */ uint256 public icoUnitPrice = 3 finney; /* Main wallet for collecting ethers*/ address mainWallet="0x20ce46Bce85BFf0CA13b02401164D96B3806f56e"; // contract manager address address manager = "0xE3ff0BA0C6E7673f46C7c94A5155b4CA84a5bE0C"; /* Wallets wor reserved tokens */ address reservedWallet1 = "0x43Ceb8b8f755518e325898d95F3912aF16b6110C"; address reservedWallet2 = "0x11F386d6c7950369E8Da56F401d1727cf131816D"; // flag - reserved tokens already distributed (can be distributed only once) bool public reservedTokensDistributed; /* If an ICO is abandoned and some withdrawals fail then this map allows people to request withdrawal of locked-in ether. */ mapping(address => uint256) public abandonedIcoBalances; /* Defines our interface to the XWIN Token contract. */ XWinToken xWinToken; /* Defines the admin contract we interface with for credentails. */ AuthenticationManager authenticationManager; /* Defines the time that the ICO starts. */ uint256 public icoStartTime; /* Defines the time that the ICO ends. */ uint256 public icoEndTime; /* Defines our event fired when the ICO is closed */ event IcoClosed(); /* Defines our event fired if the ICO is abandoned */ event IcoAbandoned(string details); /* Ensures that once the ICO is over this contract cannot be used until the point it is destructed. */ modifier onlyDuringIco { bool contractValid = xwinContractDefined && !xWinToken.isClosed(); if (!contractValid || (!icoPhase && !icoAbandoned)) throw; _; } /* This code can be executed only after ICO */ modifier onlyAfterIco { if ( icoEndTime > now) throw; _; } /* This modifier allows a method to only be called by current admins */ modifier adminOnly { if (!authenticationManager.isCurrentAdmin(msg.sender)) throw; _; } modifier managerOnly { require (msg.sender==manager); _; } /* Create the ICO phase managerment and define the address of the main XWIN Token contract. */ function IcoPhaseManagement(address _authenticationManagerAddress) { /* A basic sanity check */ icoStartTime = now; icoEndTime = 1517270400; /* Setup access to our other contracts and validate their versions */ authenticationManager = AuthenticationManager(_authenticationManagerAddress); reservedTokensDistributed = false; } /* Set the XWIN Token contract address as a one-time operation. This happens after all the contracts are created and no other functionality can be used until this is set. */ function setXWinContractAddress(address _xwinContractAddress) adminOnly { /* This can only happen once in the lifetime of this contract */ if (xwinContractDefined) throw; /* Setup access to our other contracts and validate their versions */ xWinToken = XWinToken(_xwinContractAddress); xwinContractDefined = true; } function setTokenPrice(uint newPriceInWei) managerOnly { icoUnitPrice = newPriceInWei; } /* Close the ICO phase and transition to execution phase */ function close() managerOnly onlyDuringIco { // Forbid closing contract before the end of ICO if (now <= icoEndTime) throw; // Close the ICO icoPhase = false; IcoClosed(); // Withdraw funds to the caller // if (!msg.sender.send(this.balance)) // throw; } /* Sending reserved tokens (20% from all tokens was reserved in preICO) */ function distributeReservedTokens() managerOnly onlyAfterIco { require (!reservedTokensDistributed); uint extraTwentyPercents = xWinToken.totalSupply().div(4); xWinToken.mintTokens(reservedWallet1,extraTwentyPercents.div(2)); xWinToken.mintTokens(reservedWallet2,extraTwentyPercents.div(2)); reservedTokensDistributed = true; } /* Handle receiving ether in ICO phase - we work out how much the user has bought, allocate a suitable balance and send their change */ function () onlyDuringIco payable { // Forbid funding outside of ICO if (now < icoStartTime || now > icoEndTime) throw; /* Determine how much they've actually purhcased and any ether change */ //uint256 tokensPurchased = msg.value.div(icoUnitPrice); //uint256 purchaseTotalPrice = tokensPurchased * icoUnitPrice; //uint256 change = msg.value.sub(purchaseTotalPrice); /* Increase their new balance if they actually purchased any */ //if (tokensPurchased > 0) xWinToken.mintTokens(msg.sender, msg.value.mul(100000000).div(icoUnitPrice)); mainWallet.send(msg.value); /* Send change back to recipient */ /*if (change > 0 && !msg.sender.send(change)) throw;*/ } } contract DividendManager { using SafeMath for uint256; /* Our handle to the XWIN Token contract. */ XWinToken xwinContract; /* Handle payments we couldn't make. */ mapping (address => uint256) public dividends; /* Indicates a payment is now available to a shareholder */ event PaymentAvailable(address addr, uint256 amount); /* Indicates a dividend payment was made. */ event DividendPayment(uint256 paymentPerShare, uint256 timestamp); /* Create our contract with references to other contracts as required. */ function DividendManager(address _xwinContractAddress) { /* Setup access to our other contracts and validate their versions */ xwinContract = XWinToken(_xwinContractAddress); } /* Makes a dividend payment - we make it available to all senders then send the change back to the caller. We don't actually send the payments to everyone to reduce gas cost and also to prevent potentially getting into a situation where we have recipients throwing causing dividend failures and having to consolidate their dividends in a separate process. */ function () payable { if (xwinContract.isClosed()) throw; /* Determine how much to pay each shareholder. */ uint256 validSupply = xwinContract.totalSupply(); uint256 paymentPerShare = msg.value.div(validSupply); if (paymentPerShare == 0) throw; /* Enum all accounts and send them payment */ uint256 totalPaidOut = 0; for (uint256 i = 0; i < xwinContract.tokenHolderCount(); i++) { address addr = xwinContract.tokenHolder(i); uint256 dividend = paymentPerShare * xwinContract.balanceOf(addr); dividends[addr] = dividends[addr].add(dividend); PaymentAvailable(addr, dividend); totalPaidOut = totalPaidOut.add(dividend); } // Attempt to send change /*uint256 remainder = msg.value.sub(totalPaidOut); if (remainder > 0 && !msg.sender.send(remainder)) { dividends[msg.sender] = dividends[msg.sender].add(remainder); PaymentAvailable(msg.sender, remainder); }*/ /* Audit this */ DividendPayment(paymentPerShare, now); } /* Allows a user to request a withdrawal of their dividend in full. */ function withdrawDividend() { // Ensure we have dividends available if (dividends[msg.sender] == 0) throw; // Determine how much we're sending and reset the count uint256 dividend = dividends[msg.sender]; dividends[msg.sender] = 0; // Attempt to withdraw if (!msg.sender.send(dividend)) throw; } } //interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } /** * The shareholder association contract */ contract XWinAssociation { address public manager = "0xE3ff0BA0C6E7673f46C7c94A5155b4CA84a5bE0C"; uint public changeManagerQuorum = 80; // in % of tokens uint public debatingPeriod = 3 days; Proposal[] public proposals; uint public numProposals; XWinToken public sharesTokenAddress; event ProposalAdded(uint proposalID, address newManager, string description); event Voted(uint proposalID, bool position, address voter); event ProposalTallied(uint proposalID, uint result,bool active); event ChangeOfRules(uint newMinimumQuorum, uint newDebatingPeriodInMinutes, address newSharesTokenAddress); struct Proposal { address newManager; string description; uint votingDeadline; bool executed; bool proposalPassed; uint numberOfVotes; bytes32 proposalHash; Vote[] votes; mapping (address => bool) voted; } struct Vote { bool inSupport; address voter; } // Modifier that allows only shareholders to vote and create new proposals modifier onlyShareholders { require(sharesTokenAddress.balanceOf(msg.sender) > 0); _; } // Modifier that allows only manager modifier onlyManager { require(msg.sender == manager); _; } /** * Constructor function */ function XWinAssociation(address _xwinContractAddress) { sharesTokenAddress = XWinToken(_xwinContractAddress); } // change debating period by manager function changeVoteRules (uint debatingPeriodInDays) onlyManager { debatingPeriod = debatingPeriodInDays * 1 days; } // transfer ethers from contract account function transferEthers(address receiver, uint valueInWei) onlyManager { uint value = valueInWei; require ( this.balance > value); receiver.send(value); } function () payable { } /** * Add Proposal */ function newProposal( address newManager, string managerDescription ) onlyShareholders returns (uint proposalID) { proposalID = proposals.length++; Proposal storage p = proposals[proposalID]; p.newManager = newManager; p.description = managerDescription; p.proposalHash = sha3(newManager); p.votingDeadline = now + debatingPeriod; p.executed = false; p.proposalPassed = false; p.numberOfVotes = 0; ProposalAdded(proposalID, newManager, managerDescription); numProposals = proposalID+1; return proposalID; } /** * Check if a proposal code matches */ function checkProposalCode( uint proposalNumber, address newManager ) constant returns (bool codeChecksOut) { Proposal storage p = proposals[proposalNumber]; return p.proposalHash == sha3(newManager); } /** * Log a vote for a proposal * * Vote `supportsProposal? in support of : against` proposal #`proposalNumber` * * @param proposalNumber number of proposal * @param supportsProposal either in favor or against it */ function vote( uint proposalNumber, bool supportsProposal ) onlyShareholders returns (uint voteID) { Proposal storage p = proposals[proposalNumber]; require(p.voted[msg.sender] != true); voteID = p.votes.length++; p.votes[voteID] = Vote({inSupport: supportsProposal, voter: msg.sender}); p.voted[msg.sender] = true; p.numberOfVotes = voteID +1; Voted(proposalNumber, supportsProposal, msg.sender); return voteID; } /** * Finish vote */ function executeProposal(uint proposalNumber, address newManager) { Proposal storage p = proposals[proposalNumber]; require(now > p.votingDeadline // If it is past the voting deadline && !p.executed // and it has not already been executed && p.proposalHash == sha3(newManager)); // and the supplied code matches the proposal... // ...then tally the results uint yea = 0; for (uint i = 0; i < p.votes.length; ++i) { Vote storage v = p.votes[i]; uint voteWeight = sharesTokenAddress.balanceOf(v.voter); if (v.inSupport) yea += voteWeight; } if ( yea > changeManagerQuorum * 10**sharesTokenAddress.decimals() ) { // Proposal passed; execute the transaction manager = newManager; p.executed = true; p.proposalPassed = true; } // Fire Events ProposalTallied(proposalNumber, yea , p.proposalPassed); } } contract XWinBet { using SafeMath for uint256; event BetAdded(uint betId, address bettor, uint value, uint rate, uint deadline); event BetExecuted(uint betId, address bettor, uint winValue); event FoundsTransferd(address dao, uint value); XWinAssociation dao; // address of XWin Association contract uint public numBets; // count of bets uint public reservedWeis; // reserved weis for actual bets struct Bet { address bettor; uint value; uint rate; // with 3 symbols after point, for example: 1234 = 1.234 uint deadline; bytes32 betHash; bool executed; } Bet[] public bets; // Modifier that allows only manager modifier onlyManager { require(msg.sender == dao.manager()); _; } function XWinBet(address daoContract) { dao = XWinAssociation(daoContract); } function () payable { } function transferEthersToDao(uint valueInEthers) onlyManager { require(this.balance.sub(reservedWeis) >= valueInEthers * 1 ether); dao.transfer(valueInEthers * 1 ether); FoundsTransferd(dao, valueInEthers * 1 ether); } function bet (uint rate, uint timeLimitInMinutes) payable returns (uint betID) { uint reserved = msg.value.mul(rate).div(1000); require ( this.balance > reservedWeis.add(reserved)); reservedWeis = reservedWeis.add(reserved); betID = bets.length++; Bet storage b = bets[betID]; b.bettor = msg.sender; b.value = msg.value; b.rate = rate; b.deadline = now + timeLimitInMinutes * 1 minutes; b.betHash = sha3(betID,msg.sender,msg.value,rate,b.deadline); b.executed = false; BetAdded(betID, msg.sender,msg.value,rate,b.deadline); numBets = betID+1; return betID; } function executeBet (uint betId, bool win) { Bet b = bets[betId]; require (now > b.deadline); require (!b.executed); require (msg.sender == b.bettor); require (sha3(betId,msg.sender,b.value,b.rate,b.deadline)==b.betHash); uint winValue = b.value.mul(b.rate).div(1000); reservedWeis = reservedWeis.sub(winValue); if (win) { msg.sender.transfer(winValue); BetExecuted(betId,msg.sender,winValue); } else { BetExecuted(betId, msg.sender,0); } b.executed = true; } }
Determine how much to pay each shareholder. / Enum all accounts and send them payment / Attempt to send changeuint256 remainder = msg.value.sub(totalPaidOut);
function () payable { if (xwinContract.isClosed()) throw; uint256 validSupply = xwinContract.totalSupply(); uint256 paymentPerShare = msg.value.div(validSupply); if (paymentPerShare == 0) throw; uint256 totalPaidOut = 0; for (uint256 i = 0; i < xwinContract.tokenHolderCount(); i++) { address addr = xwinContract.tokenHolder(i); uint256 dividend = paymentPerShare * xwinContract.balanceOf(addr); dividends[addr] = dividends[addr].add(dividend); PaymentAvailable(addr, dividend); totalPaidOut = totalPaidOut.add(dividend); } if (remainder > 0 && !msg.sender.send(remainder)) { dividends[msg.sender] = dividends[msg.sender].add(remainder); PaymentAvailable(msg.sender, remainder); }*/ }
6,355,916
./partial_match/42/0xb0D299d01bBD2fb20A52E315c768C88C44256d92/sources/ProofOfHumanity.sol
Change the proportion of arbitration fees that must be paid as fee stake by the winner of the previous round. _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points./
function changeWinnerStakeMultiplier(uint _winnerStakeMultiplier) external onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; }
3,440,443
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Forked from Uniswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Tribe { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Tribe"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "TRIBE"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation // solhint-disable-next-line const-name-snakecase uint public totalSupply = 1_000_000_000e18; // 1 billion Tribe /// @notice Address which may mint new tokens address public minter; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Tribe token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Tribe: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Tribe: only the minter can mint"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); uint96 safeSupply = safe96(totalSupply, "Tribe: totalSupply exceeds 96 bits"); totalSupply = add96(safeSupply, amount, "Tribe: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(signatory == owner, "Tribe: unauthorized"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "Tribe: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, 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), "Tribe: invalid signature"); require(nonce == nonces[signatory]++, "Tribe: invalid nonce"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= expiry, "Tribe: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Tribe: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Tribe: cannot transfer from the zero address"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Tribe: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Tribe: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Tribe: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } }
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/ solhint-disable-next-line not-rely-on-time
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), "Tribe: invalid signature"); require(nonce == nonces[signatory]++, "Tribe: invalid nonce"); require(block.timestamp <= expiry, "Tribe: signature expired"); return _delegate(signatory, delegatee); }
6,180,293
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./WhiteRabbitProducerPass.sol"; contract WhiteRabbit is Ownable, ERC1155Holder { using Strings for uint256; using SafeMath for uint256; // The Producer Pass contract used for staking/voting on episodes WhiteRabbitProducerPass private whiteRabbitProducerPass; // The total number of episodes that make up the film uint256 private _numberOfEpisodes; // A mapping from episodeId to whether or not voting is enabled mapping(uint256 => bool) public votingEnabledForEpisode; // The address of the White Rabbit token ($WRAB) address public whiteRabbitTokenAddress; // The initial fixed supply of White Rabbit tokens uint256 public tokenInitialFixedSupply; // The wallet addresses of the two artists creating the film address private _artist1Address; address private _artist2Address; // The percentage of White Rabbit tokens that will go to the artists uint256 public artistTokenAllocationPercentage; // The number of White Rabbit tokens to send to each artist per episode uint256 public artistTokenPerEpisodePerArtist; // A mapping from episodeId to a boolean indicating whether or not // White Rabbit tokens have been transferred the artists yet mapping(uint256 => bool) public hasTransferredTokensToArtistForEpisode; // The percentage of White Rabbit tokens that will go to producers (via Producer Pass staking) uint256 public producersTokenAllocationPercentage; // The number of White Rabbit tokens to send to producers per episode uint256 public producerPassTokenAllocationPerEpisode; // The base number of White Rabbit tokens to allocate to producers per episode uint256 public producerPassTokenBaseAllocationPerEpisode; // The number of White Rabbit tokens to allocate to producers who stake early uint256 public producerPassTokenEarlyStakingBonusAllocationPerEpisode; // The number of White Rabbit tokens to allocate to producers who stake for the winning option uint256 public producerPassTokenWinningBonusAllocationPerEpisode; // The percentage of White Rabbit tokens that will go to the platform team uint256 public teamTokenAllocationPercentage; // Whether or not the team has received its share of White Rabbit tokens bool public teamTokenAllocationDistributed; // Event emitted when a Producer Pass is staked to vote for an episode option event ProducerPassStaked( address indexed account, uint256 episodeId, uint256 voteId, uint256 amount, uint256 tokenAmount ); // Event emitted when a Producer Pass is unstaked after voting is complete event ProducerPassUnstaked( address indexed account, uint256 episodeId, uint256 voteId, uint256 tokenAmount ); // The list of episode IDs (e.g. [1, 2, 3, 4]) uint256[] public episodes; // The voting option IDs by episodeId (e.g. 1 => [1, 2]) mapping(uint256 => uint256[]) private _episodeOptions; // The total vote counts for each episode voting option, agnostic of users // _episodeVotesByOptionId[episodeId][voteOptionId] => number of votes mapping(uint256 => mapping(uint256 => uint256)) private _episodeVotesByOptionId; // A mapping from episodeId to the winning vote option // 0 means no winner has been declared yet mapping(uint256 => uint256) public winningVoteOptionByEpisode; // A mapping of how many Producer Passes have been staked per user per episode per option // e.g. _usersStakedEpisodeVotingOptionsCount[address][episodeId][voteOptionId] => number staked // These values will be updated/decremented when Producer Passes are unstaked mapping(address => mapping(uint256 => mapping(uint256 => uint256))) private _usersStakedEpisodeVotingOptionsCount; // A mapping of the *history* how many Producer Passes have been staked per user per episode per option // e.g. _usersStakedEpisodeVotingHistoryCount[address][episodeId][voteOptionId] => number staked // Note: These values DO NOT change after Producer Passes are unstaked mapping(address => mapping(uint256 => mapping(uint256 => uint256))) private _usersStakedEpisodeVotingHistoryCount; // The base URI for episode metadata string private _episodeBaseURI; // The base URI for episode voting option metadata string private _episodeOptionBaseURI; /** * @dev Initializes the contract by setting up the Producer Pass contract to be used */ constructor(address whiteRabbitProducerPassContract) { whiteRabbitProducerPass = WhiteRabbitProducerPass( whiteRabbitProducerPassContract ); } /** * @dev Sets the Producer Pass contract to be used */ function setWhiteRabbitProducerPassContract( address whiteRabbitProducerPassContract ) external onlyOwner { whiteRabbitProducerPass = WhiteRabbitProducerPass( whiteRabbitProducerPassContract ); } /** * @dev Sets the base URI for episode metadata */ function setEpisodeBaseURI(string memory baseURI) external onlyOwner { _episodeBaseURI = baseURI; } /** * @dev Sets the base URI for episode voting option metadata */ function setEpisodeOptionBaseURI(string memory baseURI) external onlyOwner { _episodeOptionBaseURI = baseURI; } /** * @dev Sets the list of episode IDs (e.g. [1, 2, 3, 4]) * * This will be updated every time a new episode is added. */ function setEpisodes(uint256[] calldata _episodes) external onlyOwner { episodes = _episodes; } /** * @dev Sets the voting option IDs for a given episode. * * Requirements: * * - The provided episode ID exists in our list of `episodes` */ function setEpisodeOptions( uint256 episodeId, uint256[] calldata episodeOptionIds ) external onlyOwner { require(episodeId <= episodes.length, "Episode does not exist"); _episodeOptions[episodeId] = episodeOptionIds; } /** * @dev Retrieves the voting option IDs for a given episode. * * Requirements: * * - The provided episode ID exists in our list of `episodes` */ function getEpisodeOptions(uint256 episodeId) public view returns (uint256[] memory) { require(episodeId <= episodes.length, "Episode does not exist"); return _episodeOptions[episodeId]; } /** * @dev Retrieves the number of episodes currently available. */ function getCurrentEpisodeCount() external view returns (uint256) { return episodes.length; } /** * @dev Constructs the metadata URI for a given episode. * * Requirements: * * - The provided episode ID exists in our list of `episodes` */ function episodeURI(uint256 episodeId) public view virtual returns (string memory) { require(episodeId <= episodes.length, "Episode does not exist"); string memory baseURI = episodeBaseURI(); return bytes(baseURI).length > 0 ? string( abi.encodePacked(baseURI, episodeId.toString(), ".json") ) : ""; } /** * @dev Constructs the metadata URI for a given episode voting option. * * Requirements: * * - The provided episode ID exists in our list of `episodes` * - The episode voting option ID is valid */ function episodeOptionURI(uint256 episodeId, uint256 episodeOptionId) public view virtual returns (string memory) { // TODO: DRY up these requirements? ("Episode does not exist", "Invalid voting option") require(episodeId <= episodes.length, "Episode does not exist"); string memory baseURI = episodeOptionBaseURI(); return bytes(baseURI).length > 0 ? string( abi.encodePacked( _episodeOptionBaseURI, episodeId.toString(), "/", episodeOptionId.toString(), ".json" ) ) : ""; } /** * @dev Getter for the `_episodeBaseURI` */ function episodeBaseURI() internal view virtual returns (string memory) { return _episodeBaseURI; } /** * @dev Getter for the `_episodeOptionBaseURI` */ function episodeOptionBaseURI() internal view virtual returns (string memory) { return _episodeOptionBaseURI; } /** * @dev Retrieves the voting results for a given episode's voting option ID * * Requirements: * * - The provided episode ID exists in our list of `episodes` * - Voting is no longer enabled for the given episode * - Voting has completed and a winning option has been declared */ function episodeVotes(uint256 episodeId, uint256 episodeOptionId) public view virtual returns (uint256) { require(episodeId <= episodes.length, "Episode does not exist"); require(!votingEnabledForEpisode[episodeId], "Voting is still enabled"); require( winningVoteOptionByEpisode[episodeId] > 0, "Voting not finished" ); return _episodeVotesByOptionId[episodeId][episodeOptionId]; } /** * @dev Retrieves the number of Producer Passes that the user has staked * for a given episode and voting option at this point in time. * * Note that this number will change after a user has unstaked. * * Requirements: * * - The provided episode ID exists in our list of `episodes` */ function userStakedProducerPassCount( uint256 episodeId, uint256 episodeOptionId ) public view virtual returns (uint256) { require(episodeId <= episodes.length, "Episode does not exist"); return _usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][ episodeOptionId ]; } /** * @dev Retrieves the historical number of Producer Passes that the user * has staked for a given episode and voting option. * * Note that this number will not change as a result of unstaking. * * Requirements: * * - The provided episode ID exists in our list of `episodes` */ function userStakedProducerPassCountHistory( uint256 episodeId, uint256 episodeOptionId ) public view virtual returns (uint256) { require(episodeId <= episodes.length, "Episode does not exist"); return _usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][ episodeOptionId ]; } /** * @dev Stakes Producer Passes for the given episode's voting option ID, * with the ability to specify an `amount`. Staking is used to vote for the option * that the user would like to see producers for the next episode. * * Emits a `ProducerPassStaked` event indicating that the staking was successful, * including the total number of White Rabbit tokens allocated as a result. * * Requirements: * * - The provided episode ID exists in our list of `episodes` * - Voting is enabled for the given episode * - The user is attempting to stake more than zero Producer Passes * - The user has enough Producer Passes to stake * - The episode voting option is valid * - A winning option hasn't been declared yet */ function stakeProducerPass( uint256 episodeId, uint256 voteOptionId, uint256 amount ) public { require(episodeId <= episodes.length, "Episode does not exist"); require(votingEnabledForEpisode[episodeId], "Voting not enabled"); require(amount > 0, "Cannot stake 0"); require( whiteRabbitProducerPass.balanceOf(msg.sender, episodeId) >= amount, "Insufficient pass balance" ); uint256[] memory votingOptionsForThisEpisode = _episodeOptions[ episodeId ]; // vote options should be [1, 2], ID <= length require( votingOptionsForThisEpisode.length >= voteOptionId, "Invalid voting option" ); uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId]; // rely on winningVoteOptionId to determine that this episode is valid for voting on require(winningVoteOptionId == 0, "Winner already declared"); // user's vote count for selected episode & option uint256 userCurrentVoteCount = _usersStakedEpisodeVotingOptionsCount[ msg.sender ][episodeId][voteOptionId]; // Get total vote count of this option user is voting/staking for uint256 currentTotalVoteCount = _episodeVotesByOptionId[episodeId][ voteOptionId ]; // Get total vote count from every option of this episode for bonding curve calculation uint256 totalVotesForEpisode = 0; for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) { uint256 currentVotingOptionId = votingOptionsForThisEpisode[i]; totalVotesForEpisode += _episodeVotesByOptionId[episodeId][ currentVotingOptionId ]; } // calculate token rewards here uint256 tokensAllocated = getTokenAllocationForUserBeforeStaking( episodeId, amount ); uint256 userNewVoteCount = userCurrentVoteCount + amount; _usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][ voteOptionId ] = userNewVoteCount; _usersStakedEpisodeVotingHistoryCount[msg.sender][episodeId][ voteOptionId ] = userNewVoteCount; _episodeVotesByOptionId[episodeId][voteOptionId] = currentTotalVoteCount + amount; // Take custody of producer passes from user whiteRabbitProducerPass.safeTransferFrom( msg.sender, address(this), episodeId, amount, "" ); // Distribute wr tokens to user IERC20(whiteRabbitTokenAddress).transfer(msg.sender, tokensAllocated); emit ProducerPassStaked( msg.sender, episodeId, voteOptionId, amount, tokensAllocated ); } /** * @dev Unstakes Producer Passes for the given episode's voting option ID and * sends White Rabbit tokens to the user's wallet if they staked for the winning side. * * * Emits a `ProducerPassUnstaked` event indicating that the unstaking was successful, * including the total number of White Rabbit tokens allocated as a result. * * Requirements: * * - The provided episode ID exists in our list of `episodes` * - Voting is not enabled for the given episode * - The episode voting option is valid * - A winning option has been declared */ function unstakeProducerPasses(uint256 episodeId, uint256 voteOptionId) public { require(!votingEnabledForEpisode[episodeId], "Voting is still enabled"); uint256 stakedProducerPassCount = _usersStakedEpisodeVotingOptionsCount[ msg.sender ][episodeId][voteOptionId]; require(stakedProducerPassCount > 0, "No producer passes staked"); uint256 winningBonus = getUserWinningBonus(episodeId, voteOptionId) * stakedProducerPassCount; _usersStakedEpisodeVotingOptionsCount[msg.sender][episodeId][ voteOptionId ] = 0; if (winningBonus > 0) { IERC20(whiteRabbitTokenAddress).transfer(msg.sender, winningBonus); } whiteRabbitProducerPass.safeTransferFrom( address(this), msg.sender, episodeId, stakedProducerPassCount, "" ); emit ProducerPassUnstaked( msg.sender, episodeId, voteOptionId, winningBonus ); } /** * @dev Calculates the number of White Rabbit tokens to award the user for unstaking * their Producer Passes for a given episode's voting option ID. * * Requirements: * * - The provided episode ID exists in our list of `episodes` * - Voting is not enabled for the given episode * - The episode voting option is valid * - A winning option has been declared */ function getUserWinningBonus(uint256 episodeId, uint256 episodeOptionId) public view returns (uint256) { uint256 winningVoteOptionId = winningVoteOptionByEpisode[episodeId]; require(winningVoteOptionId > 0, "Voting is not finished"); require(!votingEnabledForEpisode[episodeId], "Voting is still enabled"); bool isWinningOption = winningVoteOptionId == episodeOptionId; uint256 numberOfWinningVotes = _episodeVotesByOptionId[episodeId][ episodeOptionId ]; uint256 winningBonus = 0; if (isWinningOption && numberOfWinningVotes > 0) { winningBonus = producerPassTokenWinningBonusAllocationPerEpisode / numberOfWinningVotes; } return winningBonus; } /** * @dev This method is only for the owner since we want to hide the voting results from the public * until after voting has ended. Users can verify the veracity of this via the `episodeVotes` method * which can be called publicly after voting has finished for an episode. * * Requirements: * * - The provided episode ID exists in our list of `episodes` */ function getTotalVotesForEpisode(uint256 episodeId) external view onlyOwner returns (uint256[] memory) { uint256[] memory votingOptionsForThisEpisode = _episodeOptions[ episodeId ]; uint256[] memory totalVotes = new uint256[]( votingOptionsForThisEpisode.length ); for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) { uint256 currentVotingOptionId = votingOptionsForThisEpisode[i]; uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][ currentVotingOptionId ]; totalVotes[i] = votesForEpisode; } return totalVotes; } /** * @dev Owner method to toggle the voting state of a given episode. * * Requirements: * * - The provided episode ID exists in our list of `episodes` * - The voting state is different than the current state * - A winning option has not yet been declared */ function setVotingEnabledForEpisode(uint256 episodeId, bool enabled) public onlyOwner { require(episodeId <= episodes.length, "Episode does not exist"); require( votingEnabledForEpisode[episodeId] != enabled, "Voting state unchanged" ); // if winner already set, don't allow re-opening of voting if (enabled) { require( winningVoteOptionByEpisode[episodeId] == 0, "Winner for episode already set" ); } votingEnabledForEpisode[episodeId] = enabled; } /** * @dev Sets up the distribution parameters for White Rabbit (WRAB) tokens. * * - We will create fractionalized NFT basket first, which will represent the finished film NFT * - Tokens will be stored on platform and distributed to artists and producers as the film progresses * - Artist distribution happens when new episodes are uploaded * - Producer distribution happens when Producer Passes are staked and unstaked (with a bonus for winning the vote) * * Requirements: * * - The allocation percentages do not exceed 100% */ function startWhiteRabbitShowWithParams( address tokenAddress, address artist1Address, address artist2Address, uint256 numberOfEpisodes, uint256 producersAllocationPercentage, uint256 artistAllocationPercentage, uint256 teamAllocationPercentage ) external onlyOwner { require( (producersAllocationPercentage + artistAllocationPercentage + teamAllocationPercentage) <= 100, "Total percentage exceeds 100" ); whiteRabbitTokenAddress = tokenAddress; tokenInitialFixedSupply = IERC20(whiteRabbitTokenAddress).totalSupply(); _artist1Address = artist1Address; _artist2Address = artist2Address; _numberOfEpisodes = numberOfEpisodes; producersTokenAllocationPercentage = producersAllocationPercentage; artistTokenAllocationPercentage = artistAllocationPercentage; teamTokenAllocationPercentage = teamAllocationPercentage; // If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100 * 2) => 28571 artistTokenPerEpisodePerArtist = (tokenInitialFixedSupply * artistTokenAllocationPercentage) / (_numberOfEpisodes * 100 * 2); // 2 for 2 artists // If total supply is 1000000 and pct is 40 => (1000000 * 40) / (7 * 100) => 57142 producerPassTokenAllocationPerEpisode = (tokenInitialFixedSupply * producersTokenAllocationPercentage) / (_numberOfEpisodes * 100); } /** * @dev Sets the White Rabbit (WRAB) token distrubution for producers. * This distribution is broken into 3 categories: * - Base allocation (every Producer Pass gets the same) * - Early staking bonus (bonding curve distribution where earlier stakers are rewarded more) * - Winning bonus (extra pot split among winning voters) * * Requirements: * * - The allocation percentages do not exceed 100% */ function setProducerPassWhiteRabbitTokensAllocationParameters( uint256 earlyStakingBonus, uint256 winningVoteBonus ) external onlyOwner { require( (earlyStakingBonus + winningVoteBonus) <= 100, "Total percentage exceeds 100" ); uint256 basePercentage = 100 - earlyStakingBonus - winningVoteBonus; producerPassTokenBaseAllocationPerEpisode = (producerPassTokenAllocationPerEpisode * basePercentage) / 100; producerPassTokenEarlyStakingBonusAllocationPerEpisode = (producerPassTokenAllocationPerEpisode * earlyStakingBonus) / 100; producerPassTokenWinningBonusAllocationPerEpisode = (producerPassTokenAllocationPerEpisode * winningVoteBonus) / 100; } /** * @dev Calculates the number of White Rabbit tokens the user would receive if the * provided `amount` of Producer Passes is staked for the given episode. * * Requirements: * * - The provided episode ID exists in our list of `episodes` */ function getTokenAllocationForUserBeforeStaking( uint256 episodeId, uint256 amount ) public view returns (uint256) { ProducerPass memory pass = whiteRabbitProducerPass .getEpisodeToProducerPass(episodeId); uint256 maxSupply = pass.maxSupply; uint256 basePerPass = SafeMath.div( producerPassTokenBaseAllocationPerEpisode, maxSupply ); // Get total vote count from every option of this episode for bonding curve calculation uint256[] memory votingOptionsForThisEpisode = _episodeOptions[ episodeId ]; uint256 totalVotesForEpisode = 0; for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) { uint256 currentVotingOptionId = votingOptionsForThisEpisode[i]; totalVotesForEpisode += _episodeVotesByOptionId[episodeId][ currentVotingOptionId ]; } // Below calculates number of tokens user will receive if staked // using a linear bonding curve where early stakers get more // Y = aX (where X = number of stakers, a = Slope, Y = tokens each staker receives) uint256 maxBonusY = 1000 * ((producerPassTokenEarlyStakingBonusAllocationPerEpisode * 2) / maxSupply); uint256 slope = SafeMath.div(maxBonusY, maxSupply); uint256 y1 = (slope * (maxSupply - totalVotesForEpisode)); uint256 y2 = (slope * (maxSupply - totalVotesForEpisode - amount)); uint256 earlyStakingBonus = (amount * (y1 + y2)) / 2; return basePerPass * amount + earlyStakingBonus / 1000; } function endVotingForEpisode(uint256 episodeId) external onlyOwner { uint256[] memory votingOptionsForThisEpisode = _episodeOptions[ episodeId ]; uint256 winningOptionId = 0; uint256 totalVotesForWinningOption = 0; for (uint256 i = 0; i < votingOptionsForThisEpisode.length; i++) { uint256 currentOptionId = votingOptionsForThisEpisode[i]; uint256 votesForEpisode = _episodeVotesByOptionId[episodeId][ currentOptionId ]; if (votesForEpisode >= totalVotesForWinningOption) { winningOptionId = currentOptionId; totalVotesForWinningOption = votesForEpisode; } } setVotingEnabledForEpisode(episodeId, false); winningVoteOptionByEpisode[episodeId] = winningOptionId; } /** * @dev Manually sets the winning voting option for a given episode. * Only call this method to break a tie among voting options for an episode. * * Requirements: * * - This should only be called for ties */ function endVotingForEpisodeOverride( uint256 episodeId, uint256 winningOptionId ) external onlyOwner { setVotingEnabledForEpisode(episodeId, false); winningVoteOptionByEpisode[episodeId] = winningOptionId; } /** * Token distribution for artists and team */ /** * @dev Sends the artists their allocation of White Rabbit tokens after an episode is launched. * * Requirements: * * - The artists have not yet received their tokens for the given episode */ function sendArtistTokensForEpisode(uint256 episodeId) external onlyOwner { require( !hasTransferredTokensToArtistForEpisode[episodeId], "Artist tokens distributed" ); hasTransferredTokensToArtistForEpisode[episodeId] = true; IERC20(whiteRabbitTokenAddress).transfer( _artist1Address, artistTokenPerEpisodePerArtist ); IERC20(whiteRabbitTokenAddress).transfer( _artist2Address, artistTokenPerEpisodePerArtist ); } /** * @dev Transfers White Rabbit tokens to the team based on the `teamTokenAllocationPercentage` * * Requirements: * * - The tokens have not yet been distributed to the team */ function withdrawTokensForTeamAllocation(address[] calldata teamAddresses) external onlyOwner { require(!teamTokenAllocationDistributed, "Team tokens distributed"); uint256 teamBalancePerMember = (teamTokenAllocationPercentage * tokenInitialFixedSupply) / (100 * teamAddresses.length); for (uint256 i = 0; i < teamAddresses.length; i++) { IERC20(whiteRabbitTokenAddress).transfer( teamAddresses[i], teamBalancePerMember ); } teamTokenAllocationDistributed = true; } /** * @dev Transfers White Rabbit tokens to the team based on the platform allocation * * Requirements: * * - All Episodes finished * - Voting completed */ function withdrawPlatformReserveTokens() external onlyOwner { require(episodes.length == _numberOfEpisodes, "Show not ended"); require( !votingEnabledForEpisode[_numberOfEpisodes], "Last episode still voting" ); uint256 leftOverBalance = IERC20(whiteRabbitTokenAddress).balanceOf( address(this) ); IERC20(whiteRabbitTokenAddress).transfer(msg.sender, leftOverBalance); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Holder.sol) pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { 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; } } // 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/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; struct ProducerPass { uint256 price; uint256 episodeId; uint256 maxSupply; uint256 maxPerWallet; uint256 openMintTimestamp; // unix timestamp in seconds bytes32 merkleRoot; } contract WhiteRabbitProducerPass is ERC1155, ERC1155Supply, Ownable { using Strings for uint256; // The name of the token ("White Rabbit Producer Pass") string public name; // The token symbol ("WRPP") string public symbol; // The wallet addresses of the two artists creating the film address payable private artistAddress1; address payable private artistAddress2; // The wallet addresses of the three developers managing the film address payable private devAddress1; address payable private devAddress2; address payable private devAddress3; // The royalty percentages for the artists and developers uint256 private constant ARTIST_ROYALTY_PERCENTAGE = 60; uint256 private constant DEV_ROYALTY_PERCENTAGE = 40; // A mapping of the number of Producer Passes minted per episodeId per user // userPassesMintedPerTokenId[msg.sender][episodeId] => number of minted passes mapping(address => mapping(uint256 => uint256)) private userPassesMintedPerTokenId; // A mapping from episodeId to its Producer Pass mapping(uint256 => ProducerPass) private episodeToProducerPass; // Event emitted when a Producer Pass is bought event ProducerPassBought( uint256 episodeId, address indexed account, uint256 amount ); /** * @dev Initializes the contract by setting the name and the token symbol */ constructor(string memory baseURI) ERC1155(baseURI) { name = "White Rabbit Producer Pass"; symbol = "WRPP"; } /** * @dev Checks if the provided Merkle Proof is valid for the given root hash. */ function isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) internal view returns (bool) { return MerkleProof.verify( merkleProof, root, keccak256(abi.encodePacked(msg.sender)) ); } /** * @dev Retrieves the Producer Pass for a given episode. */ function getEpisodeToProducerPass(uint256 episodeId) external view returns (ProducerPass memory) { return episodeToProducerPass[episodeId]; } /** * @dev Contracts the metadata URI for the Producer Pass of the given episodeId. * * Requirements: * * - The Producer Pass exists for the given episode */ function uri(uint256 episodeId) public view override returns (string memory) { require( episodeToProducerPass[episodeId].episodeId != 0, "Invalid episode" ); return string( abi.encodePacked( super.uri(episodeId), episodeId.toString(), ".json" ) ); } /** * Owner-only methods */ /** * @dev Sets the base URI for the Producer Pass metadata. */ function setBaseURI(string memory baseURI) external onlyOwner { _setURI(baseURI); } /** * @dev Sets the parameters on the Producer Pass struct for the given episode. */ function setProducerPass( uint256 price, uint256 episodeId, uint256 maxSupply, uint256 maxPerWallet, uint256 openMintTimestamp, bytes32 merkleRoot ) external onlyOwner { episodeToProducerPass[episodeId] = ProducerPass( price, episodeId, maxSupply, maxPerWallet, openMintTimestamp, merkleRoot ); } /** * @dev Withdraws the balance and distributes it to the artists and developers * based on the `ARTIST_ROYALTY_PERCENTAGE` and `DEV_ROYALTY_PERCENTAGE`. */ function withdraw() external onlyOwner { uint256 balance = address(this).balance; uint256 artistBalance = (balance * ARTIST_ROYALTY_PERCENTAGE) / 100; uint256 balancePerArtist = artistBalance / 2; uint256 devBalance = (balance * DEV_ROYALTY_PERCENTAGE) / 100; uint256 balancePerDev = devBalance / 3; bool success; // Transfer artist balances (success, ) = artistAddress1.call{value: balancePerArtist}(""); require(success, "Withdraw unsuccessful"); (success, ) = artistAddress2.call{value: balancePerArtist}(""); require(success, "Withdraw unsuccessful"); // Transfer dev balances (success, ) = devAddress1.call{value: balancePerDev}(""); require(success, "Withdraw unsuccessful"); (success, ) = devAddress2.call{value: balancePerDev}(""); require(success, "Withdraw unsuccessful"); (success, ) = devAddress3.call{value: balancePerDev}(""); require(success, "Withdraw unsuccessful"); } /** * @dev Sets the royalty addresses for the two artists and three developers. */ function setRoyaltyAddresses( address _a1, address _a2, address _d1, address _d2, address _d3 ) external onlyOwner { artistAddress1 = payable(_a1); artistAddress2 = payable(_a2); devAddress1 = payable(_d1); devAddress2 = payable(_d2); devAddress3 = payable(_d3); } /** * @dev Creates a reserve of Producer Passes to set aside for gifting. * * Requirements: * * - There are enough Producer Passes to mint for the given episode * - The supply for the given episode does not exceed the maxSupply of the Producer Pass */ function reserveProducerPassesForGifting( uint256 episodeId, uint256 amountEachAddress, address[] calldata addresses ) public onlyOwner { ProducerPass memory pass = episodeToProducerPass[episodeId]; require(amountEachAddress > 0, "Amount cannot be 0"); require(totalSupply(episodeId) < pass.maxSupply, "No passes to mint"); require( totalSupply(episodeId) + amountEachAddress * addresses.length <= pass.maxSupply, "Cannot mint that many" ); require(addresses.length > 0, "Need addresses"); for (uint256 i = 0; i < addresses.length; i++) { address add = addresses[i]; _mint(add, episodeId, amountEachAddress, ""); } } /** * @dev Mints a set number of Producer Passes for a given episode. * * Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully. * * Requirements: * * - The current time is within the minting window for the given episode * - There are Producer Passes available to mint for the given episode * - The user is not trying to mint more than the maxSupply * - The user is not trying to mint more than the maxPerWallet * - The user has enough ETH for the transaction */ function mintProducerPass(uint256 episodeId, uint256 amount) external payable { ProducerPass memory pass = episodeToProducerPass[episodeId]; require( block.timestamp >= pass.openMintTimestamp, "Mint is not available" ); require(totalSupply(episodeId) < pass.maxSupply, "Sold out"); require( totalSupply(episodeId) + amount <= pass.maxSupply, "Cannot mint that many" ); uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][ episodeId ]; require( totalMintedPasses + amount <= pass.maxPerWallet, "Exceeding maximum per wallet" ); require(msg.value == pass.price * amount, "Not enough eth"); userPassesMintedPerTokenId[msg.sender][episodeId] = totalMintedPasses + amount; _mint(msg.sender, episodeId, amount, ""); emit ProducerPassBought(episodeId, msg.sender, amount); } /** * @dev For those on with early access (on the whitelist), * mints a set number of Producer Passes for a given episode. * * Emits a `ProducerPassBought` event indicating the Producer Pass was minted successfully. * * Requirements: * * - Provides a valid Merkle proof, indicating the user is on the whitelist * - There are Producer Passes available to mint for the given episode * - The user is not trying to mint more than the maxSupply * - The user is not trying to mint more than the maxPerWallet * - The user has enough ETH for the transaction */ function earlyMintProducerPass( uint256 episodeId, uint256 amount, bytes32[] calldata merkleProof ) external payable { ProducerPass memory pass = episodeToProducerPass[episodeId]; require( isValidMerkleProof(merkleProof, pass.merkleRoot), "Not authorized to mint" ); require(totalSupply(episodeId) < pass.maxSupply, "Sold out"); require( totalSupply(episodeId) + amount <= pass.maxSupply, "Cannot mint that many" ); uint256 totalMintedPasses = userPassesMintedPerTokenId[msg.sender][ episodeId ]; require( totalMintedPasses + amount <= pass.maxPerWallet, "Exceeding maximum per wallet" ); require(msg.value == pass.price * amount, "Not enough eth"); userPassesMintedPerTokenId[msg.sender][episodeId] = totalMintedPasses + amount; _mint(msg.sender, episodeId, amount, ""); emit ProducerPassBought(episodeId, msg.sender, amount); } /** * @dev Retrieves the number of Producer Passes a user has minted by episodeId. */ function userPassesMintedByEpisodeId(uint256 episodeId) external view returns (uint256) { return userPassesMintedPerTokenId[msg.sender][episodeId]; } /** * @dev Boilerplate override for `_beforeTokenTransfer` */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol) pragma solidity ^0.8.0; import "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } }
Contracts the metadata URI for the Producer Pass of the given episodeId. Requirements: - The Producer Pass exists for the given episode/
function uri(uint256 episodeId) public view override returns (string memory) { require( episodeToProducerPass[episodeId].episodeId != 0, "Invalid episode" ); return string( abi.encodePacked( super.uri(episodeId), episodeId.toString(), ".json" ) ); }
1,528,306
./partial_match/1/0x9C05dc7c7f6332CBc16Ce1e196Ff6928f3fCe5bF/sources/Platform.sol
The wallet to receive payments here before initiating crowdsale will overwrite old wallet addressemit LogPlatformWallet(_walletAddress);
function setPlatformFundsWallet(address _walletAddress) external onlyOwner { database.setAddress(keccak256(abi.encodePacked("platform.wallet.funds")), _walletAddress); events.registration('Platform funds wallet', _walletAddress); }
3,619,124
./full_match/1/0xBe2E0c770785179210b27d76354B2950EB90b94C/sources/contracts/BLSTokenERC1155.sol
xref:ROOT:erc1155.adocbatch-operations[Batched] variant of {mint}./
function mintBatch( address _to, uint256[] memory _ids, string[] calldata _uri, uint256[] memory _amounts, bytes memory _data ) external virtual { require(hasRole(MINTER_ROLE, _msgSender()), "BLSTokenERC1155: must have minter role to mint"); _mintBatch(_to, _ids, _amounts, _data); for (uint256 i = 0; i < _ids.length; i++) { _setURI(_ids[i], _uri[i]); _setTokenRoyalty(_ids[i], _to, defaultRoyaltyBps); } }
16,483,561
./full_match/42/0xEBD18473513D68E5b463800cDd717b64B542Cd03/sources/browser/doan_antt_nhom2.sol
Vđv đăng ký tham giaNhập vào các tham số sau: Họ tên, năm sinh, đội muốn tham gia, cự ly, thời gian đăng ký
function registerAthletes(string memory _name,uint _yearOfBirth, uint _team, uint _distance, uint _rperiod) public{ athletes.push(Athletes( idnext, _name, _yearOfBirth, _team, _distance, 0, _rperiod,0)); ++idnext; }
16,222,944
pragma solidity 0.8.6; contract AddressesProvider { address public ownerAddress; mapping(uint256 => address) addressMap; mapping(uint256 => string) addressIdMap; uint256 addressesLength; constructor() { ownerAddress = msg.sender; } struct AddressMetadata { string addrId; address addr; } function setAddress(AddressMetadata memory addressMetadata) public { require(msg.sender == ownerAddress, "Caller is not owner"); string memory addressId = addressMetadata.addrId; address addr = addressMetadata.addr; uint256 upsertPosition = addressesLength; int256 addressPosition = addressPositionById(addressId); if (addressPosition >= 0) { upsertPosition = uint256(addressPosition); } else { addressIdMap[upsertPosition] = addressId; addressesLength++; } addressMap[upsertPosition] = addr; } function setAddresses(AddressMetadata[] memory _addressesMetadata) public { require(msg.sender == ownerAddress, "Caller is not owner"); for ( uint256 addressMetadataIdx; addressMetadataIdx < _addressesMetadata.length; addressMetadataIdx++ ) { AddressMetadata memory addressMetadata = _addressesMetadata[ addressMetadataIdx ]; setAddress(addressMetadata); } } function addressPositionById(string memory addressId) public view returns (int256) { for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { string memory currentAddressId = addressIdMap[addressIdx]; if (stringsEqual(addressId, currentAddressId)) { return int256(addressIdx); } } return -1; } function addressById(string memory addressId) external view returns (address) { return addressMap[uint256(addressPositionById(addressId))]; } function addresses() external view returns (address[] memory) { address[] memory _addresses = new address[](addressesLength); for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { _addresses[addressIdx] = addressMap[addressIdx]; } return _addresses; } function addressesIds() external view returns (string[] memory) { string[] memory _addressesIds = new string[](addressesLength); for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { _addressesIds[addressIdx] = addressIdMap[addressIdx]; } return _addressesIds; } function addressesMetadata() external view returns (AddressMetadata[] memory) { AddressMetadata[] memory _addressesMetadata = new AddressMetadata[]( addressesLength ); for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { _addressesMetadata[addressIdx] = AddressMetadata({ addrId: addressIdMap[addressIdx], addr: addressMap[addressIdx] }); } return _addressesMetadata; } function addressesMetadataByIdStartsWith(string memory addressIdSubstring) external view returns (AddressMetadata[] memory) { AddressMetadata[] memory _addressesMetadata = new AddressMetadata[]( addressesLength ); uint256 _addressesLength; for (uint256 addressIdx; addressIdx < addressesLength; addressIdx++) { string memory addressId = addressIdMap[addressIdx]; bool foundMatch = startsWith(addressId, addressIdSubstring); if (foundMatch) { _addressesMetadata[_addressesLength] = AddressMetadata({ addrId: addressIdMap[addressIdx], addr: addressMap[addressIdx] }); _addressesLength++; } } bytes memory encodedAddresses = abi.encode(_addressesMetadata); assembly { mstore(add(encodedAddresses, 0x40), _addressesLength) } AddressMetadata[] memory filteredAddresses = abi.decode( encodedAddresses, (AddressMetadata[]) ); return filteredAddresses; } /** * Allow storage slots to be manually updated by owner */ function updateSlot(bytes32 slot, bytes32 value) external { require(msg.sender == ownerAddress, "Caller is not owner"); assembly { sstore(slot, value) } } /*********** * Utilities ***********/ /** * Search for a needle in a haystack */ function startsWith(string memory haystack, string memory needle) internal pure returns (bool) { return indexOf(needle, haystack) == 0; } /** * Case insensitive string search * * @param needle The string to search for * @param haystack The string to search in * @return Returns -1 if no match is found, otherwise returns the index of the match */ function indexOf(string memory needle, string memory haystack) internal pure returns (int256) { bytes memory _needle = bytes(needle); bytes memory _haystack = bytes(haystack); if (_haystack.length < _needle.length) { return -1; } bool _match; for ( uint256 haystackIdx; haystackIdx < _haystack.length; haystackIdx++ ) { for (uint256 needleIdx; needleIdx < _needle.length; needleIdx++) { uint8 needleChar = uint8(_needle[needleIdx]); if (haystackIdx + needleIdx >= _haystack.length) { return -1; } uint8 haystackChar = uint8(_haystack[haystackIdx + needleIdx]); if (needleChar == haystackChar) { _match = true; if (needleIdx == _needle.length - 1) { return int256(haystackIdx); } } else { _match = false; break; } } } return -1; } /** * Check to see if two strings are exactly equal * @dev Only valid for strings up to 32 characters */ function stringsEqual(string memory input1, string memory input2) internal pure returns (bool) { bytes32 input1Bytes32; bytes32 input2Bytes32; assembly { input1Bytes32 := mload(add(input1, 32)) input2Bytes32 := mload(add(input2, 32)) } return input1Bytes32 == input2Bytes32; } }
Case insensitive string search needle The string to search for haystack The string to search in return Returns -1 if no match is found, otherwise returns the index of the match/
function indexOf(string memory needle, string memory haystack) internal pure returns (int256) { bytes memory _needle = bytes(needle); bytes memory _haystack = bytes(haystack); if (_haystack.length < _needle.length) { return -1; } bool _match; for ( uint256 haystackIdx; haystackIdx < _haystack.length; haystackIdx++ ) { for (uint256 needleIdx; needleIdx < _needle.length; needleIdx++) { uint8 needleChar = uint8(_needle[needleIdx]); if (haystackIdx + needleIdx >= _haystack.length) { return -1; } uint8 haystackChar = uint8(_haystack[haystackIdx + needleIdx]); if (needleChar == haystackChar) { _match = true; if (needleIdx == _needle.length - 1) { return int256(haystackIdx); } _match = false; break; } } } return -1; }
12,580,827
pragma solidity ^0.4.24; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // // received pot swap deposit // event onPotSwapDeposit // ( // uint256 roundID, // uint256 amountAddedToPot // ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; //god of game address constant private god = 0xe1B35fEBaB9Ff6da5b29C3A7A44eef06cD86B0f9; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x99a1cac09c1c07037c3c7b821ce4ddc4a9fe564d); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FM3D More Award~"; string constant public symbol = "F3D"; uint256 private rndExtra_ = 10 minutes; // length of the very first ICO uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 8 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation percentages fees_[0] = F3Ddatasets.TeamFee(40,0); //40% to gen, 20% to pot, 35% to aff, 5% to com, 0% to air drop pot fees_[1] = F3Ddatasets.TeamFee(40,0); //40% to gen, 20% to pot, 35% to aff, 5% to com, 0% to air drop pot fees_[2] = F3Ddatasets.TeamFee(40,0); //40% to gen, 20% to pot, 35% to aff, 5% to com, 0% to air drop pot fees_[3] = F3Ddatasets.TeamFee(40,0); //40% to gen, 20% to pot, 35% to aff, 5% to com, 0% to air drop pot potSplit_[0] = F3Ddatasets.PotSplit(95,0); //95% to winner, 5% to next round, 0% to com potSplit_[1] = F3Ddatasets.PotSplit(95,0); //95% to winner, 5% to next round, 0% to com potSplit_[2] = F3Ddatasets.PotSplit(95,0); //95% to winner, 5% to next round, 0% to com potSplit_[3] = F3Ddatasets.PotSplit(95,0); //95% to winner, 5% to next round, 0% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev determine player's affid * @param _pID the ID/address/name of the player who gets the affiliate fee * @param _inAffID what team is the player playing for? * @return _affID player's real affid */ function determineAffID(uint256 _pID, uint256 _inAffID) private returns(uint256){ if(plyr_[_pID].laff == 0){ // update last affiliate plyr_[_pID].laff = _inAffID; } return plyr_[_pID].laff; } /** * @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) { _affCode = determineAffID(_pID,_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) { _affID = determineAffID(_pID,_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) { _affID = determineAffID(_pID,_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) { _affCode = determineAffID(_pID,_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) { _affID = determineAffID(_pID,_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) { _affID = determineAffID(_pID,_affID); } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 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(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(95)) / 100; uint256 _com = 0; //(_pot / 10); uint256 _gen = 0; //(_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = 0; //(_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(Jekyll_Island_Inc).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; // } // // community rewards send to god // address(god).transfer(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // // send share for p3d to divies // if (_p3d > 0) // address(god).transfer(_p3d); //Divies.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 5% out to community rewards uint256 _com = _eth / 20; uint256 _p3d; // if (!address(Jekyll_Island_Inc).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)(); //community rewards and FoMo3D short all send to god address(god).transfer(_com); // distribute share to affiliate 35% uint256 _aff = _eth.mul(35) / (100); // 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 // Divies.deposit.value(_p3d)(); // // set up event data // _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); // p3d send to god address(god).transfer(_p3d); } return(_eventData_); } // this function had a bug~ // 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 0% into airdrop pot uint256 _air = 0; // (_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.mul(20)) / 100; //_eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate // require( // msg.sender == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C || // msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D || // msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 || // msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C || // msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3, // "only team just can activate" // ); require(msg.sender == god, "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 == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C || // msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D || // msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 || // msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C || // msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3, // "only team just can activate" // ); // // make sure that it HASNT yet been linked. // require(address(otherF3D_) == address(0), "silly dev, you already did that"); // // set up other fomo3d (fast or long) for pot swap // otherF3D_ = otherFoMo3D(_otherF3D); // } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== // interface otherFoMo3D { // function potSwap() external payable; // } interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } // interface DiviesInterface { // function deposit() external payable; // } // interface JIincForwarderInterface { // 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 PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given get affiliate ID from aff Code if affID is not the same as previously stored
function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { _affID = determineAffID(_pID,_affID); } } }
9,851,753
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./ZombieAttack.sol"; //the zo contract ZombieOwnership is ZombieAttack, ERC721 { //use safemath using SafeMath for uint256; using SafeMath32 for uint32; using SafeMath16 for uint16; // //mapping mapping (uint => address) zombieApprovals; /**************************************** * ERC721 FUNCTION LOGIC DEFINED HERE * ****************************************/ function balanceOf(address _owner) external override view returns (uint256) { // 1. Return the number of zombies `_owner` has here return ownerZombieCount[_owner]; } function ownerOf(uint256 _tokenId) external override view returns (address) { // 2. Return the owner of `_tokenId` here return zombieToOwner[_tokenId]; } function transferFrom(address _from, address _to, uint256 _tokenId) external override payable { require (zombieToOwner[_tokenId] == msg.sender || zombieApprovals[_tokenId] == msg.sender); INTERNAL_transfer(_from, _to, _tokenId); } function approve(address _approved, uint256 _tokenId) external override payable ownerOfZombie(_tokenId) { zombieApprovals[_tokenId] = _approved; //raise the event from ERC721 emit Approval(msg.sender, _approved, _tokenId); } /*********************************** * PRIVATE FUNCTION DEFINED HERE * ***********************************/ /** * INTERNAL_transfer : private function that will handle transfer tokenId from address to address * @param _from : from address * @param _to : to address * @param _tokenId : id of the token will be tranfered */ function INTERNAL_transfer(address _from, address _to, uint256 _tokenId) private { //number of zombie of to increase ownerZombieCount[_to] = ownerZombieCount[_to].add(1); //number of zombie of from decrease ownerZombieCount[_from] = ownerZombieCount[_from].sub(1); //change owner of the zombie id zombieToOwner[_tokenId] = _to; //raise the event from ERC721 emit Transfer(_from, _to, _tokenId); } }
2. Return the owner of `_tokenId` here
function ownerOf(uint256 _tokenId) external override view returns (address) { return zombieToOwner[_tokenId]; }
12,770,456
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ============ Internal Imports ============ import {Home} from "../Home.sol"; import {Version0} from "../Version0.sol"; import {XAppConnectionManager, TypeCasts} from "../XAppConnectionManager.sol"; import {IMessageRecipient} from "../../interfaces/IMessageRecipient.sol"; import {GovernanceMessage} from "./GovernanceMessage.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; contract GovernanceRouter is Version0, Initializable, IMessageRecipient { // ============ Libraries ============ using SafeMath for uint256; using TypedMemView for bytes; using TypedMemView for bytes29; using GovernanceMessage for bytes29; // ============ Immutables ============ uint32 public immutable localDomain; // number of seconds before recovery can be activated uint256 public immutable recoveryTimelock; // ============ Public Storage ============ // timestamp when recovery timelock expires; 0 if timelock has not been initiated uint256 public recoveryActiveAt; // the address of the recovery manager multisig address public recoveryManager; // the local entity empowered to call governance functions, set to 0x0 on non-Governor chains address public governor; // domain of Governor chain -- for accepting incoming messages from Governor uint32 public governorDomain; // xAppConnectionManager contract which stores Replica addresses XAppConnectionManager public xAppConnectionManager; // domain -> remote GovernanceRouter contract address mapping(uint32 => bytes32) public routers; // array of all domains with registered GovernanceRouter uint32[] public domains; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[43] private __GAP; // ============ Events ============ /** * @notice Emitted a remote GovernanceRouter address is added, removed, or changed * @param domain the domain of the remote Router * @param previousRouter the previously registered router; 0 if router is being added * @param newRouter the new registered router; 0 if router is being removed */ event SetRouter( uint32 indexed domain, bytes32 previousRouter, bytes32 newRouter ); /** * @notice Emitted when the Governor role is transferred * @param previousGovernorDomain the domain of the previous Governor * @param newGovernorDomain the domain of the new Governor * @param previousGovernor the address of the previous Governor; 0 if the governor was remote * @param newGovernor the address of the new Governor; 0 if the governor is remote */ event TransferGovernor( uint32 previousGovernorDomain, uint32 newGovernorDomain, address indexed previousGovernor, address indexed newGovernor ); /** * @notice Emitted when the RecoveryManager role is transferred * @param previousRecoveryManager the address of the previous RecoveryManager * @param newRecoveryManager the address of the new RecoveryManager */ event TransferRecoveryManager( address indexed previousRecoveryManager, address indexed newRecoveryManager ); /** * @notice Emitted when recovery state is initiated by the RecoveryManager * @param recoveryManager the address of the current RecoveryManager who initiated the transition * @param recoveryActiveAt the block at which recovery state will be active */ event InitiateRecovery( address indexed recoveryManager, uint256 recoveryActiveAt ); /** * @notice Emitted when recovery state is exited by the RecoveryManager * @param recoveryManager the address of the current RecoveryManager who initiated the transition */ event ExitRecovery(address recoveryManager); modifier typeAssert(bytes29 _view, GovernanceMessage.Types _type) { _view.assertType(uint40(_type)); _; } // ============ Modifiers ============ modifier onlyReplica() { require(xAppConnectionManager.isReplica(msg.sender), "!replica"); _; } modifier onlyGovernorRouter(uint32 _domain, bytes32 _address) { require(_isGovernorRouter(_domain, _address), "!governorRouter"); _; } modifier onlyGovernor() { require(msg.sender == governor, "! called by governor"); _; } modifier onlyRecoveryManager() { require(msg.sender == recoveryManager, "! called by recovery manager"); _; } modifier onlyInRecovery() { require(inRecovery(), "! in recovery"); _; } modifier onlyNotInRecovery() { require(!inRecovery(), "in recovery"); _; } modifier onlyGovernorOrRecoveryManager() { if (!inRecovery()) { require(msg.sender == governor, "! called by governor"); } else { require( msg.sender == recoveryManager, "! called by recovery manager" ); } _; } // ============ Constructor ============ constructor(uint32 _localDomain, uint256 _recoveryTimelock) { localDomain = _localDomain; recoveryTimelock = _recoveryTimelock; } // ============ Initializer ============ function initialize( address _xAppConnectionManager, address _recoveryManager ) public initializer { // initialize governor address _governorAddr = msg.sender; bool _isLocalGovernor = true; _transferGovernor(localDomain, _governorAddr, _isLocalGovernor); // initialize recovery manager recoveryManager = _recoveryManager; // initialize XAppConnectionManager setXAppConnectionManager(_xAppConnectionManager); require( xAppConnectionManager.localDomain() == localDomain, "XAppConnectionManager bad domain" ); } // ============ External Functions ============ /** * @notice Handle Optics messages * For all non-Governor chains to handle messages * sent from the Governor chain via Optics. * Governor chain should never receive messages, * because non-Governor chains are not able to send them * @param _origin The domain (of the Governor Router) * @param _sender The message sender (must be the Governor Router) * @param _message The message */ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyGovernorRouter(_origin, _sender) { bytes29 _msg = _message.ref(0); if (_msg.isValidCall()) { _handleCall(_msg.tryAsCall()); } else if (_msg.isValidTransferGovernor()) { _handleTransferGovernor(_msg.tryAsTransferGovernor()); } else if (_msg.isValidSetRouter()) { _handleSetRouter(_msg.tryAsSetRouter()); } else { require(false, "!valid message type"); } } /** * @notice Dispatch calls locally * @param _calls The calls */ function callLocal(GovernanceMessage.Call[] calldata _calls) external onlyGovernorOrRecoveryManager { for (uint256 i = 0; i < _calls.length; i++) { _dispatchCall(_calls[i]); } } /** * @notice Dispatch calls on a remote chain via the remote GovernanceRouter * @param _destination The domain of the remote chain * @param _calls The calls */ function callRemote( uint32 _destination, GovernanceMessage.Call[] calldata _calls ) external onlyGovernor onlyNotInRecovery { // ensure that destination chain has enrolled router bytes32 _router = _mustHaveRouter(_destination); // format call message bytes memory _msg = GovernanceMessage.formatCalls(_calls); // dispatch call message using Optics Home(xAppConnectionManager.home()).dispatch( _destination, _router, _msg ); } /** * @notice Transfer governorship * @param _newDomain The domain of the new governor * @param _newGovernor The address of the new governor */ function transferGovernor(uint32 _newDomain, address _newGovernor) external onlyGovernor onlyNotInRecovery { bool _isLocalGovernor = _isLocalDomain(_newDomain); // transfer the governor locally _transferGovernor(_newDomain, _newGovernor, _isLocalGovernor); // if the governor domain is local, we only need to change the governor address locally // no need to message remote routers; they should already have the same domain set and governor = bytes32(0) if (_isLocalGovernor) { return; } // format transfer governor message bytes memory _transferGovernorMessage = GovernanceMessage .formatTransferGovernor( _newDomain, TypeCasts.addressToBytes32(_newGovernor) ); // send transfer governor message to all remote routers // note: this assumes that the Router is on the global GovernorDomain; // this causes a process error when relinquishing governorship // on a newly deployed domain which is not the GovernorDomain _sendToAllRemoteRouters(_transferGovernorMessage); } /** * @notice Transfer recovery manager role * @dev callable by the recoveryManager at any time to transfer the role * @param _newRecoveryManager The address of the new recovery manager */ function transferRecoveryManager(address _newRecoveryManager) external onlyRecoveryManager { emit TransferRecoveryManager(recoveryManager, _newRecoveryManager); recoveryManager = _newRecoveryManager; } /** * @notice Set the router address for a given domain and * dispatch the change to all remote routers * @param _domain The domain * @param _router The address of the new router */ function setRouter(uint32 _domain, bytes32 _router) external onlyGovernor onlyNotInRecovery { // set the router locally _setRouter(_domain, _router); // format message to set the router on all remote routers bytes memory _setRouterMessage = GovernanceMessage.formatSetRouter( _domain, _router ); _sendToAllRemoteRouters(_setRouterMessage); } /** * @notice Set the router address *locally only* * for the deployer to setup the router mapping locally * before transferring governorship to the "true" governor * @dev External helper for contract setup * @param _domain The domain * @param _router The new router */ function setRouterLocal(uint32 _domain, bytes32 _router) external onlyGovernorOrRecoveryManager { // set the router locally _setRouter(_domain, _router); } /** * @notice Set the address of the XAppConnectionManager * @dev Domain/address validation helper * @param _xAppConnectionManager The address of the new xAppConnectionManager */ function setXAppConnectionManager(address _xAppConnectionManager) public onlyGovernorOrRecoveryManager { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); } /** * @notice Initiate the recovery timelock * @dev callable by the recovery manager */ function initiateRecoveryTimelock() external onlyNotInRecovery onlyRecoveryManager { require(recoveryActiveAt == 0, "recovery already initiated"); // set the time that recovery will be active recoveryActiveAt = block.timestamp.add(recoveryTimelock); emit InitiateRecovery(recoveryManager, recoveryActiveAt); } /** * @notice Exit recovery mode * @dev callable by the recovery manager to end recovery mode */ function exitRecovery() external onlyRecoveryManager { require(recoveryActiveAt != 0, "recovery not initiated"); delete recoveryActiveAt; emit ExitRecovery(recoveryManager); } // ============ Public Functions ============ /** * @notice Check if the contract is in recovery mode currently * @return TRUE iff the contract is actively in recovery mode currently */ function inRecovery() public view returns (bool) { uint256 _recoveryActiveAt = recoveryActiveAt; bool _recoveryInitiated = _recoveryActiveAt != 0; bool _recoveryActive = _recoveryActiveAt <= block.timestamp; return _recoveryInitiated && _recoveryActive; } // ============ Internal Functions ============ /** * @notice Handle message dispatching calls locally * @param _msg The message */ function _handleCall(bytes29 _msg) internal typeAssert(_msg, GovernanceMessage.Types.Call) { GovernanceMessage.Call[] memory _calls = _msg.getCalls(); for (uint256 i = 0; i < _calls.length; i++) { _dispatchCall(_calls[i]); } } /** * @notice Handle message transferring governorship to a new Governor * @param _msg The message */ function _handleTransferGovernor(bytes29 _msg) internal typeAssert(_msg, GovernanceMessage.Types.TransferGovernor) { uint32 _newDomain = _msg.domain(); address _newGovernor = TypeCasts.bytes32ToAddress(_msg.governor()); bool _isLocalGovernor = _isLocalDomain(_newDomain); _transferGovernor(_newDomain, _newGovernor, _isLocalGovernor); } /** * @notice Handle message setting the router address for a given domain * @param _msg The message */ function _handleSetRouter(bytes29 _msg) internal typeAssert(_msg, GovernanceMessage.Types.SetRouter) { uint32 _domain = _msg.domain(); bytes32 _router = _msg.router(); _setRouter(_domain, _router); } /** * @notice Dispatch message to all remote routers * @param _msg The message */ function _sendToAllRemoteRouters(bytes memory _msg) internal { Home _home = Home(xAppConnectionManager.home()); for (uint256 i = 0; i < domains.length; i++) { if (domains[i] != uint32(0)) { _home.dispatch(domains[i], routers[domains[i]], _msg); } } } /** * @notice Dispatch call locally * @param _call The call * @return _ret */ function _dispatchCall(GovernanceMessage.Call memory _call) internal returns (bytes memory _ret) { address _toContract = TypeCasts.bytes32ToAddress(_call.to); // attempt to dispatch using low-level call bool _success; (_success, _ret) = _toContract.call(_call.data); // revert if the call failed require(_success, "call failed"); } /** * @notice Transfer governorship within this contract's state * @param _newDomain The domain of the new governor * @param _newGovernor The address of the new governor * @param _isLocalGovernor True if the newDomain is the localDomain */ function _transferGovernor( uint32 _newDomain, address _newGovernor, bool _isLocalGovernor ) internal { // require that the governor domain has a valid router if (!_isLocalGovernor) { _mustHaveRouter(_newDomain); } // Governor is 0x0 unless the governor is local address _newGov = _isLocalGovernor ? _newGovernor : address(0); // emit event before updating state variables emit TransferGovernor(governorDomain, _newDomain, governor, _newGov); // update state governorDomain = _newDomain; governor = _newGov; } /** * @notice Set the router for a given domain * @param _domain The domain * @param _newRouter The new router */ function _setRouter(uint32 _domain, bytes32 _newRouter) internal { bytes32 _previousRouter = routers[_domain]; // emit event at beginning in case return after remove emit SetRouter(_domain, _previousRouter, _newRouter); // if the router is being removed, remove the domain if (_newRouter == bytes32(0)) { _removeDomain(_domain); return; } // if the router is being added, add the domain if (_previousRouter == bytes32(0)) { _addDomain(_domain); } // update state with new router routers[_domain] = _newRouter; } /** * @notice Add a domain that has a router * @param _domain The domain */ function _addDomain(uint32 _domain) internal { domains.push(_domain); } /** * @notice Remove a domain and its associated router * @param _domain The domain */ function _removeDomain(uint32 _domain) internal { delete routers[_domain]; // find the index of the domain to remove & delete it from domains[] for (uint256 i = 0; i < domains.length; i++) { if (domains[i] == _domain) { delete domains[i]; return; } } } /** * @notice Determine if a given domain and address is the Governor Router * @param _domain The domain * @param _address The address of the domain's router * @return _ret True if the given domain/address is the * Governor Router. */ function _isGovernorRouter(uint32 _domain, bytes32 _address) internal view returns (bool) { return _domain == governorDomain && _address == routers[_domain]; } /** * @notice Determine if a given domain is the local domain * @param _domain The domain * @return _ret - True if the given domain is the local domain */ function _isLocalDomain(uint32 _domain) internal view returns (bool) { return _domain == localDomain; } /** * @notice Require that a domain has a router and returns the router * @param _domain The domain * @return _router - The domain's router */ function _mustHaveRouter(uint32 _domain) internal view returns (bytes32 _router) { _router = routers[_domain]; require(_router != bytes32(0), "!router"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library GovernanceMessage { using TypedMemView for bytes; using TypedMemView for bytes29; uint256 private constant CALL_PREFIX_LEN = 64; uint256 private constant MSG_PREFIX_NUM_ITEMS = 2; uint256 private constant MSG_PREFIX_LEN = 2; uint256 private constant GOV_ACTION_LEN = 37; enum Types { Invalid, // 0 Call, // 1 TransferGovernor, // 2 SetRouter, // 3 Data // 4 } struct Call { bytes32 to; bytes data; } modifier typeAssert(bytes29 _view, Types _t) { _view.assertType(uint40(_t)); _; } // Types.Call function data(bytes29 _view) internal view returns (bytes memory _data) { _data = TypedMemView.clone( _view.slice(CALL_PREFIX_LEN, dataLen(_view), uint40(Types.Data)) ); } function formatCalls(Call[] memory _calls) internal view returns (bytes memory _msg) { uint256 _numCalls = _calls.length; bytes29[] memory _encodedCalls = new bytes29[]( _numCalls + MSG_PREFIX_NUM_ITEMS ); // Add Types.Call identifier _encodedCalls[0] = abi.encodePacked(Types.Call).ref(0); // Add number of calls _encodedCalls[1] = abi.encodePacked(uint8(_numCalls)).ref(0); for (uint256 i = 0; i < _numCalls; i++) { Call memory _call = _calls[i]; bytes29 _callMsg = abi .encodePacked(_call.to, _call.data.length, _call.data) .ref(0); _encodedCalls[i + MSG_PREFIX_NUM_ITEMS] = _callMsg; } _msg = TypedMemView.join(_encodedCalls); } function formatTransferGovernor(uint32 _domain, bytes32 _governor) internal view returns (bytes memory _msg) { _msg = TypedMemView.clone( mustBeTransferGovernor( abi .encodePacked(Types.TransferGovernor, _domain, _governor) .ref(0) ) ); } function formatSetRouter(uint32 _domain, bytes32 _router) internal view returns (bytes memory _msg) { _msg = TypedMemView.clone( mustBeSetRouter( abi.encodePacked(Types.SetRouter, _domain, _router).ref(0) ) ); } function getCalls(bytes29 _msg) internal view returns (Call[] memory) { uint8 _numCalls = uint8(_msg.indexUint(1, 1)); // Skip message prefix bytes29 _msgPtr = _msg.slice( MSG_PREFIX_LEN, _msg.len() - MSG_PREFIX_LEN, uint40(Types.Call) ); Call[] memory _calls = new Call[](_numCalls); uint256 counter = 0; while (_msgPtr.len() > 0) { _calls[counter].to = to(_msgPtr); _calls[counter].data = data(_msgPtr); _msgPtr = nextCall(_msgPtr); counter++; } return _calls; } function nextCall(bytes29 _view) internal pure typeAssert(_view, Types.Call) returns (bytes29) { uint256 lastCallLen = CALL_PREFIX_LEN + dataLen(_view); return _view.slice( lastCallLen, _view.len() - lastCallLen, uint40(Types.Call) ); } function messageType(bytes29 _view) internal pure returns (Types) { return Types(uint8(_view.typeOf())); } /* Message fields */ // All Types function identifier(bytes29 _view) internal pure returns (uint8) { return uint8(_view.indexUint(0, 1)); } // Types.Call function to(bytes29 _view) internal pure returns (bytes32) { return _view.index(0, 32); } // Types.Call function dataLen(bytes29 _view) internal pure returns (uint256) { return uint256(_view.index(32, 32)); } // Types.TransferGovernor & Types.EnrollRemote function domain(bytes29 _view) internal pure returns (uint32) { return uint32(_view.indexUint(1, 4)); } // Types.EnrollRemote function router(bytes29 _view) internal pure returns (bytes32) { return _view.index(5, 32); } // Types.TransferGovernor function governor(bytes29 _view) internal pure returns (bytes32) { return _view.index(5, 32); } /* Message Type: CALL struct Call { identifier, // message ID -- 1 byte numCalls, // number of calls -- 1 byte calls[], { to, // address to call -- 32 bytes dataLen, // call data length -- 32 bytes, data // call data -- 0+ bytes (length unknown) } } */ function isValidCall(bytes29 _view) internal pure returns (bool) { return identifier(_view) == uint8(Types.Call) && _view.len() >= CALL_PREFIX_LEN; } function isCall(bytes29 _view) internal pure returns (bool) { return isValidCall(_view) && messageType(_view) == Types.Call; } function tryAsCall(bytes29 _view) internal pure returns (bytes29) { if (isValidCall(_view)) { return _view.castTo(uint40(Types.Call)); } return TypedMemView.nullView(); } function mustBeCalls(bytes29 _view) internal pure returns (bytes29) { return tryAsCall(_view).assertValid(); } /* Message Type: TRANSFER GOVERNOR struct TransferGovernor { identifier, // message ID -- 1 byte domain, // domain of new governor -- 4 bytes addr // address of new governor -- 32 bytes } */ function isValidTransferGovernor(bytes29 _view) internal pure returns (bool) { return identifier(_view) == uint8(Types.TransferGovernor) && _view.len() == GOV_ACTION_LEN; } function isTransferGovernor(bytes29 _view) internal pure returns (bool) { return isValidTransferGovernor(_view) && messageType(_view) == Types.TransferGovernor; } function tryAsTransferGovernor(bytes29 _view) internal pure returns (bytes29) { if (isValidTransferGovernor(_view)) { return _view.castTo(uint40(Types.TransferGovernor)); } return TypedMemView.nullView(); } function mustBeTransferGovernor(bytes29 _view) internal pure returns (bytes29) { return tryAsTransferGovernor(_view).assertValid(); } /* Message Type: ENROLL ROUTER struct SetRouter { identifier, // message ID -- 1 byte domain, // domain of new router -- 4 bytes addr // address of new router -- 32 bytes } */ function isValidSetRouter(bytes29 _view) internal pure returns (bool) { return identifier(_view) == uint8(Types.SetRouter) && _view.len() == GOV_ACTION_LEN; } function isSetRouter(bytes29 _view) internal pure returns (bool) { return isValidSetRouter(_view) && messageType(_view) == Types.SetRouter; } function tryAsSetRouter(bytes29 _view) internal pure returns (bytes29) { if (isValidSetRouter(_view)) { return _view.castTo(uint40(Types.SetRouter)); } return TypedMemView.nullView(); } function mustBeSetRouter(bytes29 _view) internal pure returns (bytes29) { return tryAsSetRouter(_view).assertValid(); } } // 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.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 OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // 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 "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title 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; require(c / _a == _b, "Overflow during multiplication."); 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) { require(_b <= _a, "Underflow during subtraction."); 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, "Overflow during addition."); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } }
Exit recovery mode callable by the recovery manager to end recovery mode/
function exitRecovery() external onlyRecoveryManager { require(recoveryActiveAt != 0, "recovery not initiated"); delete recoveryActiveAt; emit ExitRecovery(recoveryManager); }
9,926,135
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import '@unlock-protocol/contracts/dist/PublicLock/ILockKeyPurchaseHookV7.sol'; import '@unlock-protocol/contracts/dist/PublicLock/IPublicLockV8sol8.sol'; import '../mixins/LockRoles.sol'; /** * @notice Used with a Lock in order to require the user knows * a code in order to buy. * @dev One instance of this contract may be used for all v7 locks. */ contract CodeRequiredHook is ILockKeyPurchaseHookV7, LockRoles { /** * @notice The code expressed as an address where the private key is * keccak256(abi.encode(code, lock.address)) */ mapping(address => mapping(address => bool)) public lockToCodeAddress; /** * @notice Allows the lock manager to add one or more codes. */ function addCodes( IPublicLockV8 _lock, address[] calldata _codeAddresses ) external onlyLockManager(_lock) { for(uint i = 0; i < _codeAddresses.length; i++) { require(_codeAddresses[i] != address(0), 'INVALID_CODE'); lockToCodeAddress[address(_lock)][_codeAddresses[i]] = true; } } /** * @notice Allows the lock manager to remove one or more codes. */ function removeCodes( IPublicLockV8 _lock, address[] calldata _codeAddresses ) external onlyLockManager(_lock) { for(uint i = 0; i < _codeAddresses.length; i++) { require(_codeAddresses[i] != address(0), 'INVALID_CODE'); lockToCodeAddress[address(_lock)][_codeAddresses[i]] = false; } } /** * @notice Returns the price per key which is unaffected by this hook. */ function keyPurchasePrice( address /*from*/, address /*recipient*/, address /*referrer*/, bytes calldata /*data*/ ) external override view returns (uint minKeyPrice) { return IPublicLockV8(msg.sender).keyPrice(); } /** * @notice Confirms the correct code was entered in order to purchase a key. * @param _recipient the account which will be granted a key * @param _data arbitrary data populated by the front-end which initiated the sale */ function onKeyPurchase( address /*from*/, address _recipient, address /*referrer*/, bytes calldata _data, uint /*minKeyPrice*/, uint /*pricePaid*/ ) external view override { // Confirm `_to` (the new keyOwner) bytes32 secretMessage = ECDSA.toEthSignedMessageHash(keccak256(abi.encode(_recipient))); require(lockToCodeAddress[msg.sender][ECDSA.recover(secretMessage, _data)], 'INCORRECT_CODE'); } }
Allows the lock manager to remove one or more codes./
function removeCodes( IPublicLockV8 _lock, address[] calldata _codeAddresses ) external onlyLockManager(_lock) { for(uint i = 0; i < _codeAddresses.length; i++) { require(_codeAddresses[i] != address(0), 'INVALID_CODE'); lockToCodeAddress[address(_lock)][_codeAddresses[i]] = false; } }
1,071,296
./full_match/4/0x7C2aEBAfBB7c7AD6bE572A587a4634394924B2c9/sources/smartsig/NiftyNafty.sol
Get the next token ID Randomly gets a new token ID and keeps track of the ones that are still available. return the next token ID If this matrix position is empty, set the value to the generated random number. Otherwise, use the previously stored number from the matrix. If the last available tokenID is still unused... ...store that ID in the current matrix position. ...otherwise copy over the stored number to the current matrix position.
function nextToken(uint256 tokenCount) internal returns (uint256) { uint256 maxIndex = PUBLIC_MAX - tokenCount; uint256 random = uint256(keccak256( abi.encodePacked( msg.sender, block.coinbase, block.difficulty, block.gaslimit, block.timestamp ) )) % maxIndex; uint256 value = 0; if (tokenMatrix[random] == 0) { value = random; value = tokenMatrix[random]; } if (tokenMatrix[maxIndex - 1] == 0) { tokenMatrix[random] = maxIndex - 1; tokenMatrix[random] = tokenMatrix[maxIndex - 1]; } return value + startIDFrom; }
12,529,387
./full_match/4/0x6831048fd98b7f5e58735d2Ad7D35B49F3A2e024/sources/browser/GovTreasurer.sol
DEPOSIT | ASSETS (TOKENS)
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 taxedAmount = _amount.div(pool.taxRate); uint256 pending = user.amount.mul(pool.accGDAOPerShare).div(1e12).sub(user.rewardDebt); safeGDAOTransfer(msg.sender, pending); }
755,316
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function add(uint256 x, uint256 y) pure internal returns (uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function sub(uint256 x, uint256 y) pure internal returns (uint256) { assert(x >= y); uint256 z = x - y; return z; } function mul(uint256 x, uint256 y) pure internal returns (uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } } /* * 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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); 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 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title DogezerICOPublicCrowdSale public crowdsale contract */ contract DogezerICOPublicCrowdSale is Haltable{ using SafeMath for uint; string public name = "Dogezer Public Sale ITO"; address public beneficiary; uint public startTime = 1518699600; uint public stopTime = 1520514000; uint public totalTokensAvailableForSale = 9800000000000000; uint public preDGZTokensSold = 20699056632305; uint public privateSalesTokensSold = 92644444444444; uint public tokensAvailableForSale = 0; uint public tokensSoldOnPublicRound = 0; StandardToken public tokenReward; StandardToken public tokenRewardPreDGZ; mapping(address => uint256) public balanceOf; mapping(address => uint256) public nonWLBalanceOf; mapping(address => uint256) public preBalanceOf; mapping(address => bool) public whiteList; event DGZTokensWithdraw(address where, uint amount); event DGZTokensSold(address where, uint amount); event TokensWithdraw(address where, address token, uint amount); event FundsWithdrawal(address where, uint amount); bool[] public yearlyTeamTokensPaid = [false, false, false]; uint public yearlyTeamAmount= 0; bool public bountyPaid = false; uint public bountyAmount = 0; bool public crowdsaleClosed = false; uint public constant maxPurchaseNonWhiteListed = 10 * 1 ether; uint public preDGZtoDGZExchangeRate = 914285714; uint public discountValue5 = 50.0 * 1 ether; uint public discountValue10 = 100.0 * 1 ether; uint[] public price1stWeek = [ 5625000, 5343750, 5062500]; uint[] public price2ndWeek = [ 5940000, 5643000, 5346000]; uint[] public price3rdWeek = [ 6250000, 5937500, 5625000]; function DogezerICOPublicCrowdSale( address addressOfPreDGZToken, address addressOfDGZToken, address addressOfBeneficiary ) public { beneficiary = addressOfBeneficiary; tokenRewardPreDGZ = StandardToken(addressOfPreDGZToken); tokenReward = StandardToken(addressOfDGZToken); tokensAvailableForSale = totalTokensAvailableForSale - preDGZTokensSold * preDGZtoDGZExchangeRate / 100000000 - privateSalesTokensSold; tokensSoldOnPublicRound = 0; } modifier onlyAfterStart() { require (now >= startTime); _; } modifier onlyBeforeEnd() { require (now < stopTime); _; } /** * @notice Main Payable function. * @dev In case if purchaser purchases on more than 10 ETH - only send tokens back if a person passed KYC (whitelisted) * in other case - funds are being frozen until whitelisting will be done. If price will change before * whitelisting is done for person, person will receive tokens basing on the new price, not old price. */ function () payable stopInEmergency onlyAfterStart onlyBeforeEnd public { require (crowdsaleClosed == false); require (tokensAvailableForSale > tokensSoldOnPublicRound); require (msg.value > 500000000000000); if ((balanceOf[msg.sender] + msg.value) > maxPurchaseNonWhiteListed && whiteList[msg.sender] == false) { // DGZ tokens are not being reserved for the purchasers who are not in a whitelist yet. nonWLBalanceOf[msg.sender] += msg.value; } else { sendTokens(msg.sender, msg.value); } } /** * @notice Add multiple addresses to white list to allow purchase for more than 10 ETH. Owned. * @dev Automatically send tokens to addresses being whitelisted if they have already send funds before * the call of this function. It is recommended to check that addreses being added are VALID and not smartcontracts * as problem somewhere in the middle of the loop may cause error which will make all gas to be lost. * @param _addresses address[] Pass a bunch of etherium addresses as * ["0xca35b7d915458ef540ade6068dfe2f44e8fa733c", "0x14723a09acff6d2a60dcdf7aa4aff308fddc160c"] to add to WhiteList */ function addListToWhiteList (address[] _addresses) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) { if (nonWLBalanceOf[_addresses[i]] > 0) { sendTokens(_addresses[i], nonWLBalanceOf[_addresses[i]]); nonWLBalanceOf[_addresses[i]] = 0; } whiteList[_addresses[i]] = true; } } /** * @notice Add a single address to white list to allow purchase for more than 10 ETH. Owned. * @param _address address An etherium addresses to add to WhiteList */ function addToWhiteList (address _address) public onlyOwner { if (nonWLBalanceOf[_address] > 0) { sendTokens(_address, nonWLBalanceOf[_address]); nonWLBalanceOf[_address] = 0; } whiteList[_address] = true; } /** * @notice Finalize sales and sets bounty & yearly paid value. Owned. */ function finalizeSale () public onlyOwner { require (crowdsaleClosed == false); crowdsaleClosed = true; uint totalSold = tokensSoldOnPublicRound + preDGZTokensSold * preDGZtoDGZExchangeRate / 100000000 + privateSalesTokensSold; bountyAmount = totalSold / 980 * 15; yearlyTeamAmount= totalSold / 980 * 5 / 3; } /** * @notice A function to burn unsold DGZ tokens. The ammount would be a parameter, not calculated value to ensure that all of the * last moment changes related to KYC processing, such as overdue of KYC documents or delay with confirming of KYC * documents which caused purchaser to receive tokens using next period price, are handled. Owned. * @param _amount uint Number of tokens to burn */ function tokenBurn (uint _amount) public onlyOwner { require (crowdsaleClosed == true); tokenReward.transfer(address(0), _amount); } /** * @notice A function to withdraw tokens for bounty campaign. Can be called only once. Owned. */ function bountyTokenWithdrawal () public onlyOwner { require (crowdsaleClosed == true); require (bountyPaid == false); tokenReward.transfer(beneficiary, bountyAmount); bountyPaid = true; } /** * @notice A function to withdraw team tokens. Allow to withdraw one third of founders share in each yearly * after the end of ICO. In total can be called at maximum 3 times. Owned. */ function yearlyOwnerTokenWithdrawal () public onlyOwner { require (crowdsaleClosed == true); require ( ((now > stopTime + 1 years) && (yearlyTeamTokensPaid[0] == false)) || ((now > stopTime + 2 years) && (yearlyTeamTokensPaid[1] == false)) || ((now > stopTime + 3 years) && (yearlyTeamTokensPaid[2] == false)) ); tokenReward.transfer(beneficiary, yearlyTeamAmount); if (yearlyTeamTokensPaid[0] == false) yearlyTeamTokensPaid[0] = true; else if (yearlyTeamTokensPaid[1] == false) yearlyTeamTokensPaid[1] = true; else if (yearlyTeamTokensPaid[2] == false) yearlyTeamTokensPaid[2] = true; } /** * @notice A method to exchange preDGZ tokens to DGZ tokens. To use that method, a person first * need to call approve method of preDGZ to define how many tokens to convert. Note that function * doesn't end with the rest of crowdsale - it may be possible to exchange preDGZ after the end of crowdsale * @dev Exchanged preDGZ tokens are automatically burned. */ function exchangePreDGZTokens() stopInEmergency onlyAfterStart public { uint tokenAmount = tokenRewardPreDGZ.allowance(msg.sender, this); require(tokenAmount > 0); require(tokenRewardPreDGZ.transferFrom(msg.sender, address(0), tokenAmount)); uint amountSendTokens = tokenAmount * preDGZtoDGZExchangeRate / 100000000; preBalanceOf[msg.sender] += tokenAmount; tokenReward.transfer(msg.sender, amountSendTokens); } /** * @notice This function is needed to handled unlikely case when person who owns preDGZ tokens * makes a mistake and send them to smartcontract without setting the allowance in advance. In such case * conversion of tokens by calling exchangePreDGZTokens is not possible. Ownable. * @dev IMPORTANT! Should only be called is Dogezer team is in possesion of preDGZ tokens. * @dev Doesn't increment tokensSoldOnPublicRound as these tokens are already accounted as preDGZTokensSold * @param _address address Etherium address where to send tokens as a result of conversion. * @param preDGZAmount uint Number of preDGZ to convert. */ function manuallyExchangeContractPreDGZtoDGZ(address _address, uint preDGZAmount) public onlyOwner { require (_address != address(0)); require (preDGZAmount > 0); uint amountSendTokens = preDGZAmount * preDGZtoDGZExchangeRate / 100000000; preBalanceOf[_address] += preDGZAmount; tokenReward.transfer(_address, amountSendTokens); } /** * @notice Function to define prices for some particular week. Would be utilized if prices are changed. Owned. * @dev It is important to apply this function for all of three weeks. The final week should be a week which is active now * @param week uint Ordinal number of the week. * @param price uint DGZ token price. * @param price5 uint DGZ token price with 5% discount. * @param price10 uint DGZ token price with 10% discount. */ function setTokenPrice (uint week, uint price, uint price5, uint price10) public onlyOwner { require (crowdsaleClosed == false); require (week >= 1 && week <= 3); if (week == 1) price1stWeek = [price, price5, price10]; else if (week == 2) price2ndWeek = [price, price5, price10]; else if (week == 3) price3rdWeek = [price, price5, price10]; } /** * @notice In case if prices are changed due to some great change in ETH price, * this function can be used to change conversion rate for preDGZ owners. Owned. * @param rate uint Conversion rate. */ function setPreDGZtoDgzRate (uint rate) public onlyOwner { preDGZtoDGZExchangeRate = rate; tokensAvailableForSale = totalTokensAvailableForSale - preDGZTokensSold * preDGZtoDGZExchangeRate / 100000000 - privateSalesTokensSold; } /** * @notice Set number of tokens sold on private round. Required to correctly calcualte * total numbers of tokens sold at the end. Owned. * @param tokens uint Number of tokens sold on private sale. */ function setPrivateSaleTokensSold (uint tokens) public onlyOwner { privateSalesTokensSold = tokens; tokensAvailableForSale = totalTokensAvailableForSale - preDGZTokensSold * preDGZtoDGZExchangeRate / 100000000 - privateSalesTokensSold; } /** * @notice Internal function which is responsible for sending tokens. Note that * discount is determined basing on accumulated sale, but only applied to the current * request to send tokens. * @param msg_sender address Address of PreDGZ holder who allowed it to exchange. * @param msg_value uint Number of DGZ tokens to send. */ function sendTokens(address msg_sender, uint msg_value) internal { var prices = price1stWeek; if (now >= startTime + 2 weeks) prices = price3rdWeek; else if (now >= startTime + 1 weeks) prices = price2ndWeek; uint currentPrice = prices[0]; if (balanceOf[msg_sender] + msg_value >= discountValue5) { currentPrice = prices[1]; if (balanceOf[msg_sender] + msg_value >= discountValue10) currentPrice = prices[2]; } uint amountSendTokens = msg_value / currentPrice; if (amountSendTokens > (tokensAvailableForSale - tokensSoldOnPublicRound)) { uint tokensAvailable = tokensAvailableForSale - tokensSoldOnPublicRound; uint refund = msg_value - (tokensAvailable * currentPrice); amountSendTokens = tokensAvailable; tokensSoldOnPublicRound += amountSendTokens; msg_sender.transfer(refund); balanceOf[msg_sender] += (msg_value - refund); } else { tokensSoldOnPublicRound += amountSendTokens; balanceOf[msg_sender] += msg_value; } tokenReward.transfer(msg_sender, amountSendTokens); DGZTokensSold(msg_sender, amountSendTokens); } /** * @notice Withdraw funds to beneficiary. Owned * @param _amount uint Amount funds to withdraw. */ function fundWithdrawal (uint _amount) public onlyOwner { require (crowdsaleClosed == true); beneficiary.transfer(_amount); FundsWithdrawal(beneficiary, _amount); } /** * @notice Function to process cases when person send more than 10 ETH to smartcontract * but never provided KYC data and wants/needs to be refunded. Owned * @param _address address Address of refunded person. */ function refundNonWhitelistedPerson (address _address) public onlyOwner { uint refundAmount = nonWLBalanceOf[_address]; nonWLBalanceOf[_address] = 0; _address.transfer(refundAmount); } /** * @notice Withdraws DGZ tokens to beneficiary. Would be used to process BTC payments. Owned. * @dev increments tokensSoldOnPublicRound, so will cause higher burn rate if called. * @param _amount uint Amount of DGZ tokens to withdraw. */ function tokenWithdrawal (uint _amount) public onlyOwner { require (crowdsaleClosed == false); tokenReward.transfer(beneficiary, _amount); tokensSoldOnPublicRound += _amount; DGZTokensWithdraw(beneficiary, _amount); } /** * @notice Withdraws tokens other than DGZ to beneficiary. Owned * @dev Generally need this to handle cases when user just transfers preDGZ * to the contract by mistake and we need to manually burn then after calling * manuallyExchangeContractPreDGZtoDGZ * @param _address address Address of tokens to withdraw. * @param _amount uint Amount of tokens to withdraw. */ function anyTokenWithdrawal (address _address, uint _amount) public onlyOwner { require(_address != address(tokenReward)); StandardToken token = StandardToken(_address); token.transfer(beneficiary, _amount); TokensWithdraw(beneficiary, _address, _amount); } /** * @notice Changes beneficiary address. Owned. * @param _newBeneficiary address Address of new beneficiary. */ function changeBeneficiary(address _newBeneficiary) public onlyOwner { if (_newBeneficiary != address(0)) { beneficiary = _newBeneficiary; } } /** * @notice Reopens closed sale to recalcualte total tokens sold if there are any late deals - such as * delayed whitelist processing. Owned. */ function reopenSale () public onlyOwner { require (crowdsaleClosed == true); crowdsaleClosed = false; } }
Main Payable function. In case if purchaser purchases on more than 10 ETH - only send tokens back if a person passed KYC (whitelisted) in other case - funds are being frozen until whitelisting will be done. If price will change before whitelisting is done for person, person will receive tokens basing on the new price, not old price./ DGZ tokens are not being reserved for the purchasers who are not in a whitelist yet.
function () payable stopInEmergency onlyAfterStart onlyBeforeEnd public { require (crowdsaleClosed == false); require (tokensAvailableForSale > tokensSoldOnPublicRound); require (msg.value > 500000000000000); if ((balanceOf[msg.sender] + msg.value) > maxPurchaseNonWhiteListed && whiteList[msg.sender] == false) { nonWLBalanceOf[msg.sender] += msg.value; } else { sendTokens(msg.sender, msg.value); } }
2,554,596
pragma solidity 0.6.12; import "../prize-strategy/PeriodicPrizeStrategy.sol"; /* solium-disable security/no-block-members */ interface PeriodicPrizeStrategyDistributorInterface { function distribute(uint256 randomNumber) external; }
solium-disable security/no-block-members /
interface PeriodicPrizeStrategyDistributorInterface { function distribute(uint256 randomNumber) external; }
1,805,083
./partial_match/1/0x266aB88D8679f3935990DD3db1d19ceeE939599d/sources/afiUSDT.sol
No rebalance implementation for lower fees and faster swaps Could have over value from cTokens Calc to redeem before updating balances Check balance
function withdraw(uint256 _shares) external nonReentrant { require(_shares > 0, "withdraw must be greater than 0"); uint256 ibalance = balanceOf(msg.sender); require(_shares <= ibalance, "insufficient balance"); pool = _calcPoolValueInToken(); uint256 r = (pool.mul(_shares)).div(_totalSupply); _balances[msg.sender] = _balances[msg.sender].sub(_shares, "redeem amount exceeds balance"); _totalSupply = _totalSupply.sub(_shares); emit Transfer(msg.sender, address(0), _shares); uint256 b = IERC20(token).balanceOf(address(this)); if (b < r) { _withdrawSome(r.sub(b)); } IERC20(token).safeTransfer(msg.sender, r); pool = _calcPoolValueInToken(); }
3,557,351
pragma solidity ^0.5.0; import "./HotelToken.sol"; contract HotelTokenSale { address payable admin; HotelToken public tokenContract; uint256 public tokenPrice; uint256 public tokensSold; event Sell(address _buyer, uint256 _amount); event EndSale(uint256 _totalAmountSold); constructor(HotelToken _tokenContract, uint256 _tokenPrice) public { admin = msg.sender; tokenContract = _tokenContract; tokenPrice = _tokenPrice; _tokenContract.makeSaleLive(true); } // function multiply(uint x, uint y) internal pure returns (uint z) { // require(y == 0 || (z = x * y) / y == x); // } function buyTokens(uint256 _numberOfTokens, uint256 _date) public payable { // require(msg.value == multiply(_numberOfTokens, tokenPrice), 'msg.value must equal number of tokens in wei'); require(tokenContract.balanceOfPerDates(address(this), _date) >= _numberOfTokens, 'cannot purchase more tokens than available'); require(tokenContract.transfer(msg.sender, _numberOfTokens, _date), 'Unable to send tokens'); // emit Balance(address(this), _numberOfTokens); tokensSold += _numberOfTokens; emit Sell(msg.sender, _numberOfTokens); } function endSale() public { require(msg.sender == admin,"sender is not admin"); require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this)),1),"error in end sale"); // require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this)))); // UPDATE: Let's not destroy the contract here // Just transfer the balance to the admin admin.transfer(address(this).balance); emit EndSale(tokensSold); } }
require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this)))); UPDATE: Let's not destroy the contract here Just transfer the balance to the admin
function endSale() public { require(msg.sender == admin,"sender is not admin"); require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this)),1),"error in end sale"); admin.transfer(address(this).balance); emit EndSale(tokensSold); }
5,525,891
./full_match/1/0x166aEeE931f1933DA41273D0A76d8b23Dca3c196/sources/MouseTrap.sol
must register before trying to steal cheese must wait at least 1 block after registering before trying to steal cheese must have priority fee of at least 20 gwei must pass in the correct block number cheese can be stolen only once per block
function stealTheCheese(uint256 _targetBlock) external { if (registeredBlock[msg.sender] == 0) return; if (block.number == registeredBlock[msg.sender]) { _lose(); return; } if (tx.gasprice - block.basefee < 20 gwei) { _lose(); return; } if (_targetBlock != block.number) { _lose(); return; } if (lastBlockCheeseWasStolen == block.number) { _lose(); return; } lastBlockCheeseWasStolen = block.number; }
2,904,878
// simple planet invitation management contract // https://azimuth.network pragma solidity 0.4.24; //////////////////////////////////////////////////////////////////////////////// // Imports //////////////////////////////////////////////////////////////////////////////// // OpenZeppelin's Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // Azimuth's SafeMath8.sol /** * @title SafeMath8 * @dev Math operations for uint8 with safety checks that throw on error */ library SafeMath8 { function mul(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint8 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint8 a, uint8 b) internal pure returns (uint8) { assert(b <= a); return a - b; } function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; assert(c >= a); return c; } } // Azimuth's SafeMath16.sol /** * @title SafeMath16 * @dev Math operations for uint16 with safety checks that throw on error */ library SafeMath16 { function mul(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint16 a, uint16 b) internal pure returns (uint16) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint16 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } } // OpenZeppelin's SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // OpenZeppelin's ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // OpenZeppelin's SupportsInterfaceWithLookup.sol /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } // OpenZeppelin's ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_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)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ 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 exists(uint256 _tokenId) public view returns (bool _exists); 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 _data ) public; } // OpenZeppelin's ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // OpenZeppelin's ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the 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(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // OpenZeppelin's AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * 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 _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) 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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // Azimuth's Azimuth.sol // Azimuth: point state data contract // // This contract is used for storing all data related to Azimuth points // and their ownership. Consider this contract the Azimuth ledger. // // It also contains permissions data, which ties in to ERC721 // functionality. Operators of an address are allowed to transfer // ownership of all points owned by their associated address // (ERC721's approveAll()). A transfer proxy is allowed to transfer // ownership of a single point (ERC721's approve()). // Separate from ERC721 are managers, assigned per point. They are // allowed to perform "low-impact" operations on the owner's points, // like configuring public keys and making escape requests. // // Since data stores are difficult to upgrade, this contract contains // as little actual business logic as possible. Instead, the data stored // herein can only be modified by this contract's owner, which can be // changed and is thus upgradable/replaceable. // // This contract will be owned by the Ecliptic contract. // contract Azimuth is Ownable { // // Events // // OwnerChanged: :point is now owned by :owner // event OwnerChanged(uint32 indexed point, address indexed owner); // Activated: :point is now active // event Activated(uint32 indexed point); // Spawned: :prefix has spawned :child // event Spawned(uint32 indexed prefix, uint32 indexed child); // EscapeRequested: :point has requested a new :sponsor // event EscapeRequested(uint32 indexed point, uint32 indexed sponsor); // EscapeCanceled: :point's :sponsor request was canceled or rejected // event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor); // EscapeAccepted: :point confirmed with a new :sponsor // event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor); // LostSponsor: :point's :sponsor is now refusing it service // event LostSponsor(uint32 indexed point, uint32 indexed sponsor); // ChangedKeys: :point has new network public keys // event ChangedKeys( uint32 indexed point, bytes32 encryptionKey, bytes32 authenticationKey, uint32 cryptoSuiteVersion, uint32 keyRevisionNumber ); // BrokeContinuity: :point has a new continuity number, :number // event BrokeContinuity(uint32 indexed point, uint32 number); // ChangedSpawnProxy: :spawnProxy can now spawn using :point // event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy); // ChangedTransferProxy: :transferProxy can now transfer ownership of :point // event ChangedTransferProxy( uint32 indexed point, address indexed transferProxy ); // ChangedManagementProxy: :managementProxy can now manage :point // event ChangedManagementProxy( uint32 indexed point, address indexed managementProxy ); // ChangedVotingProxy: :votingProxy can now vote using :point // event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy); // ChangedDns: dnsDomains have been updated // event ChangedDns(string primary, string secondary, string tertiary); // // Structures // // Size: kinds of points registered on-chain // // NOTE: the order matters, because of Solidity enum numbering // enum Size { Galaxy, // = 0 Star, // = 1 Planet // = 2 } // Point: state of a point // // While the ordering of the struct members is semantically chaotic, // they are ordered to tightly pack them into Ethereum's 32-byte storage // slots, which reduces gas costs for some function calls. // The comment ticks indicate assumed slot boundaries. // struct Point { // encryptionKey: (curve25519) encryption public key, or 0 for none // bytes32 encryptionKey; // // authenticationKey: (ed25519) authentication public key, or 0 for none // bytes32 authenticationKey; // // spawned: for stars and galaxies, all :active children // uint32[] spawned; // // hasSponsor: true if the sponsor still supports the point // bool hasSponsor; // active: whether point can be linked // // false: point belongs to prefix, cannot be configured or linked // true: point no longer belongs to prefix, can be configured and linked // bool active; // escapeRequested: true if the point has requested to change sponsors // bool escapeRequested; // sponsor: the point that supports this one on the network, or, // if :hasSponsor is false, the last point that supported it. // (by default, the point's half-width prefix) // uint32 sponsor; // escapeRequestedTo: if :escapeRequested is true, new sponsor requested // uint32 escapeRequestedTo; // cryptoSuiteVersion: version of the crypto suite used for the pubkeys // uint32 cryptoSuiteVersion; // keyRevisionNumber: incremented every time the public keys change // uint32 keyRevisionNumber; // continuityNumber: incremented to indicate network-side state loss // uint32 continuityNumber; } // Deed: permissions for a point // struct Deed { // owner: address that owns this point // address owner; // managementProxy: 0, or another address with the right to perform // low-impact, managerial operations on this point // address managementProxy; // spawnProxy: 0, or another address with the right to spawn children // of this point // address spawnProxy; // votingProxy: 0, or another address with the right to vote as this point // address votingProxy; // transferProxy: 0, or another address with the right to transfer // ownership of this point // address transferProxy; } // // General state // // points: per point, general network-relevant point state // mapping(uint32 => Point) public points; // rights: per point, on-chain ownership and permissions // mapping(uint32 => Deed) public rights; // operators: per owner, per address, has the right to transfer ownership // of all the owner's points (ERC721) // mapping(address => mapping(address => bool)) public operators; // dnsDomains: base domains for contacting galaxies // // dnsDomains[0] is primary, the others are used as fallbacks // string[3] public dnsDomains; // // Lookups // // sponsoring: per point, the points they are sponsoring // mapping(uint32 => uint32[]) public sponsoring; // sponsoringIndexes: per point, per point, (index + 1) in // the sponsoring array // mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes; // escapeRequests: per point, the points they have open escape requests from // mapping(uint32 => uint32[]) public escapeRequests; // escapeRequestsIndexes: per point, per point, (index + 1) in // the escapeRequests array // mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes; // pointsOwnedBy: per address, the points they own // mapping(address => uint32[]) public pointsOwnedBy; // pointOwnerIndexes: per owner, per point, (index + 1) in // the pointsOwnedBy array // // We delete owners by moving the last entry in the array to the // newly emptied slot, which is (n - 1) where n is the value of // pointOwnerIndexes[owner][point]. // mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes; // managerFor: per address, the points they are the management proxy for // mapping(address => uint32[]) public managerFor; // managerForIndexes: per address, per point, (index + 1) in // the managerFor array // mapping(address => mapping(uint32 => uint256)) public managerForIndexes; // spawningFor: per address, the points they can spawn with // mapping(address => uint32[]) public spawningFor; // spawningForIndexes: per address, per point, (index + 1) in // the spawningFor array // mapping(address => mapping(uint32 => uint256)) public spawningForIndexes; // votingFor: per address, the points they can vote with // mapping(address => uint32[]) public votingFor; // votingForIndexes: per address, per point, (index + 1) in // the votingFor array // mapping(address => mapping(uint32 => uint256)) public votingForIndexes; // transferringFor: per address, the points they can transfer // mapping(address => uint32[]) public transferringFor; // transferringForIndexes: per address, per point, (index + 1) in // the transferringFor array // mapping(address => mapping(uint32 => uint256)) public transferringForIndexes; // // Logic // // constructor(): configure default dns domains // constructor() public { setDnsDomains("example.com", "example.com", "example.com"); } // setDnsDomains(): set the base domains used for contacting galaxies // // Note: since a string is really just a byte[], and Solidity can't // work with two-dimensional arrays yet, we pass in the three // domains as individual strings. // function setDnsDomains(string _primary, string _secondary, string _tertiary) onlyOwner public { dnsDomains[0] = _primary; dnsDomains[1] = _secondary; dnsDomains[2] = _tertiary; emit ChangedDns(_primary, _secondary, _tertiary); } // // Point reading // // isActive(): return true if _point is active // function isActive(uint32 _point) view external returns (bool equals) { return points[_point].active; } // getKeys(): returns the public keys and their details, as currently // registered for _point // function getKeys(uint32 _point) view external returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision) { Point storage point = points[_point]; return (point.encryptionKey, point.authenticationKey, point.cryptoSuiteVersion, point.keyRevisionNumber); } // getKeyRevisionNumber(): gets the revision number of _point's current // public keys // function getKeyRevisionNumber(uint32 _point) view external returns (uint32 revision) { return points[_point].keyRevisionNumber; } // hasBeenLinked(): returns true if the point has ever been assigned keys // function hasBeenLinked(uint32 _point) view external returns (bool result) { return ( points[_point].keyRevisionNumber > 0 ); } // isLive(): returns true if _point currently has keys properly configured // function isLive(uint32 _point) view external returns (bool result) { Point storage point = points[_point]; return ( point.encryptionKey != 0 && point.authenticationKey != 0 && point.cryptoSuiteVersion != 0 ); } // getContinuityNumber(): returns _point's current continuity number // function getContinuityNumber(uint32 _point) view external returns (uint32 continuityNumber) { return points[_point].continuityNumber; } // getSpawnCount(): return the number of children spawned by _point // function getSpawnCount(uint32 _point) view external returns (uint32 spawnCount) { uint256 len = points[_point].spawned.length; assert(len < 2**32); return uint32(len); } // getSpawned(): return array of points created under _point // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawned(uint32 _point) view external returns (uint32[] spawned) { return points[_point].spawned; } // hasSponsor(): returns true if _point's sponsor is providing it service // function hasSponsor(uint32 _point) view external returns (bool has) { return points[_point].hasSponsor; } // getSponsor(): returns _point's current (or most recent) sponsor // function getSponsor(uint32 _point) view external returns (uint32 sponsor) { return points[_point].sponsor; } // isSponsor(): returns true if _sponsor is currently providing service // to _point // function isSponsor(uint32 _point, uint32 _sponsor) view external returns (bool result) { Point storage point = points[_point]; return ( point.hasSponsor && (point.sponsor == _sponsor) ); } // getSponsoringCount(): returns the number of points _sponsor is // providing service to // function getSponsoringCount(uint32 _sponsor) view external returns (uint256 count) { return sponsoring[_sponsor].length; } // getSponsoring(): returns a list of points _sponsor is providing // service to // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSponsoring(uint32 _sponsor) view external returns (uint32[] sponsees) { return sponsoring[_sponsor]; } // escaping // isEscaping(): returns true if _point has an outstanding escape request // function isEscaping(uint32 _point) view external returns (bool escaping) { return points[_point].escapeRequested; } // getEscapeRequest(): returns _point's current escape request // // the returned escape request is only valid as long as isEscaping() // returns true // function getEscapeRequest(uint32 _point) view external returns (uint32 escape) { return points[_point].escapeRequestedTo; } // isRequestingEscapeTo(): returns true if _point has an outstanding // escape request targetting _sponsor // function isRequestingEscapeTo(uint32 _point, uint32 _sponsor) view public returns (bool equals) { Point storage point = points[_point]; return (point.escapeRequested && (point.escapeRequestedTo == _sponsor)); } // getEscapeRequestsCount(): returns the number of points _sponsor // is providing service to // function getEscapeRequestsCount(uint32 _sponsor) view external returns (uint256 count) { return escapeRequests[_sponsor].length; } // getEscapeRequests(): get the points _sponsor has received escape // requests from // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getEscapeRequests(uint32 _sponsor) view external returns (uint32[] requests) { return escapeRequests[_sponsor]; } // // Point writing // // activatePoint(): activate a point, register it as spawned by its prefix // function activatePoint(uint32 _point) onlyOwner external { // make a point active, setting its sponsor to its prefix // Point storage point = points[_point]; require(!point.active); point.active = true; registerSponsor(_point, true, getPrefix(_point)); emit Activated(_point); } // setKeys(): set network public keys of _point to _encryptionKey and // _authenticationKey, with the specified _cryptoSuiteVersion // function setKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion) onlyOwner external { Point storage point = points[_point]; if ( point.encryptionKey == _encryptionKey && point.authenticationKey == _authenticationKey && point.cryptoSuiteVersion == _cryptoSuiteVersion ) { return; } point.encryptionKey = _encryptionKey; point.authenticationKey = _authenticationKey; point.cryptoSuiteVersion = _cryptoSuiteVersion; point.keyRevisionNumber++; emit ChangedKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion, point.keyRevisionNumber); } // incrementContinuityNumber(): break continuity for _point // function incrementContinuityNumber(uint32 _point) onlyOwner external { Point storage point = points[_point]; point.continuityNumber++; emit BrokeContinuity(_point, point.continuityNumber); } // registerSpawn(): add a point to its prefix's list of spawned points // function registerSpawned(uint32 _point) onlyOwner external { // if a point is its own prefix (a galaxy) then don't register it // uint32 prefix = getPrefix(_point); if (prefix == _point) { return; } // register a new spawned point for the prefix // points[prefix].spawned.push(_point); emit Spawned(prefix, _point); } // loseSponsor(): indicates that _point's sponsor is no longer providing // it service // function loseSponsor(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.hasSponsor) { return; } registerSponsor(_point, false, point.sponsor); emit LostSponsor(_point, point.sponsor); } // setEscapeRequest(): for _point, start an escape request to _sponsor // function setEscapeRequest(uint32 _point, uint32 _sponsor) onlyOwner external { if (isRequestingEscapeTo(_point, _sponsor)) { return; } registerEscapeRequest(_point, true, _sponsor); emit EscapeRequested(_point, _sponsor); } // cancelEscape(): for _point, stop the current escape request, if any // function cancelEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; if (!point.escapeRequested) { return; } uint32 request = point.escapeRequestedTo; registerEscapeRequest(_point, false, 0); emit EscapeCanceled(_point, request); } // doEscape(): perform the requested escape // function doEscape(uint32 _point) onlyOwner external { Point storage point = points[_point]; require(point.escapeRequested); registerSponsor(_point, true, point.escapeRequestedTo); registerEscapeRequest(_point, false, 0); emit EscapeAccepted(_point, point.sponsor); } // // Point utils // // getPrefix(): compute prefix ("parent") of _point // function getPrefix(uint32 _point) pure public returns (uint16 prefix) { if (_point < 0x10000) { return uint16(_point % 0x100); } return uint16(_point % 0x10000); } // getPointSize(): return the size of _point // function getPointSize(uint32 _point) external pure returns (Size _size) { if (_point < 0x100) return Size.Galaxy; if (_point < 0x10000) return Size.Star; return Size.Planet; } // internal use // registerSponsor(): set the sponsorship state of _point and update the // reverse lookup for sponsors // function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor) internal { Point storage point = points[_point]; bool had = point.hasSponsor; uint32 prev = point.sponsor; // if we didn't have a sponsor, and won't get one, // or if we get the sponsor we already have, // nothing will change, so jump out early. // if ( (!had && !_hasSponsor) || (had && _hasSponsor && prev == _sponsor) ) { return; } // if the point used to have a different sponsor, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (had) { // i: current index in previous sponsor's list of sponsored points // uint256 i = sponsoringIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :sponsoringIndexes reference // uint32[] storage prevSponsoring = sponsoring[prev]; uint256 last = prevSponsoring.length - 1; uint32 moved = prevSponsoring[last]; prevSponsoring[i] = moved; sponsoringIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSponsoring[last]); prevSponsoring.length = last; sponsoringIndexes[prev][_point] = 0; } if (_hasSponsor) { uint32[] storage newSponsoring = sponsoring[_sponsor]; newSponsoring.push(_point); sponsoringIndexes[_sponsor][_point] = newSponsoring.length; } point.sponsor = _sponsor; point.hasSponsor = _hasSponsor; } // registerEscapeRequest(): set the escape state of _point and update the // reverse lookup for sponsors // function registerEscapeRequest( uint32 _point, bool _isEscaping, uint32 _sponsor ) internal { Point storage point = points[_point]; bool was = point.escapeRequested; uint32 prev = point.escapeRequestedTo; // if we weren't escaping, and won't be, // or if we were escaping, and the new target is the same, // nothing will change, so jump out early. // if ( (!was && !_isEscaping) || (was && _isEscaping && prev == _sponsor) ) { return; } // if the point used to have a different request, do some gymnastics // to keep the reverse lookup gapless. delete the point from the old // sponsor's list, then fill that gap with the list tail. // if (was) { // i: current index in previous sponsor's list of sponsored points // uint256 i = escapeRequestsIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :escapeRequestsIndexes reference // uint32[] storage prevRequests = escapeRequests[prev]; uint256 last = prevRequests.length - 1; uint32 moved = prevRequests[last]; prevRequests[i] = moved; escapeRequestsIndexes[prev][moved] = i + 1; // delete the last item // delete(prevRequests[last]); prevRequests.length = last; escapeRequestsIndexes[prev][_point] = 0; } if (_isEscaping) { uint32[] storage newRequests = escapeRequests[_sponsor]; newRequests.push(_point); escapeRequestsIndexes[_sponsor][_point] = newRequests.length; } point.escapeRequestedTo = _sponsor; point.escapeRequested = _isEscaping; } // // Deed reading // // owner // getOwner(): return owner of _point // function getOwner(uint32 _point) view external returns (address owner) { return rights[_point].owner; } // isOwner(): true if _point is owned by _address // function isOwner(uint32 _point, address _address) view external returns (bool result) { return (rights[_point].owner == _address); } // getOwnedPointCount(): return length of array of points that _whose owns // function getOwnedPointCount(address _whose) view external returns (uint256 count) { return pointsOwnedBy[_whose].length; } // getOwnedPoints(): return array of points that _whose owns // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getOwnedPoints(address _whose) view external returns (uint32[] ownedPoints) { return pointsOwnedBy[_whose]; } // getOwnedPointAtIndex(): get point at _index from array of points that // _whose owns // function getOwnedPointAtIndex(address _whose, uint256 _index) view external returns (uint32 point) { uint32[] storage owned = pointsOwnedBy[_whose]; require(_index < owned.length); return owned[_index]; } // management proxy // getManagementProxy(): returns _point's current management proxy // function getManagementProxy(uint32 _point) view external returns (address manager) { return rights[_point].managementProxy; } // isManagementProxy(): returns true if _proxy is _point's management proxy // function isManagementProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].managementProxy == _proxy); } // canManage(): true if _who is the owner or manager of _point // function canManage(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.managementProxy) ) ); } // getManagerForCount(): returns the amount of points _proxy can manage // function getManagerForCount(address _proxy) view external returns (uint256 count) { return managerFor[_proxy].length; } // getManagerFor(): returns the points _proxy can manage // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getManagerFor(address _proxy) view external returns (uint32[] mfor) { return managerFor[_proxy]; } // spawn proxy // getSpawnProxy(): returns _point's current spawn proxy // function getSpawnProxy(uint32 _point) view external returns (address spawnProxy) { return rights[_point].spawnProxy; } // isSpawnProxy(): returns true if _proxy is _point's spawn proxy // function isSpawnProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].spawnProxy == _proxy); } // canSpawnAs(): true if _who is the owner or spawn proxy of _point // function canSpawnAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.spawnProxy) ) ); } // getSpawningForCount(): returns the amount of points _proxy // can spawn with // function getSpawningForCount(address _proxy) view external returns (uint256 count) { return spawningFor[_proxy].length; } // getSpawningFor(): get the points _proxy can spawn with // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getSpawningFor(address _proxy) view external returns (uint32[] sfor) { return spawningFor[_proxy]; } // voting proxy // getVotingProxy(): returns _point's current voting proxy // function getVotingProxy(uint32 _point) view external returns (address voter) { return rights[_point].votingProxy; } // isVotingProxy(): returns true if _proxy is _point's voting proxy // function isVotingProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].votingProxy == _proxy); } // canVoteAs(): true if _who is the owner of _point, // or the voting proxy of _point's owner // function canVoteAs(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.votingProxy) ) ); } // getVotingForCount(): returns the amount of points _proxy can vote as // function getVotingForCount(address _proxy) view external returns (uint256 count) { return votingFor[_proxy].length; } // getVotingFor(): returns the points _proxy can vote as // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getVotingFor(address _proxy) view external returns (uint32[] vfor) { return votingFor[_proxy]; } // transfer proxy // getTransferProxy(): returns _point's current transfer proxy // function getTransferProxy(uint32 _point) view external returns (address transferProxy) { return rights[_point].transferProxy; } // isTransferProxy(): returns true if _proxy is _point's transfer proxy // function isTransferProxy(uint32 _point, address _proxy) view external returns (bool result) { return (rights[_point].transferProxy == _proxy); } // canTransfer(): true if _who is the owner or transfer proxy of _point, // or is an operator for _point's current owner // function canTransfer(uint32 _point, address _who) view external returns (bool result) { Deed storage deed = rights[_point]; return ( (0x0 != _who) && ( (_who == deed.owner) || (_who == deed.transferProxy) || operators[deed.owner][_who] ) ); } // getTransferringForCount(): returns the amount of points _proxy // can transfer // function getTransferringForCount(address _proxy) view external returns (uint256 count) { return transferringFor[_proxy].length; } // getTransferringFor(): get the points _proxy can transfer // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getTransferringFor(address _proxy) view external returns (uint32[] tfor) { return transferringFor[_proxy]; } // isOperator(): returns true if _operator is allowed to transfer // ownership of _owner's points // function isOperator(address _owner, address _operator) view external returns (bool result) { return operators[_owner][_operator]; } // // Deed writing // // setOwner(): set owner of _point to _owner // // Note: setOwner() only implements the minimal data storage // logic for a transfer; the full transfer is implemented in // Ecliptic. // // Note: _owner must not be the zero address. // function setOwner(uint32 _point, address _owner) onlyOwner external { // prevent burning of points by making zero the owner // require(0x0 != _owner); // prev: previous owner, if any // address prev = rights[_point].owner; if (prev == _owner) { return; } // if the point used to have a different owner, do some gymnastics to // keep the list of owned points gapless. delete this point from the // list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous owner's list of owned points // uint256 i = pointOwnerIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :pointOwnerIndexes reference // uint32[] storage owner = pointsOwnedBy[prev]; uint256 last = owner.length - 1; uint32 moved = owner[last]; owner[i] = moved; pointOwnerIndexes[prev][moved] = i + 1; // delete the last item // delete(owner[last]); owner.length = last; pointOwnerIndexes[prev][_point] = 0; } // update the owner list and the owner's index list // rights[_point].owner = _owner; pointsOwnedBy[_owner].push(_point); pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length; emit OwnerChanged(_point, _owner); } // setManagementProxy(): makes _proxy _point's management proxy // function setManagementProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.managementProxy; if (prev == _proxy) { return; } // if the point used to have a different manager, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old manager's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous manager's list of managed points // uint256 i = managerForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :managerForIndexes reference // uint32[] storage prevMfor = managerFor[prev]; uint256 last = prevMfor.length - 1; uint32 moved = prevMfor[last]; prevMfor[i] = moved; managerForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevMfor[last]); prevMfor.length = last; managerForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage mfor = managerFor[_proxy]; mfor.push(_point); managerForIndexes[_proxy][_point] = mfor.length; } deed.managementProxy = _proxy; emit ChangedManagementProxy(_point, _proxy); } // setSpawnProxy(): makes _proxy _point's spawn proxy // function setSpawnProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.spawnProxy; if (prev == _proxy) { return; } // if the point used to have a different spawn proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of spawning points // uint256 i = spawningForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :spawningForIndexes reference // uint32[] storage prevSfor = spawningFor[prev]; uint256 last = prevSfor.length - 1; uint32 moved = prevSfor[last]; prevSfor[i] = moved; spawningForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevSfor[last]); prevSfor.length = last; spawningForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage sfor = spawningFor[_proxy]; sfor.push(_point); spawningForIndexes[_proxy][_point] = sfor.length; } deed.spawnProxy = _proxy; emit ChangedSpawnProxy(_point, _proxy); } // setVotingProxy(): makes _proxy _point's voting proxy // function setVotingProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.votingProxy; if (prev == _proxy) { return; } // if the point used to have a different voter, do some gymnastics // to keep the reverse lookup gapless. delete the point from the // old voter's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous voter's list of points it was // voting for // uint256 i = votingForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :votingForIndexes reference // uint32[] storage prevVfor = votingFor[prev]; uint256 last = prevVfor.length - 1; uint32 moved = prevVfor[last]; prevVfor[i] = moved; votingForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevVfor[last]); prevVfor.length = last; votingForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage vfor = votingFor[_proxy]; vfor.push(_point); votingForIndexes[_proxy][_point] = vfor.length; } deed.votingProxy = _proxy; emit ChangedVotingProxy(_point, _proxy); } // setManagementProxy(): makes _proxy _point's transfer proxy // function setTransferProxy(uint32 _point, address _proxy) onlyOwner external { Deed storage deed = rights[_point]; address prev = deed.transferProxy; if (prev == _proxy) { return; } // if the point used to have a different transfer proxy, do some // gymnastics to keep the reverse lookup gapless. delete the point // from the old proxy's list, then fill that gap with the list tail. // if (0x0 != prev) { // i: current index in previous proxy's list of transferable points // uint256 i = transferringForIndexes[prev][_point]; // we store index + 1, because 0 is the solidity default value // assert(i > 0); i--; // copy the last item in the list into the now-unused slot, // making sure to update its :transferringForIndexes reference // uint32[] storage prevTfor = transferringFor[prev]; uint256 last = prevTfor.length - 1; uint32 moved = prevTfor[last]; prevTfor[i] = moved; transferringForIndexes[prev][moved] = i + 1; // delete the last item // delete(prevTfor[last]); prevTfor.length = last; transferringForIndexes[prev][_point] = 0; } if (0x0 != _proxy) { uint32[] storage tfor = transferringFor[_proxy]; tfor.push(_point); transferringForIndexes[_proxy][_point] = tfor.length; } deed.transferProxy = _proxy; emit ChangedTransferProxy(_point, _proxy); } // setOperator(): dis/allow _operator to transfer ownership of all points // owned by _owner // // operators are part of the ERC721 standard // function setOperator(address _owner, address _operator, bool _approved) onlyOwner external { operators[_owner][_operator] = _approved; } } // Azimuth's ReadsAzimuth.sol // ReadsAzimuth: referring to and testing against the Azimuth // data contract // // To avoid needless repetition, this contract provides common // checks and operations using the Azimuth contract. // contract ReadsAzimuth { // azimuth: points data storage contract. // Azimuth public azimuth; // constructor(): set the Azimuth data contract's address // constructor(Azimuth _azimuth) public { azimuth = _azimuth; } // activePointOwner(): require that :msg.sender is the owner of _point, // and that _point is active // modifier activePointOwner(uint32 _point) { require( azimuth.isOwner(_point, msg.sender) && azimuth.isActive(_point) ); _; } // activePointManager(): require that :msg.sender can manage _point, // and that _point is active // modifier activePointManager(uint32 _point) { require( azimuth.canManage(_point, msg.sender) && azimuth.isActive(_point) ); _; } } // Azimuth's Polls.sol // Polls: proposals & votes data contract // // This contract is used for storing all data related to the proposals // of the senate (galaxy owners) and their votes on those proposals. // It keeps track of votes and uses them to calculate whether a majority // is in favor of a proposal. // // Every galaxy can only vote on a proposal exactly once. Votes cannot // be changed. If a proposal fails to achieve majority within its // duration, it can be restarted after its cooldown period has passed. // // The requirements for a proposal to achieve majority are as follows: // - At least 1/4 of the currently active voters (rounded down) must have // voted in favor of the proposal, // - More than half of the votes cast must be in favor of the proposal, // and this can no longer change, either because // - the poll duration has passed, or // - not enough voters remain to take away the in-favor majority. // As soon as these conditions are met, no further interaction with // the proposal is possible. Achieving majority is permanent. // // Since data stores are difficult to upgrade, all of the logic unrelated // to the voting itself (that is, determining who is eligible to vote) // is expected to be implemented by this contract's owner. // // This contract will be owned by the Ecliptic contract. // contract Polls is Ownable { using SafeMath for uint256; using SafeMath16 for uint16; using SafeMath8 for uint8; // UpgradePollStarted: a poll on :proposal has opened // event UpgradePollStarted(address proposal); // DocumentPollStarted: a poll on :proposal has opened // event DocumentPollStarted(bytes32 proposal); // UpgradeMajority: :proposal has achieved majority // event UpgradeMajority(address proposal); // DocumentMajority: :proposal has achieved majority // event DocumentMajority(bytes32 proposal); // Poll: full poll state // struct Poll { // start: the timestamp at which the poll was started // uint256 start; // voted: per galaxy, whether they have voted on this poll // bool[256] voted; // yesVotes: amount of votes in favor of the proposal // uint16 yesVotes; // noVotes: amount of votes against the proposal // uint16 noVotes; // duration: amount of time during which the poll can be voted on // uint256 duration; // cooldown: amount of time before the (non-majority) poll can be reopened // uint256 cooldown; } // pollDuration: duration set for new polls. see also Poll.duration above // uint256 public pollDuration; // pollCooldown: cooldown set for new polls. see also Poll.cooldown above // uint256 public pollCooldown; // totalVoters: amount of active galaxies // uint16 public totalVoters; // upgradeProposals: list of all upgrades ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // address[] public upgradeProposals; // upgradePolls: per address, poll held to determine if that address // will become the new ecliptic // mapping(address => Poll) public upgradePolls; // upgradeHasAchievedMajority: per address, whether that address // has ever achieved majority // // If we did not store this, we would have to look at old poll data // to see whether or not a proposal has ever achieved majority. // Since the outcome of a poll is calculated based on :totalVoters, // which may not be consistent across time, we need to store outcomes // explicitly instead of re-calculating them. This allows us to always // tell with certainty whether or not a majority was achieved, // regardless of the current :totalVoters. // mapping(address => bool) public upgradeHasAchievedMajority; // documentProposals: list of all documents ever proposed // // this allows clients to discover the existence of polls. // from there, they can do liveness checks on the polls themselves. // bytes32[] public documentProposals; // documentPolls: per hash, poll held to determine if the corresponding // document is accepted by the galactic senate // mapping(bytes32 => Poll) public documentPolls; // documentHasAchievedMajority: per hash, whether that hash has ever // achieved majority // // the note for upgradeHasAchievedMajority above applies here as well // mapping(bytes32 => bool) public documentHasAchievedMajority; // documentMajorities: all hashes that have achieved majority // bytes32[] public documentMajorities; // constructor(): initial contract configuration // constructor(uint256 _pollDuration, uint256 _pollCooldown) public { reconfigure(_pollDuration, _pollCooldown); } // reconfigure(): change poll duration and cooldown // function reconfigure(uint256 _pollDuration, uint256 _pollCooldown) public onlyOwner { require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) && (5 days <= _pollCooldown) && (_pollCooldown <= 90 days) ); pollDuration = _pollDuration; pollCooldown = _pollCooldown; } // incrementTotalVoters(): increase the amount of registered voters // function incrementTotalVoters() external onlyOwner { require(totalVoters < 256); totalVoters = totalVoters.add(1); } // getAllUpgradeProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getUpgradeProposals() external view returns (address[] proposals) { return upgradeProposals; } // getUpgradeProposalCount(): get the number of unique proposed upgrades // function getUpgradeProposalCount() external view returns (uint256 count) { return upgradeProposals.length; } // getAllDocumentProposals(): return array of all upgrade proposals ever made // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentProposals() external view returns (bytes32[] proposals) { return documentProposals; } // getDocumentProposalCount(): get the number of unique proposed upgrades // function getDocumentProposalCount() external view returns (uint256 count) { return documentProposals.length; } // getDocumentMajorities(): return array of all document majorities // // Note: only useful for clients, as Solidity does not currently // support returning dynamic arrays. // function getDocumentMajorities() external view returns (bytes32[] majorities) { return documentMajorities; } // hasVotedOnUpgradePoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal) external view returns (bool result) { return upgradePolls[_proposal].voted[_galaxy]; } // hasVotedOnDocumentPoll(): returns true if _galaxy has voted // on the _proposal // function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal) external view returns (bool result) { return documentPolls[_proposal].voted[_galaxy]; } // startUpgradePoll(): open a poll on making _proposal the new ecliptic // function startUpgradePoll(address _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); Poll storage poll = upgradePolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { upgradeProposals.push(_proposal); } startPoll(poll); emit UpgradePollStarted(_proposal); } // startDocumentPoll(): open a poll on accepting the document // whose hash is _proposal // function startDocumentPoll(bytes32 _proposal) external onlyOwner { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); Poll storage poll = documentPolls[_proposal]; // if the proposal is being made for the first time, register it. // if (0 == poll.start) { documentProposals.push(_proposal); } startPoll(poll); emit DocumentPollStarted(_proposal); } // startPoll(): open a new poll, or re-open an old one // function startPoll(Poll storage _poll) internal { // check that the poll has cooled down enough to be started again // // for completely new polls, the values used will be zero // require( block.timestamp > ( _poll.start.add( _poll.duration.add( _poll.cooldown )) ) ); // set started poll state // _poll.start = block.timestamp; delete _poll.voted; _poll.yesVotes = 0; _poll.noVotes = 0; _poll.duration = pollDuration; _poll.cooldown = pollCooldown; } // castUpgradeVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castUpgradeVote(uint8 _as, address _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = upgradePolls[_proposal]; processVote(poll, _as, _vote); return updateUpgradePoll(_proposal); } // castDocumentVote(): as galaxy _as, cast a vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote) external onlyOwner returns (bool majority) { Poll storage poll = documentPolls[_proposal]; processVote(poll, _as, _vote); return updateDocumentPoll(_proposal); } // processVote(): record a vote from _as on the _poll // function processVote(Poll storage _poll, uint8 _as, bool _vote) internal { // assist symbolic execution tools // assert(block.timestamp >= _poll.start); require( // may only vote once // !_poll.voted[_as] && // // may only vote when the poll is open // (block.timestamp < _poll.start.add(_poll.duration)) ); // update poll state to account for the new vote // _poll.voted[_as] = true; if (_vote) { _poll.yesVotes = _poll.yesVotes.add(1); } else { _poll.noVotes = _poll.noVotes.add(1); } } // updateUpgradePoll(): check whether the _proposal has achieved // majority, updating state, sending an event, // and returning true if it has // function updateUpgradePoll(address _proposal) public onlyOwner returns (bool majority) { // _proposal must not have achieved majority before // require(!upgradeHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = upgradePolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update the state and send an event // if (majority) { upgradeHasAchievedMajority[_proposal] = true; emit UpgradeMajority(_proposal); } return majority; } // updateDocumentPoll(): check whether the _proposal has achieved majority, // updating the state and sending an event if it has // // this can be called by anyone, because the ecliptic does not // need to be aware of the result // function updateDocumentPoll(bytes32 _proposal) public returns (bool majority) { // _proposal must not have achieved majority before // require(!documentHasAchievedMajority[_proposal]); // check for majority in the poll // Poll storage poll = documentPolls[_proposal]; majority = checkPollMajority(poll); // if majority was achieved, update state and send an event // if (majority) { documentHasAchievedMajority[_proposal] = true; documentMajorities.push(_proposal); emit DocumentMajority(_proposal); } return majority; } // checkPollMajority(): returns true if the majority is in favor of // the subject of the poll // function checkPollMajority(Poll _poll) internal view returns (bool majority) { return ( // poll must have at least the minimum required yes-votes // (_poll.yesVotes >= (totalVoters / 4)) && // // and have a majority... // (_poll.yesVotes > _poll.noVotes) && // // ...that is indisputable // ( // either because the poll has ended // (block.timestamp > _poll.start.add(_poll.duration)) || // // or there are more yes votes than there can be no votes // ( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) ); } } // Azimuth's Claims.sol // Claims: simple identity management // // This contract allows points to document claims about their owner. // Most commonly, these are about identity, with a claim's protocol // defining the context or platform of the claim, and its dossier // containing proof of its validity. // Points are limited to a maximum of 16 claims. // // For existing claims, the dossier can be updated, or the claim can // be removed entirely. It is recommended to remove any claims associated // with a point when it is about to be transferred to a new owner. // For convenience, the owner of the Azimuth contract (the Ecliptic) // is allowed to clear claims for any point, allowing it to do this for // you on-transfer. // contract Claims is ReadsAzimuth { // ClaimAdded: a claim was added by :by // event ClaimAdded( uint32 indexed by, string _protocol, string _claim, bytes _dossier ); // ClaimRemoved: a claim was removed by :by // event ClaimRemoved(uint32 indexed by, string _protocol, string _claim); // maxClaims: the amount of claims that can be registered per point // uint8 constant maxClaims = 16; // Claim: claim details // struct Claim { // protocol: context of the claim // string protocol; // claim: the claim itself // string claim; // dossier: data relating to the claim, as proof // bytes dossier; } // per point, list of claims // mapping(uint32 => Claim[maxClaims]) public claims; // constructor(): register the azimuth contract. // constructor(Azimuth _azimuth) ReadsAzimuth(_azimuth) public { // } // addClaim(): register a claim as _point // function addClaim(uint32 _point, string _protocol, string _claim, bytes _dossier) external activePointManager(_point) { // cur: index + 1 of the claim if it already exists, 0 otherwise // uint8 cur = findClaim(_point, _protocol, _claim); // if the claim doesn't yet exist, store it in state // if (cur == 0) { // if there are no empty slots left, this throws // uint8 empty = findEmptySlot(_point); claims[_point][empty] = Claim(_protocol, _claim, _dossier); } // // if the claim has been made before, update the version in state // else { claims[_point][cur-1] = Claim(_protocol, _claim, _dossier); } emit ClaimAdded(_point, _protocol, _claim, _dossier); } // removeClaim(): unregister a claim as _point // function removeClaim(uint32 _point, string _protocol, string _claim) external activePointManager(_point) { // i: current index + 1 in _point's list of claims // uint256 i = findClaim(_point, _protocol, _claim); // we store index + 1, because 0 is the eth default value // can only delete an existing claim // require(i > 0); i--; // clear out the claim // delete claims[_point][i]; emit ClaimRemoved(_point, _protocol, _claim); } // clearClaims(): unregister all of _point's claims // // can also be called by the ecliptic during point transfer // function clearClaims(uint32 _point) external { // both point owner and ecliptic may do this // // We do not necessarily need to check for _point's active flag here, // since inactive points cannot have claims set. Doing the check // anyway would make this function slightly harder to think about due // to its relation to Ecliptic's transferPoint(). // require( azimuth.canManage(_point, msg.sender) || ( msg.sender == azimuth.owner() ) ); Claim[maxClaims] storage currClaims = claims[_point]; // clear out all claims // for (uint8 i = 0; i < maxClaims; i++) { delete currClaims[i]; } } // findClaim(): find the index of the specified claim // // returns 0 if not found, index + 1 otherwise // function findClaim(uint32 _whose, string _protocol, string _claim) public view returns (uint8 index) { // we use hashes of the string because solidity can't do string // comparison yet // bytes32 protocolHash = keccak256(bytes(_protocol)); bytes32 claimHash = keccak256(bytes(_claim)); Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) && ( claimHash == keccak256(bytes(thisClaim.claim)) ) ) { return i+1; } } return 0; } // findEmptySlot(): find the index of the first empty claim slot // // returns the index of the slot, throws if there are no empty slots // function findEmptySlot(uint32 _whose) internal view returns (uint8 index) { Claim[maxClaims] storage theirClaims = claims[_whose]; for (uint8 i = 0; i < maxClaims; i++) { Claim storage thisClaim = theirClaims[i]; if ( (0 == bytes(thisClaim.protocol).length) && (0 == bytes(thisClaim.claim).length) ) { return i; } } revert(); } } // Azimuth's EclipticBase.sol // EclipticBase: upgradable ecliptic // // This contract implements the upgrade logic for the Ecliptic. // Newer versions of the Ecliptic are expected to provide at least // the onUpgrade() function. If they don't, upgrading to them will // fail. // // Note that even though this contract doesn't specify any required // interface members aside from upgrade() and onUpgrade(), contracts // and clients may still rely on the presence of certain functions // provided by the Ecliptic proper. Keep this in mind when writing // new versions of it. // contract EclipticBase is Ownable, ReadsAzimuth { // Upgraded: _to is the new canonical Ecliptic // event Upgraded(address to); // polls: senate voting contract // Polls public polls; // previousEcliptic: address of the previous ecliptic this // instance expects to upgrade from, stored and // checked for to prevent unexpected upgrade paths // address public previousEcliptic; constructor( address _previous, Azimuth _azimuth, Polls _polls ) ReadsAzimuth(_azimuth) internal { previousEcliptic = _previous; polls = _polls; } // onUpgrade(): called by previous ecliptic when upgrading // // in future ecliptics, this might perform more logic than // just simple checks and verifications. // when overriding this, make sure to call this original as well. // function onUpgrade() external { // make sure this is the expected upgrade path, // and that we have gotten the ownership we require // require( msg.sender == previousEcliptic && this == azimuth.owner() && this == polls.owner() ); } // upgrade(): transfer ownership of the ecliptic data to the new // ecliptic contract, notify it, then self-destruct. // // Note: any eth that have somehow ended up in this contract // are also sent to the new ecliptic. // function upgrade(EclipticBase _new) internal { // transfer ownership of the data contracts // azimuth.transferOwnership(_new); polls.transferOwnership(_new); // trigger upgrade logic on the target contract // _new.onUpgrade(); // emit event and destroy this contract // emit Upgraded(_new); selfdestruct(_new); } } // Azimuth's Ecliptic // Ecliptic: logic for interacting with the Azimuth ledger // // This contract is the point of entry for all operations on the Azimuth // ledger as stored in the Azimuth data contract. The functions herein // are responsible for performing all necessary business logic. // Examples of such logic include verifying permissions of the caller // and ensuring a requested change is actually valid. // Point owners can always operate on their own points. Ethereum addresses // can also perform specific operations if they've been given the // appropriate permissions. (For example, managers for general management, // spawn proxies for spawning child points, etc.) // // This contract uses external contracts (Azimuth, Polls) for data storage // so that it itself can easily be replaced in case its logic needs to // be changed. In other words, it can be upgraded. It does this by passing // ownership of the data contracts to a new Ecliptic contract. // // Because of this, it is advised for clients to not store this contract's // address directly, but rather ask the Azimuth contract for its owner // attribute to ensure transactions get sent to the latest Ecliptic. // Alternatively, the ENS name ecliptic.eth will resolve to the latest // Ecliptic as well. // // Upgrading happens based on polls held by the senate (galaxy owners). // Through this contract, the senate can submit proposals, opening polls // for the senate to cast votes on. These proposals can be either hashes // of documents or addresses of new Ecliptics. // If an ecliptic proposal gains majority, this contract will transfer // ownership of the data storage contracts to that address, so that it may // operate on the data they contain. This contract will selfdestruct at // the end of the upgrade process. // // This contract implements the ERC721 interface for non-fungible tokens, // allowing points to be managed using generic clients that support the // standard. It also implements ERC165 to allow this to be discovered. // contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata { using SafeMath for uint256; using AddressUtils for address; // Transfer: This emits when ownership of any NFT changes by any mechanism. // This event emits when NFTs are created (`from` == 0) and // destroyed (`to` == 0). At the time of any transfer, the // approved address for that NFT (if any) is reset to none. // event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); // Approval: This emits when the approved address for an NFT is changed or // reaffirmed. The zero address indicates there is no approved // address. When a Transfer event emits, this also indicates that // the approved address for that NFT (if any) is reset to none. // event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // ApprovalForAll: This emits when an operator is enabled or disabled for an // owner. The operator can manage all NFTs of the owner. // event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // erc721Received: equal to: // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) // which can be also obtained as: // ERC721Receiver(0).onERC721Received.selector` bytes4 constant erc721Received = 0x150b7a02; // claims: contract reference, for clearing claims on-transfer // Claims public claims; // constructor(): set data contract addresses and signal interface support // // Note: during first deploy, ownership of these data contracts must // be manually transferred to this contract. // constructor(address _previous, Azimuth _azimuth, Polls _polls, Claims _claims) EclipticBase(_previous, _azimuth, _polls) public { claims = _claims; // register supported interfaces for ERC165 // _registerInterface(0x80ac58cd); // ERC721 _registerInterface(0x5b5e139f); // ERC721Metadata _registerInterface(0x7f5828d0); // ERC173 (ownership) } // // ERC721 interface // // balanceOf(): get the amount of points owned by _owner // function balanceOf(address _owner) public view returns (uint256 balance) { require(0x0 != _owner); return azimuth.getOwnedPointCount(_owner); } // ownerOf(): get the current owner of point _tokenId // function ownerOf(uint256 _tokenId) public view validPointId(_tokenId) returns (address owner) { uint32 id = uint32(_tokenId); // this will throw if the owner is the zero address, // active points always have a valid owner. // require(azimuth.isActive(id)); return azimuth.getOwner(id); } // exists(): returns true if point _tokenId is active // function exists(uint256 _tokenId) public view returns (bool doesExist) { return ( (_tokenId < 0x100000000) && azimuth.isActive(uint32(_tokenId)) ); } // safeTransferFrom(): transfer point _tokenId from _from to _to // function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { // transfer with empty data // safeTransferFrom(_from, _to, _tokenId, ""); } // safeTransferFrom(): transfer point _tokenId from _from to _to, // and call recipient if it's a contract // function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { // perform raw transfer // transferFrom(_from, _to, _tokenId); // do the callback last to avoid re-entrancy // if (_to.isContract()) { bytes4 retval = ERC721Receiver(_to) .onERC721Received(msg.sender, _from, _tokenId, _data); // // standard return idiom to confirm contract semantics // require(retval == erc721Received); } } // transferFrom(): transfer point _tokenId from _from to _to, // WITHOUT notifying recipient contract // function transferFrom(address _from, address _to, uint256 _tokenId) public validPointId(_tokenId) { uint32 id = uint32(_tokenId); require(azimuth.isOwner(id, _from)); // the ERC721 operator/approved address (if any) is // accounted for in transferPoint() // transferPoint(id, _to, true); } // approve(): allow _approved to transfer ownership of point // _tokenId // function approve(address _approved, uint256 _tokenId) public validPointId(_tokenId) { setTransferProxy(uint32(_tokenId), _approved); } // setApprovalForAll(): allow or disallow _operator to // transfer ownership of ALL points // owned by :msg.sender // function setApprovalForAll(address _operator, bool _approved) public { require(0x0 != _operator); azimuth.setOperator(msg.sender, _operator, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } // getApproved(): get the approved address for point _tokenId // function getApproved(uint256 _tokenId) public view validPointId(_tokenId) returns (address approved) { //NOTE redundant, transfer proxy cannot be set for // inactive points // require(azimuth.isActive(uint32(_tokenId))); return azimuth.getTransferProxy(uint32(_tokenId)); } // isApprovedForAll(): returns true if _operator is an // operator for _owner // function isApprovedForAll(address _owner, address _operator) public view returns (bool result) { return azimuth.isOperator(_owner, _operator); } // // ERC721Metadata interface // // name(): returns the name of a collection of points // function name() external view returns (string) { return "Azimuth Points"; } // symbol(): returns an abbreviates name for points // function symbol() external view returns (string) { return "AZP"; } // tokenURI(): returns a URL to an ERC-721 standard JSON file // function tokenURI(uint256 _tokenId) public view validPointId(_tokenId) returns (string _tokenURI) { _tokenURI = "https://azimuth.network/erc721/0000000000.json"; bytes memory _tokenURIBytes = bytes(_tokenURI); _tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10); _tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10); _tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10); _tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10); _tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10); _tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10); _tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10); _tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10); _tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10); _tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10); } // // Points interface // // configureKeys(): configure _point with network public keys // _encryptionKey, _authenticationKey, // and corresponding _cryptoSuiteVersion, // incrementing the point's continuity number if needed // function configureKeys(uint32 _point, bytes32 _encryptionKey, bytes32 _authenticationKey, uint32 _cryptoSuiteVersion, bool _discontinuous) external activePointManager(_point) { if (_discontinuous) { azimuth.incrementContinuityNumber(_point); } azimuth.setKeys(_point, _encryptionKey, _authenticationKey, _cryptoSuiteVersion); } // spawn(): spawn _point, then either give, or allow _target to take, // ownership of _point // // if _target is the :msg.sender, _targets owns the _point right away. // otherwise, _target becomes the transfer proxy of _point. // // Requirements: // - _point must not be active // - _point must not be a planet with a galaxy prefix // - _point's prefix must be linked and under its spawn limit // - :msg.sender must be either the owner of _point's prefix, // or an authorized spawn proxy for it // function spawn(uint32 _point, address _target) external { // only currently unowned (and thus also inactive) points can be spawned // require(azimuth.isOwner(_point, 0x0)); // prefix: half-width prefix of _point // uint16 prefix = azimuth.getPrefix(_point); // only allow spawning of points of the size directly below the prefix // // this is possible because of how the address space works, // but supporting it introduces complexity through broken assumptions. // // example: // 0x0000.0000 - galaxy zero // 0x0000.0100 - the first star of galaxy zero // 0x0001.0100 - the first planet of the first star // 0x0001.0000 - the first planet of galaxy zero // require( (uint8(azimuth.getPointSize(prefix)) + 1) == uint8(azimuth.getPointSize(_point)) ); // prefix point must be linked and able to spawn // require( (azimuth.hasBeenLinked(prefix)) && ( azimuth.getSpawnCount(prefix) < getSpawnLimit(prefix, block.timestamp) ) ); // the owner of a prefix can always spawn its children; // other addresses need explicit permission (the role // of "spawnProxy" in the Azimuth contract) // require( azimuth.canSpawnAs(prefix, msg.sender) ); // if the caller is spawning the point to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_point, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern // making the _point prefix's owner the _point owner in the mean time // else { doSpawn(_point, _target, false, azimuth.getOwner(prefix)); } } // doSpawn(): actual spawning logic, used in spawn(). creates _point, // making the _target its owner if _direct, or making the // _holder the owner and the _target the transfer proxy // if not _direct. // function doSpawn( uint32 _point, address _target, bool _direct, address _holder ) internal { // register the spawn for _point's prefix, incrementing spawn count // azimuth.registerSpawned(_point); // if the spawn is _direct, assume _target knows what they're doing // and resolve right away // if (_direct) { // make the point active and set its new owner // azimuth.activatePoint(_point); azimuth.setOwner(_point, _target); emit Transfer(0x0, _target, uint256(_point)); } // // when spawning indirectly, enforce a withdraw pattern by approving // the _target for transfer of the _point instead. // we make the _holder the owner of this _point in the mean time, // so that it may cancel the transfer (un-approve) if _target flakes. // we don't make _point active yet, because it still doesn't really // belong to anyone. // else { // have _holder hold on to the _point while _target gets to transfer // ownership of it // azimuth.setOwner(_point, _holder); azimuth.setTransferProxy(_point, _target); emit Transfer(0x0, _holder, uint256(_point)); emit Approval(_holder, _target, uint256(_point)); } } // transferPoint(): transfer _point to _target, clearing all permissions // data and keys if _reset is true // // Note: the _reset flag is useful when transferring the point to // a recipient who doesn't trust the previous owner. // // Requirements: // - :msg.sender must be either _point's current owner, authorized // to transfer _point, or authorized to transfer the current // owner's points (as in ERC721's operator) // - _target must not be the zero address // function transferPoint(uint32 _point, address _target, bool _reset) public { // transfer is legitimate if the caller is the current owner, or // an operator for the current owner, or the _point's transfer proxy // require(azimuth.canTransfer(_point, msg.sender)); // if the point wasn't active yet, that means transferring it // is part of the "spawn" flow, so we need to activate it // if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } // if the owner would actually change, change it // // the only time this deliberately wouldn't be the case is when a // prefix owner wants to activate a spawned but untransferred child. // if ( !azimuth.isOwner(_point, _target) ) { // remember the previous owner, to be included in the Transfer event // address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); // according to ERC721, the approved address (here, transfer proxy) // gets cleared during every Transfer event // azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } // reset sensitive data // used when transferring the point to a new owner // if ( _reset ) { // clear the network public keys and break continuity, // but only if the point has already been linked // if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } // clear management proxy // azimuth.setManagementProxy(_point, 0); // clear voting proxy // azimuth.setVotingProxy(_point, 0); // clear transfer proxy // // in most cases this is done above, during the ownership transfer, // but we might not hit that and still be expected to reset the // transfer proxy. // doing it a second time is a no-op in Azimuth. // azimuth.setTransferProxy(_point, 0); // clear spawning proxy // azimuth.setSpawnProxy(_point, 0); // clear claims // claims.clearClaims(_point); } } // escape(): request escape as _point to _sponsor // // if an escape request is already active, this overwrites // the existing request // // Requirements: // - :msg.sender must be the owner or manager of _point, // - _point must be able to escape to _sponsor as per to canEscapeTo() // function escape(uint32 _point, uint32 _sponsor) external activePointManager(_point) { require(canEscapeTo(_point, _sponsor)); azimuth.setEscapeRequest(_point, _sponsor); } // cancelEscape(): cancel the currently set escape for _point // function cancelEscape(uint32 _point) external activePointManager(_point) { azimuth.cancelEscape(_point); } // adopt(): as the relevant sponsor, accept the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function adopt(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); // _sponsor becomes _point's sponsor // its escape request is reset to "not escaping" // azimuth.doEscape(_point); } // reject(): as the relevant sponsor, deny the _point's request // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's requested sponsor // function reject(uint32 _point) external { require( azimuth.isEscaping(_point) && azimuth.canManage( azimuth.getEscapeRequest(_point), msg.sender ) ); // reset the _point's escape request to "not escaping" // azimuth.cancelEscape(_point); } // detach(): as the _sponsor, stop sponsoring the _point // // Requirements: // - :msg.sender must be the owner or management proxy // of _point's current sponsor // function detach(uint32 _point) external { require( azimuth.hasSponsor(_point) && azimuth.canManage(azimuth.getSponsor(_point), msg.sender) ); // signal that its sponsor no longer supports _point // azimuth.loseSponsor(_point); } // // Point rules // // getSpawnLimit(): returns the total number of children the _point // is allowed to spawn at _time. // function getSpawnLimit(uint32 _point, uint256 _time) public view returns (uint32 limit) { Azimuth.Size size = azimuth.getPointSize(_point); if ( size == Azimuth.Size.Galaxy ) { return 255; } else if ( size == Azimuth.Size.Star ) { // in 2019, stars may spawn at most 1024 planets. this limit doubles // for every subsequent year. // // Note: 1546300800 corresponds to 2019-01-01 // uint256 yearsSince2019 = (_time - 1546300800) / 365 days; if (yearsSince2019 < 6) { limit = uint32( 1024 * (2 ** yearsSince2019) ); } else { limit = 65535; } return limit; } else // size == Azimuth.Size.Planet { // planets can create moons, but moons aren't on the chain // return 0; } } // canEscapeTo(): true if _point could try to escape to _sponsor // function canEscapeTo(uint32 _point, uint32 _sponsor) public view returns (bool canEscape) { // can't escape to a sponsor that hasn't been linked // if ( !azimuth.hasBeenLinked(_sponsor) ) return false; // Can only escape to a point one size higher than ourselves, // except in the special case where the escaping point hasn't // been linked yet -- in that case we may escape to points of // the same size, to support lightweight invitation chains. // // The use case for lightweight invitations is that a planet // owner should be able to invite their friends onto an // Azimuth network in a two-party transaction, without a new // star relationship. // The lightweight invitation process works by escaping your // own active (but never linked) point to one of your own // points, then transferring the point to your friend. // // These planets can, in turn, sponsor other unlinked planets, // so the "planet sponsorship chain" can grow to arbitrary // length. Most users, especially deep down the chain, will // want to improve their performance by switching to direct // star sponsors eventually. // Azimuth.Size pointSize = azimuth.getPointSize(_point); Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor); return ( // normal hierarchical escape structure // ( (uint8(sponsorSize) + 1) == uint8(pointSize) ) || // // special peer escape // ( (sponsorSize == pointSize) && // // peer escape is only for points that haven't been linked // yet, because it's only for lightweight invitation chains // !azimuth.hasBeenLinked(_point) ) ); } // // Permission management // // setManagementProxy(): configure the management proxy for _point // // The management proxy may perform "reversible" operations on // behalf of the owner. This includes public key configuration and // operations relating to sponsorship. // function setManagementProxy(uint32 _point, address _manager) external activePointOwner(_point) { azimuth.setManagementProxy(_point, _manager); } // setSpawnProxy(): give _spawnProxy the right to spawn points // with the prefix _prefix // function setSpawnProxy(uint16 _prefix, address _spawnProxy) external activePointOwner(_prefix) { azimuth.setSpawnProxy(_prefix, _spawnProxy); } // setVotingProxy(): configure the voting proxy for _galaxy // // the voting proxy is allowed to start polls and cast votes // on the point's behalf. // function setVotingProxy(uint8 _galaxy, address _voter) external activePointOwner(_galaxy) { azimuth.setVotingProxy(_galaxy, _voter); } // setTransferProxy(): give _transferProxy the right to transfer _point // // Requirements: // - :msg.sender must be either _point's current owner, // or be an operator for the current owner // function setTransferProxy(uint32 _point, address _transferProxy) public { // owner: owner of _point // address owner = azimuth.getOwner(_point); // caller must be :owner, or an operator designated by the owner. // require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender)); // set transfer proxy field in Azimuth contract // azimuth.setTransferProxy(_point, _transferProxy); // emit Approval event // emit Approval(owner, _transferProxy, uint256(_point)); } // // Poll actions // // startUpgradePoll(): as _galaxy, start a poll for the ecliptic // upgrade _proposal // // Requirements: // - :msg.sender must be the owner or voting proxy of _galaxy, // - the _proposal must expect to be upgraded from this specific // contract, as indicated by its previousEcliptic attribute // function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal) external activePointVoter(_galaxy) { // ensure that the upgrade target expects this contract as the source // require(_proposal.previousEcliptic() == address(this)); polls.startUpgradePoll(_proposal); } // startDocumentPoll(): as _galaxy, start a poll for the _proposal // // the _proposal argument is the keccak-256 hash of any arbitrary // document or string of text // function startDocumentPoll(uint8 _galaxy, bytes32 _proposal) external activePointVoter(_galaxy) { polls.startDocumentPoll(_proposal); } // castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic // upgrade _proposal // // _vote is true when in favor of the proposal, false otherwise // // If this vote results in a majority for the _proposal, it will // be upgraded to immediately. // function castUpgradeVote(uint8 _galaxy, EclipticBase _proposal, bool _vote) external activePointVoter(_galaxy) { // majority: true if the vote resulted in a majority, false otherwise // bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // castDocumentVote(): as _galaxy, cast a _vote on the _proposal // // _vote is true when in favor of the proposal, false otherwise // function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote) external activePointVoter(_galaxy) { polls.castDocumentVote(_galaxy, _proposal, _vote); } // updateUpgradePoll(): check whether the _proposal has achieved // majority, upgrading to it if it has // function updateUpgradePoll(EclipticBase _proposal) external { // majority: true if the poll ended in a majority, false otherwise // bool majority = polls.updateUpgradePoll(_proposal); // if a majority is in favor of the upgrade, it happens as defined // in the ecliptic base contract // if (majority) { upgrade(_proposal); } } // updateDocumentPoll(): check whether the _proposal has achieved majority // // Note: the polls contract publicly exposes the function this calls, // but we offer it in the ecliptic interface as a convenience // function updateDocumentPoll(bytes32 _proposal) external { polls.updateDocumentPoll(_proposal); } // // Contract owner operations // // createGalaxy(): grant _target ownership of the _galaxy and register // it for voting // function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { // only currently unowned (and thus also inactive) galaxies can be // created, and only to non-zero addresses // require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); // new galaxy means a new registered voter // polls.incrementTotalVoters(); // if the caller is sending the galaxy to themselves, // assume it knows what it's doing and resolve right away // if (msg.sender == _target) { doSpawn(_galaxy, _target, true, 0x0); } // // when sending to a "foreign" address, enforce a withdraw pattern, // making the caller the owner in the mean time // else { doSpawn(_galaxy, _target, false, msg.sender); } } function setDnsDomains(string _primary, string _secondary, string _tertiary) external onlyOwner { azimuth.setDnsDomains(_primary, _secondary, _tertiary); } // // Function modifiers for this contract // // validPointId(): require that _id is a valid point // modifier validPointId(uint256 _id) { require(_id < 0x100000000); _; } // activePointVoter(): require that :msg.sender can vote as _point, // and that _point is active // modifier activePointVoter(uint32 _point) { require( azimuth.canVoteAs(_point, msg.sender) && azimuth.isActive(_point) ); _; } } //////////////////////////////////////////////////////////////////////////////// // DelegatedSending //////////////////////////////////////////////////////////////////////////////// // DelegatedSending: invite-like point sending // // This contract allows planet owners to gift planets to their friends, // if their prefix has allowed it. // // Star owners can set a limit, the amount of "invite planets" each of // their planets is allowed to send. Enabling this by setting the limit // to a value higher than zero can help the network grow by providing // regular users with a way to get their friends and family onto it. // // To allow planets to be sent by this contract, stars must set it as // their spawnProxy using the Ecliptic. // contract DelegatedSending is ReadsAzimuth { // Sent: :by sent :point // event Sent( uint16 indexed prefix, uint64 indexed fromPool, uint32 by, uint32 point, address to); // limits: per star, the maximum amount of planets any of its planets may // give away // mapping(uint16 => uint16) public limits; // pools: per pool, the amount of planets that have been given away by // the pool's planet itself or the ones it invited // // pools are associated with planets by number, pool n belongs to // planet n - 1. // pool 0 does not exist, and is used symbolically by :fromPool. // mapping(uint64 => uint16) public pools; // fromPool: per planet, the pool from which they were sent/invited // // when invited by planet n, the invitee is registered in pool n + 1. // a pool of 0 means the planet has its own invite pool. // this is done so that all planets that were born outside of this // contract start out with their own pool (0, solidity default), // while we configure planets created through this contract to use // their inviter's pool. // mapping(uint32 => uint64) public fromPool; // constructor(): register the azimuth contract // constructor(Azimuth _azimuth) ReadsAzimuth(_azimuth) public { // } // configureLimit(): as the owner of a star, configure the amount of // planets that may be given away per point. // function configureLimit(uint16 _prefix, uint16 _limit) external activePointOwner(_prefix) { limits[_prefix] = _limit; } // resetPool(): grant _for their own invite pool in case they still // share one and reset its counter to zero // function resetPool(uint32 _for) external activePointOwner(azimuth.getPrefix(_for)) { fromPool[_for] = 0; pools[uint64(_for) + 1] = 0; } // sendPoint(): as the point _as, spawn the point _point to _to. // // Requirements: // - :msg.sender must be the owner of _as, // - _to must not be the :msg.sender, // - _as must be able to send the _point according to canSend() // function sendPoint(uint32 _as, uint32 _point, address _to) external activePointOwner(_as) { require(canSend(_as, _point)); // caller may not send to themselves // require(msg.sender != _to); // recipient must be eligible to receive a planet from this contract // require(canReceive(_to)); // increment the sent counter for _as. // uint64 pool = getPool(_as); pools[pool]++; // associate the _point with this pool // fromPool[_point] = pool; // spawn _point to _to, they still need to accept the transfer manually // Ecliptic(azimuth.owner()).spawn(_point, _to); emit Sent(azimuth.getPrefix(_point), pool, _as, _point, _to); } // canSend(): check whether current conditions allow _as to send _point // function canSend(uint32 _as, uint32 _point) public view returns (bool result) { uint16 prefix = azimuth.getPrefix(_as); uint64 pool = getPool(_as); return ( // can only send points with the same prefix // (prefix == azimuth.getPrefix(_point)) && // // _as must not have hit the allowed limit yet // (pools[pool] < limits[prefix]) && // // _point needs to not be (in the process of being) spawned // azimuth.isOwner(_point, 0x0) && // // this contract must have permission to spawn points // azimuth.isSpawnProxy(prefix, this) && // // the prefix must be linked // azimuth.hasBeenLinked(prefix) && // // the prefix must not have hit its spawn limit yet // ( azimuth.getSpawnCount(prefix) < Ecliptic(azimuth.owner()) .getSpawnLimit(prefix, block.timestamp) ) ); } // getPool(): get the invite pool _point belongs to // function getPool(uint32 _point) internal view returns (uint64 pool) { pool = fromPool[_point]; // no pool explicitly registered means they have their own pool, // because they either were not invited by this contract, or have // been granted their own pool by their star. // if (0 == pool) { // the pool for planet n is n + 1, see also :fromPool // return uint64(_point) + 1; } return pool; } // canReceive(): whether the _recipient is eligible to receive a planet // from this contract or not // // only those who don't own or are entitled to any points may receive // function canReceive(address _recipient) public view returns (bool result) { return ( 0 == azimuth.getOwnedPointCount(_recipient) && 0 == azimuth.getTransferringForCount(_recipient) ); } }
transferPoint(): transfer _point to _target, clearing all permissions data and keys if _reset is true Note: the _reset flag is useful when transferring the point to a recipient who doesn't trust the previous owner. Requirements: - :msg.sender must be either _point's current owner, authorized to transfer _point, or authorized to transfer the current owner's points (as in ERC721's operator) - _target must not be the zero address transfer is legitimate if the caller is the current owner, or an operator for the current owner, or the _point's transfer proxy if the point wasn't active yet, that means transferring it is part of the "spawn" flow, so we need to activate it remember the previous owner, to be included in the Transfer event according to ERC721, the approved address (here, transfer proxy) gets cleared during every Transfer event clear the network public keys and break continuity, but only if the point has already been linked
function transferPoint(uint32 _point, address _target, bool _reset) public { require(azimuth.canTransfer(_point, msg.sender)); if ( !azimuth.isActive(_point) ) { azimuth.activatePoint(_point); } { address old = azimuth.getOwner(_point); azimuth.setOwner(_point, _target); azimuth.setTransferProxy(_point, 0); emit Transfer(old, _target, uint256(_point)); } { if ( azimuth.hasBeenLinked(_point) ) { azimuth.incrementContinuityNumber(_point); azimuth.setKeys(_point, 0, 0, 0); } } }
1,401,170
./partial_match/8453/0x6131B5fae19EA4f9D964eAc0408E4408b66337b5/sources/MetaAggregationRouterV2.sol
take fee and deduct total swap amount take fee
function swapSimpleMode( IAggregationExecutor caller, SwapDescriptionV2 memory desc, bytes calldata executorData, bytes calldata clientData ) public returns (uint256 returnAmount, uint256 gasUsed) { uint256 gasBefore = gasleft(); require(!_isETH(desc.srcToken), 'src is eth, should use normal swap'); _permit(desc.srcToken, desc.amount, desc.permit); address dstReceiver = (desc.dstReceiver == address(0)) ? msg.sender : desc.dstReceiver; { bool isBps = _flagsChecked(desc.flags, _FEE_IN_BPS); if (!_flagsChecked(desc.flags, _FEE_ON_DST)) { desc.amount = _takeFee(desc.srcToken, msg.sender, desc.feeReceivers, desc.feeAmounts, desc.amount, isBps); dstReceiver = address(this); } } uint256 initialDstBalance = _getBalance(desc.dstToken, dstReceiver); uint256 initialSrcBalance = _getBalance(desc.srcToken, msg.sender); _swapMultiSequencesWithSimpleMode( caller, address(desc.srcToken), desc.amount, address(desc.dstToken), dstReceiver, executorData ); { if (_flagsChecked(desc.flags, _FEE_ON_DST)) { { bool isBps = _flagsChecked(desc.flags, _FEE_IN_BPS); returnAmount = _takeFee( desc.dstToken, address(this), desc.feeReceivers, desc.feeAmounts, returnAmount, isBps ); } IERC20 dstToken = desc.dstToken; dstReceiver = desc.dstReceiver == address(0) ? msg.sender : desc.dstReceiver; } } uint256 spentAmount = initialSrcBalance - _getBalance(desc.srcToken, msg.sender); _checkReturnAmount(spentAmount, returnAmount, desc); emit Swapped(msg.sender, desc.srcToken, desc.dstToken, dstReceiver, spentAmount, returnAmount); emit Exchange(address(caller), returnAmount, _isETH(desc.dstToken) ? WETH : address(desc.dstToken)); emit ClientData(clientData); unchecked { gasUsed = gasBefore - gasleft(); } }
16,716,896
./full_match/1/0xFD9E52A73d92E08903BFe6f42aeDEB82a86EFF35/sources/contracts/NAGOMIMinterHalfYear.sol
ミント関数/ フリーミント用のMint関数 セールフェイズチェック マークルツリーチェック:ルートはfreeMintMerkleRoot ミント枚数チェック:フリーミントは1枚まで フリーミント済み数加算
function freeMint(uint256 _mintAmount, bytes32[] calldata _merkleProof) external callerIsUser notZeroMint(_mintAmount) notOverMaxSupply(_mintAmount) { require(phase == SalePhase.FreeMint, "FreeMint is disabled"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, freeMintMerkleRoot, leaf), "Invalid Merkle Proof"); require(freeMintCount[msg.sender] + _mintAmount <= 1, "exceeds allocation"); randomMint(msg.sender, _mintAmount); unchecked { freeMintCount[msg.sender] += _mintAmount; } }
3,024,496
./full_match/44787/0xE872636cca1c141B62bd9f82C745cE6b9113C6bD/sources/project_/contracts/KolorLandToken.sol
Return all investments made by an address /
function investmentsOf(address account) public view returns (Investment[] memory) { uint256 _totalInvestmentsOf = totalInvestmentsOf(account); Investment[] memory investments = new Investment[](_totalInvestmentsOf); for (uint256 i = 0; i < _totalInvestmentsOf; i++) { investments[i] = investmentOf(account, i); } return investments; }
13,260,558
// SPDX-License-Identifier: MIYA pragma solidity ^0.8.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./FlightSuretyData.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ bool private operational = true; // Blocks all state changes throughout the contract if false bool private isSetUp; FlightSuretyData flightSuretyData; // Arline queue struct AirlineRegistration { bool isInTheQueue; bool isReadyForVote; uint256 votesInFavor; // number of votes Yes uint256 votesAgainst; // number of votes No mapping(address => bool) voters; // check who has voted. a voter cannot vote twice } mapping(address => AirlineRegistration) private airlineRegistrationQueue; uint8 private constant AIRLINE_QUEUE_ACTIVATION = 5; uint256 public constant AIRLINE_FEE = 10 ether; uint256 public constant PASSENGER_INSURANCE_LIMIT = 1 ether; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; address[] passengerList; } mapping(bytes32 => Flight) private flights; /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier calledOnlyOnce() { require(!isSetUp, "Contract already setup"); _; } modifier nonExistingAirline(address _airline) { require( !flightSuretyData.isRegistredAirline(_airline), "Airline already registred" ); require( !airlineRegistrationQueue[_airline].isInTheQueue, "Airline already in the queue for registration" ); _; } modifier mustBeQueued(address _airline) { require( !flightSuretyData.isRegistredAirline(_airline), "Airline already registred" ); require( airlineRegistrationQueue[_airline].isInTheQueue, "Airline must be queued for registration" ); _; } modifier cannotBeInQueueVote(address _airline) { require( !airlineRegistrationQueue[_airline].isReadyForVote, "The airline is in the queue for vote" ); _; } modifier mustBeInQueueVote(address _airline) { require( airlineRegistrationQueue[_airline].isReadyForVote, "The airline must be the queue for vote" ); _; } modifier checkRegistrerAirline(address _airline) { require( flightSuretyData.isRegistredAirline(msg.sender), "Only a registred airline may register or vote" ); require( !airlineRegistrationQueue[_airline].voters[msg.sender], "You cannot vote for an airline twice" ); _; } modifier requireKnownAirline(address _airline) { require( flightSuretyData.isRegistredAirline(_airline), "Airline not registred" ); _; } modifier requireValidFlightNumber(string memory _flight) { require(bytes(_flight).length > 0, "Flight number not valid"); _; } modifier requireValidTimestamp(uint256 _timestamp) { require(block.timestamp < _timestamp, "Flight cannot be in the past"); _; } modifier requireRightStatusCode(bytes32 _key) { require( flights[_key].statusCode == STATUS_CODE_LATE_AIRLINE, "Cannot release insurance. status code not correct" ); _; } /********************************************************************************************/ /* EVENTS */ /********************************************************************************************/ event AIRLINE_REGISTRED( address indexed _airline, uint256 _votesInFavor, uint256 _votesAgainst, uint256 _numberAirlines ); event AIRLINE_REFUSED( address indexed _airline, uint256 _votesInFavor, uint256 _votesAgainst, uint256 _numberAirlines ); event AIRLINE_QUEUED(address indexed _airline); event AIRLINE_READY_FOR_VOTE(address indexed _airline); event AIRLINE_VOTED_YES(address indexed _airline, address indexed _voter); event AIRLINE_VOTED_NO(address indexed _airline, address indexed _voter); event FLIGHT_REGISTERED( address indexed _airline, bytes32 indexed _key, string _flight, uint256 _timestamp, uint8 _status ); event INSURANCE_DEPOSITED( address indexed _passenger, bytes32 indexed _key, uint256 _depositedAmount, uint256 _totalDeposit ); event INSURANCE_RELEASED( address indexed _passenger, bytes32 indexed _key, uint256 _totalDeposit, uint256 _totalReleased, uint256 _totalBalance ); event FLIGHT_INSURANCE_TOBE_RELEASED( address indexed _airline, string _flight, uint256 _timestamp, bytes32 indexed _key, uint256 _passengersNumber ); /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor() { contractOwner = msg.sender; isSetUp = false; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public pure returns (bool) { return true; // Modify to call data contract's status } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function setOperatingStatus(bool mode) public requireContractOwner() { operational = mode; } // setup of contract (called just after contructing) function setUp(FlightSuretyData _flightSuretyData, address _airline) public payable requireIsOperational() requireContractOwner() calledOnlyOnce() { require( msg.value >= AIRLINE_FEE, "Airline registration fee is required" ); isSetUp = true; flightSuretyData = FlightSuretyData(_flightSuretyData); flightSuretyData.registerAirline{value: AIRLINE_FEE}(_airline); // return back the change. registration only of 10 ether if (msg.value > AIRLINE_FEE) { payable(msg.sender).transfer(msg.value.sub(AIRLINE_FEE)); } emit AIRLINE_REGISTRED( _airline, 0, 0, flightSuretyData.numberOfRegistredAirlines() ); } // Airline stakes 10 ether before registrating function stakeAirline() public payable requireIsOperational() nonExistingAirline(msg.sender) { // Require registration fee require( msg.value >= AIRLINE_FEE, "Airline registration fee is required" ); // queue arline AirlineRegistration storage airlineRegistration = airlineRegistrationQueue[msg.sender]; airlineRegistration.isInTheQueue = true; airlineRegistration.votesInFavor = 0; airlineRegistration.votesAgainst = 0; emit AIRLINE_QUEUED(msg.sender); // return back the change. registration only of 10 ether if (msg.value > AIRLINE_FEE) { payable(msg.sender).transfer(msg.value.sub(AIRLINE_FEE)); } } function airlineQueueState(address _airline) public view returns ( bool isInTheQueue, bool isReadyForVote, uint256 votesInFavor, uint256 votesAgainst ) { AirlineRegistration storage airlineRegistration = airlineRegistrationQueue[_airline]; isInTheQueue = airlineRegistration.isInTheQueue; isReadyForVote = airlineRegistration.isReadyForVote; votesInFavor = airlineRegistration.votesInFavor; votesAgainst = airlineRegistration.votesAgainst; } /** * @dev Add an airline to the registration queue * */ function registerAirline(address _airline) public requireIsOperational() mustBeQueued(_airline) cannotBeInQueueVote(_airline) checkRegistrerAirline(_airline) returns (bool success) { if ( flightSuretyData.numberOfRegistredAirlines().add(1) < AIRLINE_QUEUE_ACTIVATION ) { delete airlineRegistrationQueue[_airline]; success = true; flightSuretyData.registerAirline{value: AIRLINE_FEE}(_airline); emit AIRLINE_REGISTRED( _airline, 1, 0, flightSuretyData.numberOfRegistredAirlines() ); } else { AirlineRegistration storage airlineRegistration = airlineRegistrationQueue[_airline]; airlineRegistration.votesInFavor = 1; airlineRegistration.votesAgainst = 0; airlineRegistration.voters[msg.sender] = true; airlineRegistration.isReadyForVote = true; success = false; emit AIRLINE_READY_FOR_VOTE(_airline); } emit AIRLINE_VOTED_YES(_airline, msg.sender); return success; } function voteAirline(address _airline, bool _inFavor) public requireIsOperational() mustBeInQueueVote(_airline) checkRegistrerAirline(_airline) { _airlineRegistrator(_airline, _inFavor); } function _airlineRegistrator(address _airline, bool _inFavor) private { uint256 threshold = flightSuretyData.numberOfRegistredAirlines().div(2).add(1); // >50% AirlineRegistration storage airlineRegistration = airlineRegistrationQueue[_airline]; airlineRegistration.voters[msg.sender] = true; if (_inFavor) { airlineRegistration.votesInFavor = airlineRegistration .votesInFavor .add(1); emit AIRLINE_VOTED_YES(_airline, msg.sender); } else { airlineRegistration.votesAgainst = airlineRegistration .votesAgainst .add(1); emit AIRLINE_VOTED_NO(_airline, msg.sender); } uint256 votesInFavor = airlineRegistration.votesInFavor; uint256 votesAgainst = airlineRegistration.votesAgainst; if (airlineRegistration.votesInFavor >= threshold) { delete airlineRegistrationQueue[_airline]; flightSuretyData.registerAirline{value: AIRLINE_FEE}(_airline); emit AIRLINE_REGISTRED( _airline, votesInFavor, votesAgainst, flightSuretyData.numberOfRegistredAirlines() ); } else if (airlineRegistration.votesAgainst >= threshold) { delete airlineRegistrationQueue[_airline]; emit AIRLINE_REFUSED( _airline, votesInFavor, votesAgainst, flightSuretyData.numberOfRegistredAirlines() ); } } /** * @dev Register a future flight for insuring. * */ function registerFlight( address _airline, string memory _flight, uint256 _timestamp ) public requireIsOperational() requireKnownAirline(_airline) requireValidFlightNumber(_flight) requireValidTimestamp(_timestamp) { bytes32 key = getFlightKey(_airline, _flight, _timestamp); Flight storage flight = flights[key]; require(!flight.isRegistered, "Cannot register an existing flight"); flight.isRegistered = true; flight.statusCode = STATUS_CODE_UNKNOWN; flight.updatedTimestamp = _timestamp; flight.airline = _airline; emit FLIGHT_REGISTERED(_airline, key, _flight, _timestamp , STATUS_CODE_UNKNOWN); } function buy( address _airline, string memory _flight, uint256 _timestamp ) public payable requireIsOperational() requireKnownAirline(_airline) requireValidFlightNumber(_flight) requireValidTimestamp(_timestamp) { bytes32 _key = getFlightKey(_airline, _flight, _timestamp); Flight storage flight = flights[_key]; require(flight.isRegistered, "Flight must be registered"); uint256 _deposit = flightSuretyData.getDeposit(msg.sender, _key); require( _deposit < PASSENGER_INSURANCE_LIMIT, "Insurance limit amount exceeded" ); if (_deposit == 0) { flight.passengerList.push(msg.sender); // first time passenger } uint256 _remaining = PASSENGER_INSURANCE_LIMIT.sub(_deposit); // allow user to increase his insurance deposit for a given flight uint256 _newDeposit; if (msg.value > _remaining) { _newDeposit = _remaining; flightSuretyData.buy{value: _newDeposit}(msg.sender, _key); payable(msg.sender).transfer(msg.value.sub(_newDeposit)); } else { _newDeposit = msg.value; flightSuretyData.buy{value: _newDeposit}(msg.sender, _key); } emit INSURANCE_DEPOSITED( msg.sender, _key, _newDeposit, flightSuretyData.getDeposit(msg.sender, _key) ); } function getFlightPassengersNumber( address airline, string memory flight, uint256 timestamp ) public view returns (uint256) { bytes32 _key = getFlightKey(airline, flight, timestamp); return getFlightPassengersNumber(_key); } function getFlightPassengersNumber(bytes32 key) public view returns (uint256) { return flights[key].passengerList.length; } function getFlightPassengersList(bytes32 key) public view returns (address[] memory) { return flights[key].passengerList; } // loop over this function from dapp to release money. Anyone can trigger money release. this avoids to loop inside the smartcontract function releaseInsurance(bytes32 key) public requireIsOperational() requireRightStatusCode(key) { uint256 length = flights[key].passengerList.length; if (length == 0) return; address _passenger = flights[key].passengerList[length - 1]; flights[key].passengerList.pop(); uint256 _totalDeposit = flightSuretyData.getDeposit(_passenger, key); require(_totalDeposit > 0, "Passenger does not have enough deposit"); // sanity check, fail fast. passenger shouldn't be in the list without having deposited somehting uint256 _totalReleased = _totalDeposit.mul(3).div(2); flightSuretyData.creditInsurees(_passenger, key, _totalReleased); emit INSURANCE_RELEASED( _passenger, key, _totalDeposit, _totalReleased, flightSuretyData.getBalance(_passenger) ); } function releaseInsurance( address airline, string memory flight, uint256 timestamp ) public requireIsOperational() { bytes32 _key = getFlightKey(airline, flight, timestamp); releaseInsurance(_key); } function getFlightStatusCode( address airline, string memory flight, uint256 timestamp ) public view returns (uint8) { return getFlightStatusCode(getFlightKey(airline, flight, timestamp)); } function getFlightStatusCode(bytes32 key) public view returns (uint8) { require(flights[key].isRegistered, "Flight must be registered"); return flights[key].statusCode; } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus( address airline, string memory flight, uint256 timestamp, uint8 statusCode ) private { if (statusCode == STATUS_CODE_LATE_AIRLINE) { bytes32 _key = getFlightKey(airline, flight, timestamp); emit FLIGHT_INSURANCE_TOBE_RELEASED( airline, flight, timestamp, _key, flights[_key].passengerList.length ); } } // Generate a request for oracles to fetch flight information function fetchFlightStatus( address airline, string memory flight, uint256 timestamp ) public requireIsOperational() { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require( flights[getFlightKey(airline, flight, timestamp)].isRegistered, "Flight must be registered" ); ResponseInfo storage responseInfo = oracleResponses[key]; responseInfo.requester = msg.sender; responseInfo.isOpen = true; emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo( address _airline, string _flight, uint256 _timestamp, uint8 _status ); event OracleRegistered( address indexed _oracle, uint256 _registrationFee, bool _isRegistered, uint8[3] _indexes ); event OracleReport( address _airline, string _flight, uint256 _timestamp, uint8 _status ); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest( uint8 _index, address _airline, string _flight, uint256 _timestamp ); // Register an oracle with the contract function registerOracle() public payable requireIsOperational() { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); require(!oracles[msg.sender].isRegistered , "Oracle already registered"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes}); emit OracleRegistered(msg.sender, msg.value, oracles[msg.sender].isRegistered, oracles[msg.sender].indexes); } function isOracleRegistered(address oracle) public view returns (bool){ return oracles[oracle].isRegistered; } function getMyIndexes() public view returns (uint8[3] memory) { require( oracles[msg.sender].isRegistered, "Not registered as an oracle" ); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse( uint8 index, address airline, string memory flight, uint256 timestamp, uint8 statusCode ) public requireIsOperational() { require( (oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request" ); require( statusCode == STATUS_CODE_UNKNOWN || statusCode == STATUS_CODE_ON_TIME || statusCode == STATUS_CODE_LATE_AIRLINE || statusCode == STATUS_CODE_LATE_WEATHER || statusCode == STATUS_CODE_LATE_TECHNICAL || statusCode == STATUS_CODE_LATE_OTHER, "Status code not known" ); require( flights[getFlightKey(airline, flight, timestamp)].isRegistered, "Flight must be registered" ); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require( oracleResponses[key].isOpen, "Flight or timestamp or index do not match oracle request" ); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if ( oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES ) { flights[getFlightKey(airline, flight, timestamp)] .statusCode = statusCode; emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey( address airline, string memory flight, uint256 timestamp ) public pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) private returns (uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while (indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) private returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8( uint256( keccak256( abi.encodePacked( blockhash(block.number - nonce++), account ) ) ) % maxValue ); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion }
Register an oracle with the contract Require registration fee
function registerOracle() public payable requireIsOperational() { require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); require(!oracles[msg.sender].isRegistered , "Oracle already registered"); uint8[3] memory indexes = generateIndexes(msg.sender); emit OracleRegistered(msg.sender, msg.value, oracles[msg.sender].isRegistered, oracles[msg.sender].indexes); }
13,002,042
./partial_match/1/0xBf6E1F1Fd72080C4793e89aCB8FB61ef1A61cA67/sources/Proposal32.sol
Rescues tokens and sends them to the `to` address token The address of the token to The address for which the tokens should be send return Success/
function rescueTokens( address token, address to, uint256 amount ) external returns (bool) { token; to; delegateAndReturn(); }
4,473,871
/** // IMPORTANT: Developer should update the ISecurityTokenRegistry.sol (Interface) if there is any change in function signature or addition/removal of the functions from SecurityTokenRegistry & STRGetter contract. // */ pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IOwnable.sol"; import "./interfaces/ISTFactory.sol"; import "./interfaces/ISecurityToken.sol"; import "./interfaces/IPolymathRegistry.sol"; import "./interfaces/IOracle.sol"; import "./storage/EternalStorage.sol"; import "./libraries/Util.sol"; import "./libraries/Encoder.sol"; import "./libraries/VersionUtils.sol"; import "./libraries/DecimalMath.sol"; import "./proxy/Proxy.sol"; /** * @title Registry contract for issuers to register their tickers and security tokens */ contract SecurityTokenRegistry is EternalStorage, Proxy { /** * @notice state variables address public polyToken; uint256 public stLaunchFee; uint256 public tickerRegFee; uint256 public expiryLimit; uint256 public latestProtocolVersion; bool public paused; address public owner; address public polymathRegistry; address[] public activeUsers; mapping(address => bool) public seenUsers; mapping(address => bytes32[]) userToTickers; mapping(string => address) tickerToSecurityToken; mapping(string => uint) tickerIndex; mapping(string => TickerDetails) registeredTickers; mapping(address => SecurityTokenData) securityTokens; mapping(bytes32 => address) protocolVersionST; mapping(uint256 => ProtocolVersion) versionData; struct ProtocolVersion { uint8 major; uint8 minor; uint8 patch; } struct TickerDetails { address owner; uint256 registrationDate; uint256 expiryDate; string tokenName; //Not stored since 3.0.0 bool status; } struct SecurityTokenData { string ticker; string tokenDetails; uint256 deployedAt; } */ using SafeMath for uint256; bytes32 constant INITIALIZE = 0x9ef7257c3339b099aacf96e55122ee78fb65a36bd2a6c19249882be9c98633bf; //keccak256("initialised") bytes32 constant POLYTOKEN = 0xacf8fbd51bb4b83ba426cdb12f63be74db97c412515797993d2a385542e311d7; //keccak256("polyToken") bytes32 constant STLAUNCHFEE = 0xd677304bb45536bb7fdfa6b9e47a3c58fe413f9e8f01474b0a4b9c6e0275baf2; //keccak256("stLaunchFee") bytes32 constant TICKERREGFEE = 0x2fcc69711628630fb5a42566c68bd1092bc4aa26826736293969fddcd11cb2d2; //keccak256("tickerRegFee") bytes32 constant EXPIRYLIMIT = 0x604268e9a73dfd777dcecb8a614493dd65c638bad2f5e7d709d378bd2fb0baee; //keccak256("expiryLimit") bytes32 constant PAUSED = 0xee35723ac350a69d2a92d3703f17439cbaadf2f093a21ba5bf5f1a53eb2a14d9; //keccak256("paused") bytes32 constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; //keccak256("owner") bytes32 constant POLYMATHREGISTRY = 0x90eeab7c36075577c7cc5ff366e389fefa8a18289b949bab3529ab4471139d4d; //keccak256("polymathRegistry") bytes32 constant STRGETTER = 0x982f24b3bd80807ec3cb227ba152e15c07d66855fa8ae6ca536e689205c0e2e9; //keccak256("STRGetter") bytes32 constant IS_FEE_IN_POLY = 0x7152e5426955da44af11ecd67fec5e2a3ba747be974678842afa9394b9a075b6; //keccak256("IS_FEE_IN_POLY") bytes32 constant ACTIVE_USERS = 0x425619ce6ba8e9f80f17c0ef298b6557e321d70d7aeff2e74dd157bd87177a9e; //keccak256("activeUsers") bytes32 constant LATEST_VERSION = 0x4c63b69b9117452b9f11af62077d0cda875fb4e2dbe07ad6f31f728de6926230; //keccak256("latestVersion") string constant POLY_ORACLE = "StablePolyUsdOracle"; // Emit when network becomes paused event Pause(address account); // Emit when network becomes unpaused event Unpause(address account); // Emit when the ticker is removed from the registry event TickerRemoved(string _ticker, address _removedBy); // Emit when the token ticker expiry is changed event ChangeExpiryLimit(uint256 _oldExpiry, uint256 _newExpiry); // Emit when changeSecurityLaunchFee is called event ChangeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee); // Emit when changeTickerRegistrationFee is called event ChangeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee); // Emit when Fee currency is changed event ChangeFeeCurrency(bool _isFeeInPoly); // Emit when ownership gets transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Emit when ownership of the ticker gets changed event ChangeTickerOwnership(string _ticker, address indexed _oldOwner, address indexed _newOwner); // Emit at the time of launching a new security token of version 3.0+ event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _usdFee, uint256 _polyFee, uint256 _protocolVersion ); // Emit at the time of launching a new security token v2.0. // _registrationFee is in poly event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _registrationFee ); // Emit after ticker registration event RegisterTicker( address indexed _owner, string _ticker, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFeePoly, uint256 _registrationFeeUsd ); // For backwards compatibility event RegisterTicker( address indexed _owner, string _ticker, string _name, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFee ); // Emit at when issuer refreshes exisiting token event SecurityTokenRefreshed( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, uint256 _protocolVersion ); event ProtocolFactorySet(address indexed _STFactory, uint8 _major, uint8 _minor, uint8 _patch); event LatestVersionSet(uint8 _major, uint8 _minor, uint8 _patch); event ProtocolFactoryRemoved(address indexed _STFactory, uint8 _major, uint8 _minor, uint8 _patch); ///////////////////////////// // Modifiers ///////////////////////////// /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() internal view { require(msg.sender == owner(), "Only owner"); } modifier onlyOwnerOrSelf() { require(msg.sender == owner() || msg.sender == address(this), "Only owner or self"); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPausedOrOwner() { _whenNotPausedOrOwner(); _; } function _whenNotPausedOrOwner() internal view { if (msg.sender != owner()) { require(!isPaused(), "Paused"); } } /** * @notice Modifier to make a function callable only when the contract is not paused and ignore is msg.sender is owner. */ modifier whenNotPaused() { require(!isPaused(), "Paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(isPaused(), "Not paused"); _; } ///////////////////////////// // Initialization ///////////////////////////// // Constructor constructor() public { set(INITIALIZE, true); } /** * @notice Initializes instance of STR * @param _polymathRegistry is the address of the Polymath Registry * @param _stLaunchFee is the fee in USD required to launch a token * @param _tickerRegFee is the fee in USD required to register a ticker * @param _owner is the owner of the STR, * @param _getterContract Contract address of the contract which consists getter functions. */ function initialize( address _polymathRegistry, uint256 _stLaunchFee, uint256 _tickerRegFee, address _owner, address _getterContract ) public { require(!getBoolValue(INITIALIZE),"Initialized"); require( _owner != address(0) && _polymathRegistry != address(0) && _getterContract != address(0), "Invalid address" ); set(STLAUNCHFEE, _stLaunchFee); set(TICKERREGFEE, _tickerRegFee); set(EXPIRYLIMIT, uint256(60 * 1 days)); set(PAUSED, false); set(OWNER, _owner); set(POLYMATHREGISTRY, _polymathRegistry); set(INITIALIZE, true); set(STRGETTER, _getterContract); _updateFromRegistry(); } /** * @notice Used to update the polyToken contract address */ function updateFromRegistry() external onlyOwner { _updateFromRegistry(); } function _updateFromRegistry() internal { address polymathRegistry = getAddressValue(POLYMATHREGISTRY); set(POLYTOKEN, IPolymathRegistry(polymathRegistry).getAddress("PolyToken")); } /** * @notice Converts USD fees into POLY amounts */ function _takeFee(bytes32 _feeType) internal returns (uint256, uint256) { (uint256 usdFee, uint256 polyFee) = getFees(_feeType); if (polyFee > 0) require(IERC20(getAddressValue(POLYTOKEN)).transferFrom(msg.sender, address(this), polyFee), "Insufficent allowance"); return (usdFee, polyFee); } /** * @notice Returns the usd & poly fee for a particular feetype * @param _feeType Key corresponding to fee type */ function getFees(bytes32 _feeType) public returns (uint256 usdFee, uint256 polyFee) { bool isFeesInPoly = getBoolValue(IS_FEE_IN_POLY); uint256 rawFee = getUintValue(_feeType); address polymathRegistry = getAddressValue(POLYMATHREGISTRY); uint256 polyRate = IOracle(IPolymathRegistry(polymathRegistry).getAddress(POLY_ORACLE)).getPrice(); if (!isFeesInPoly) { //Fee is in USD and not poly usdFee = rawFee; polyFee = DecimalMath.div(rawFee, polyRate); } else { usdFee = DecimalMath.mul(rawFee, polyRate); polyFee = rawFee; } } /** * @notice Gets the security token launch fee * @return Fee amount */ function getSecurityTokenLaunchFee() public returns(uint256 polyFee) { (, polyFee) = getFees(STLAUNCHFEE); } /** * @notice Gets the ticker registration fee * @return Fee amount */ function getTickerRegistrationFee() public returns(uint256 polyFee) { (, polyFee) = getFees(TICKERREGFEE); } /** * @notice Set the getter contract address * @param _getterContract Address of the contract */ function setGetterRegistry(address _getterContract) public onlyOwnerOrSelf { require(_getterContract != address(0)); set(STRGETTER, _getterContract); } function _implementation() internal view returns(address) { return getAddressValue(STRGETTER); } ///////////////////////////// // Token Ticker Management ///////////////////////////// /** * @notice Registers the token ticker to the selected owner * @notice Once the token ticker is registered to its owner then no other issuer can claim * @notice its ownership. If the ticker expires and its issuer hasn't used it, then someone else can take it. * @param _owner is address of the owner of the token * @param _ticker is unique token ticker */ function registerNewTicker(address _owner, string memory _ticker) public whenNotPausedOrOwner { require(_owner != address(0), "Bad address"); require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Bad ticker"); // Attempt to charge the reg fee if it is > 0 USD (uint256 usdFee, uint256 polyFee) = _takeFee(TICKERREGFEE); string memory ticker = Util.upper(_ticker); require(tickerAvailable(ticker), "Ticker reserved"); // Check whether ticker was previously registered (and expired) address previousOwner = _tickerOwner(ticker); if (previousOwner != address(0)) { _deleteTickerOwnership(previousOwner, ticker); } /*solium-disable-next-line security/no-block-members*/ _addTicker(_owner, ticker, now, now.add(getUintValue(EXPIRYLIMIT)), false, false, polyFee, usdFee); } /** * @dev This function is just for backwards compatibility */ function registerTicker(address _owner, string calldata _ticker, string calldata _tokenName) external { registerNewTicker(_owner, _ticker); (, uint256 polyFee) = getFees(TICKERREGFEE); emit RegisterTicker(_owner, _ticker, _tokenName, now, now.add(getUintValue(EXPIRYLIMIT)), false, polyFee); } /** * @notice Internal - Sets the details of the ticker */ function _addTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status, bool _fromAdmin, uint256 _polyFee, uint256 _usdFee ) internal { _setTickerOwnership(_owner, _ticker); _storeTickerDetails(_ticker, _owner, _registrationDate, _expiryDate, _status); emit RegisterTicker(_owner, _ticker, _registrationDate, _expiryDate, _fromAdmin, _polyFee, _usdFee); } /** * @notice Modifies the ticker details. Only Polymath has the ability to do so. * @notice Only allowed to modify the tickers which are not yet deployed. * @param _owner is the owner of the token * @param _ticker is the token ticker * @param _registrationDate is the date at which ticker is registered * @param _expiryDate is the expiry date for the ticker * @param _status is the token deployment status */ function modifyExistingTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status ) public onlyOwner { require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Bad ticker"); require(_expiryDate != 0 && _registrationDate != 0, "Bad dates"); require(_registrationDate <= _expiryDate, "Bad dates"); require(_owner != address(0), "Bad address"); string memory ticker = Util.upper(_ticker); _modifyTicker(_owner, ticker, _registrationDate, _expiryDate, _status); } /** * @dev This function is just for backwards compatibility */ function modifyTicker( address _owner, string calldata _ticker, string calldata _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status ) external { modifyExistingTicker(_owner, _ticker, _registrationDate, _expiryDate, _status); emit RegisterTicker(_owner, _ticker, _tokenName, now, now.add(getUintValue(EXPIRYLIMIT)), false, 0); } /** * @notice Internal -- Modifies the ticker details. */ function _modifyTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { address currentOwner = _tickerOwner(_ticker); if (currentOwner != address(0)) { _deleteTickerOwnership(currentOwner, _ticker); } if (_tickerStatus(_ticker) && !_status) { set(Encoder.getKey("tickerToSecurityToken", _ticker), address(0)); } // If status is true, there must be a security token linked to the ticker already if (_status) { require(getAddressValue(Encoder.getKey("tickerToSecurityToken", _ticker)) != address(0), "Not registered"); } _addTicker(_owner, _ticker, _registrationDate, _expiryDate, _status, true, uint256(0), uint256(0)); } function _tickerOwner(string memory _ticker) internal view returns(address) { return getAddressValue(Encoder.getKey("registeredTickers_owner", _ticker)); } /** * @notice Removes the ticker details, associated ownership & security token mapping * @param _ticker is the token ticker */ function removeTicker(string memory _ticker) public onlyOwner { string memory ticker = Util.upper(_ticker); address owner = _tickerOwner(ticker); require(owner != address(0), "Bad ticker"); _deleteTickerOwnership(owner, ticker); set(Encoder.getKey("tickerToSecurityToken", ticker), address(0)); _storeTickerDetails(ticker, address(0), 0, 0, false); /*solium-disable-next-line security/no-block-members*/ emit TickerRemoved(ticker, msg.sender); } /** * @notice Checks if the entered ticker is registered and has not expired * @param _ticker is the token ticker * @return bool */ function tickerAvailable(string memory _ticker) public view returns(bool) { if (_tickerOwner(_ticker) != address(0)) { /*solium-disable-next-line security/no-block-members*/ if ((now > getUintValue(Encoder.getKey("registeredTickers_expiryDate", _ticker))) && !_tickerStatus(_ticker)) { return true; } else return false; } return true; } function _tickerStatus(string memory _ticker) internal view returns(bool) { return getBoolValue(Encoder.getKey("registeredTickers_status", _ticker)); } /** * @notice Internal - Sets the ticker owner * @param _owner is the address of the owner of the ticker * @param _ticker is the ticker symbol */ function _setTickerOwnership(address _owner, string memory _ticker) internal { bytes32 _ownerKey = Encoder.getKey("userToTickers", _owner); uint256 length = uint256(getArrayBytes32(_ownerKey).length); pushArray(_ownerKey, Util.stringToBytes32(_ticker)); set(Encoder.getKey("tickerIndex", _ticker), length); bytes32 seenKey = Encoder.getKey("seenUsers", _owner); if (!getBoolValue(seenKey)) { pushArray(ACTIVE_USERS, _owner); set(seenKey, true); } } /** * @notice Internal - Stores the ticker details */ function _storeTickerDetails( string memory _ticker, address _owner, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { bytes32 key = Encoder.getKey("registeredTickers_owner", _ticker); set(key, _owner); key = Encoder.getKey("registeredTickers_registrationDate", _ticker); set(key, _registrationDate); key = Encoder.getKey("registeredTickers_expiryDate", _ticker); set(key, _expiryDate); key = Encoder.getKey("registeredTickers_status", _ticker); set(key, _status); } /** * @notice Transfers the ownership of the ticker * @param _newOwner is the address of the new owner of the ticker * @param _ticker is the ticker symbol */ function transferTickerOwnership(address _newOwner, string memory _ticker) public whenNotPausedOrOwner { string memory ticker = Util.upper(_ticker); require(_newOwner != address(0), "Bad address"); bytes32 ownerKey = Encoder.getKey("registeredTickers_owner", ticker); require(getAddressValue(ownerKey) == msg.sender, "Only owner"); if (_tickerStatus(ticker)) require( IOwnable(getAddressValue(Encoder.getKey("tickerToSecurityToken", ticker))).owner() == _newOwner, "Owner mismatch" ); _deleteTickerOwnership(msg.sender, ticker); _setTickerOwnership(_newOwner, ticker); set(ownerKey, _newOwner); emit ChangeTickerOwnership(ticker, msg.sender, _newOwner); } /** * @notice Internal - Removes the owner of a ticker */ function _deleteTickerOwnership(address _owner, string memory _ticker) internal { uint256 index = uint256(getUintValue(Encoder.getKey("tickerIndex", _ticker))); bytes32 ownerKey = Encoder.getKey("userToTickers", _owner); bytes32[] memory tickers = getArrayBytes32(ownerKey); assert(index < tickers.length); assert(_tickerOwner(_ticker) == _owner); deleteArrayBytes32(ownerKey, index); if (getArrayBytes32(ownerKey).length > index) { bytes32 switchedTicker = getArrayBytes32(ownerKey)[index]; set(Encoder.getKey("tickerIndex", Util.bytes32ToString(switchedTicker)), index); } } /** * @notice Changes the expiry time for the token ticker. Only available to Polymath. * @param _newExpiry is the new expiry for newly generated tickers */ function changeExpiryLimit(uint256 _newExpiry) public onlyOwner { require(_newExpiry >= 1 days, "Bad dates"); emit ChangeExpiryLimit(getUintValue(EXPIRYLIMIT), _newExpiry); set(EXPIRYLIMIT, _newExpiry); } ///////////////////////////// // Security Token Management ///////////////////////////// /** * @notice Deploys an instance of a new Security Token of version 2.0 and records it to the registry * @dev this function is for backwards compatibilty with 2.0 dApp. * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function generateSecurityToken( string calldata _name, string calldata _ticker, string calldata _tokenDetails, bool _divisible ) external { generateNewSecurityToken(_name, _ticker, _tokenDetails, _divisible, msg.sender, VersionUtils.pack(2, 0, 0)); } /** * @notice Deploys an instance of a new Security Token and records it to the registry * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible * @param _treasuryWallet Ethereum address which will holds the STs. * @param _protocolVersion Version of securityToken contract * - `_protocolVersion` is the packed value of uin8[3] array (it will be calculated offchain) * - if _protocolVersion == 0 then latest version of securityToken will be generated */ function generateNewSecurityToken( string memory _name, string memory _ticker, string memory _tokenDetails, bool _divisible, address _treasuryWallet, uint256 _protocolVersion ) public whenNotPausedOrOwner { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Bad ticker"); require(_treasuryWallet != address(0), "0x0 not allowed"); if (_protocolVersion == 0) { _protocolVersion = getUintValue(LATEST_VERSION); } _ticker = Util.upper(_ticker); bytes32 statusKey = Encoder.getKey("registeredTickers_status", _ticker); require(!getBoolValue(statusKey), "Already deployed"); set(statusKey, true); address issuer = msg.sender; require(_tickerOwner(_ticker) == issuer, "Not authorised"); /*solium-disable-next-line security/no-block-members*/ require(getUintValue(Encoder.getKey("registeredTickers_expiryDate", _ticker)) >= now, "Ticker expired"); (uint256 _usdFee, uint256 _polyFee) = _takeFee(STLAUNCHFEE); address newSecurityTokenAddress = _deployToken(_name, _ticker, _tokenDetails, issuer, _divisible, _treasuryWallet, _protocolVersion); if (_protocolVersion == VersionUtils.pack(2, 0, 0)) { // For backwards compatibilty. Should be removed with an update when we disable st 2.0 generation. emit NewSecurityToken( _ticker, _name, newSecurityTokenAddress, issuer, now, issuer, false, _polyFee ); } else { emit NewSecurityToken( _ticker, _name, newSecurityTokenAddress, issuer, now, issuer, false, _usdFee, _polyFee, _protocolVersion ); } } /** * @notice Deploys an instance of a new Security Token and replaces the old one in the registry * This can be used to upgrade from version 2.0 of ST to 3.0 or in case something goes wrong with earlier ST * @dev This function needs to be in STR 3.0. Defined public to avoid stack overflow * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function refreshSecurityToken( string memory _name, string memory _ticker, string memory _tokenDetails, bool _divisible, address _treasuryWallet ) public whenNotPausedOrOwner returns (address) { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Bad ticker"); require(_treasuryWallet != address(0), "0x0 not allowed"); string memory ticker = Util.upper(_ticker); require(_tickerStatus(ticker), "not deployed"); address st = getAddressValue(Encoder.getKey("tickerToSecurityToken", ticker)); address stOwner = IOwnable(st).owner(); require(msg.sender == stOwner, "Unauthroized"); require(ISecurityToken(st).transfersFrozen(), "Transfers not frozen"); uint256 protocolVersion = getUintValue(LATEST_VERSION); address newSecurityTokenAddress = _deployToken(_name, ticker, _tokenDetails, stOwner, _divisible, _treasuryWallet, protocolVersion); emit SecurityTokenRefreshed( _ticker, _name, newSecurityTokenAddress, stOwner, now, stOwner, protocolVersion ); } function _deployToken( string memory _name, string memory _ticker, string memory _tokenDetails, address _issuer, bool _divisible, address _wallet, uint256 _protocolVersion ) internal returns(address newSecurityTokenAddress) { // In v2.x of STFactory, the final argument to deployToken is the PolymathRegistry. // In v3.x of STFactory, the final argument to deployToken is the Treasury wallet. uint8[] memory upperLimit = new uint8[](3); upperLimit[0] = 2; upperLimit[1] = 99; upperLimit[2] = 99; if (VersionUtils.lessThanOrEqual(VersionUtils.unpack(uint24(_protocolVersion)), upperLimit)) { _wallet = getAddressValue(POLYMATHREGISTRY); } newSecurityTokenAddress = ISTFactory(getAddressValue(Encoder.getKey("protocolVersionST", _protocolVersion))).deployToken( _name, _ticker, 18, _tokenDetails, _issuer, _divisible, _wallet ); /*solium-disable-next-line security/no-block-members*/ _storeSecurityTokenData(newSecurityTokenAddress, _ticker, _tokenDetails, now); set(Encoder.getKey("tickerToSecurityToken", _ticker), newSecurityTokenAddress); } /** * @notice Adds a new custom Security Token and saves it to the registry. (Token should follow the ISecurityToken interface) * @param _ticker is the ticker symbol of the security token * @param _owner is the owner of the token * @param _securityToken is the address of the securityToken * @param _tokenDetails is the off-chain details of the token * @param _deployedAt is the timestamp at which the security token is deployed */ function modifyExistingSecurityToken( string memory _ticker, address _owner, address _securityToken, string memory _tokenDetails, uint256 _deployedAt ) public onlyOwner { require(bytes(_ticker).length <= 10, "Bad ticker"); require(_deployedAt != 0 && _owner != address(0), "Bad data"); string memory ticker = Util.upper(_ticker); require(_securityToken != address(0), "Bad address"); uint256 registrationTime = getUintValue(Encoder.getKey("registeredTickers_registrationDate", ticker)); uint256 expiryTime = getUintValue(Encoder.getKey("registeredTickers_expiryDate", ticker)); if (registrationTime == 0) { /*solium-disable-next-line security/no-block-members*/ registrationTime = now; expiryTime = registrationTime.add(getUintValue(EXPIRYLIMIT)); } set(Encoder.getKey("tickerToSecurityToken", ticker), _securityToken); _modifyTicker(_owner, ticker, registrationTime, expiryTime, true); _storeSecurityTokenData(_securityToken, ticker, _tokenDetails, _deployedAt); emit NewSecurityToken( ticker, ISecurityToken(_securityToken).name(), _securityToken, _owner, _deployedAt, msg.sender, true, uint256(0), uint256(0), 0 ); } /** * @dev This function is just for backwards compatibility */ function modifySecurityToken( string calldata /* */, string calldata _ticker, address _owner, address _securityToken, string calldata _tokenDetails, uint256 _deployedAt ) external { modifyExistingSecurityToken(_ticker, _owner, _securityToken, _tokenDetails, _deployedAt); } /** * @notice Internal - Stores the security token details */ function _storeSecurityTokenData( address _securityToken, string memory _ticker, string memory _tokenDetails, uint256 _deployedAt ) internal { set(Encoder.getKey("securityTokens_ticker", _securityToken), _ticker); set(Encoder.getKey("securityTokens_tokenDetails", _securityToken), _tokenDetails); set(Encoder.getKey("securityTokens_deployedAt", _securityToken), _deployedAt); } /** * @notice Checks that Security Token is registered * @param _securityToken is the address of the security token * @return bool */ function isSecurityToken(address _securityToken) external view returns(bool) { return (keccak256(bytes(getStringValue(Encoder.getKey("securityTokens_ticker", _securityToken)))) != keccak256("")); } ///////////////////////////// // Ownership, lifecycle & Utility ///////////////////////////// /** * @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), "Bad address"); emit OwnershipTransferred(getAddressValue(OWNER), _newOwner); set(OWNER, _newOwner); } /** * @notice Called by the owner to pause, triggers stopped state */ function pause() external whenNotPaused onlyOwner { set(PAUSED, true); /*solium-disable-next-line security/no-block-members*/ emit Pause(msg.sender); } /** * @notice Called by the owner to unpause, returns to normal state */ function unpause() external whenPaused onlyOwner { set(PAUSED, false); /*solium-disable-next-line security/no-block-members*/ emit Unpause(msg.sender); } /** * @notice Sets the ticker registration fee in USD tokens. Only Polymath. * @param _tickerRegFee is the registration fee in USD tokens (base 18 decimals) */ function changeTickerRegistrationFee(uint256 _tickerRegFee) public onlyOwner { uint256 fee = getUintValue(TICKERREGFEE); require(fee != _tickerRegFee, "Bad fee"); _changeTickerRegistrationFee(fee, _tickerRegFee); } function _changeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee) internal { emit ChangeTickerRegistrationFee(_oldFee, _newFee); set(TICKERREGFEE, _newFee); } /** * @notice Sets the ticker registration fee in USD tokens. Only Polymath. * @param _stLaunchFee is the registration fee in USD tokens (base 18 decimals) */ function changeSecurityLaunchFee(uint256 _stLaunchFee) public onlyOwner { uint256 fee = getUintValue(STLAUNCHFEE); require(fee != _stLaunchFee, "Bad fee"); _changeSecurityLaunchFee(fee, _stLaunchFee); } function _changeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee) internal { emit ChangeSecurityLaunchFee(_oldFee, _newFee); set(STLAUNCHFEE, _newFee); } /** * @notice Sets the ticker registration and ST launch fee amount and currency * @param _tickerRegFee is the ticker registration fee (base 18 decimals) * @param _stLaunchFee is the st generation fee (base 18 decimals) * @param _isFeeInPoly defines if the fee is in poly or usd */ function changeFeesAmountAndCurrency(uint256 _tickerRegFee, uint256 _stLaunchFee, bool _isFeeInPoly) public onlyOwner { uint256 tickerFee = getUintValue(TICKERREGFEE); uint256 stFee = getUintValue(STLAUNCHFEE); bool isOldFeesInPoly = getBoolValue(IS_FEE_IN_POLY); require(isOldFeesInPoly != _isFeeInPoly, "Currency unchanged"); _changeTickerRegistrationFee(tickerFee, _tickerRegFee); _changeSecurityLaunchFee(stFee, _stLaunchFee); emit ChangeFeeCurrency(_isFeeInPoly); set(IS_FEE_IN_POLY, _isFeeInPoly); } /** * @notice Reclaims all ERC20Basic compatible tokens * @param _tokenContract is the address of the token contract */ function reclaimERC20(address _tokenContract) public onlyOwner { require(_tokenContract != address(0), "Bad address"); IERC20 token = IERC20(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance), "Transfer failed"); } /** * @notice Changes the SecurityToken contract for a particular factory version * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _STFactoryAddress is the address of the proxy. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setProtocolFactory(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { _setProtocolFactory(_STFactoryAddress, _major, _minor, _patch); } function _setProtocolFactory(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) internal { require(_STFactoryAddress != address(0), "Bad address"); uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); address stFactoryAddress = getAddressValue(Encoder.getKey("protocolVersionST", uint256(_packedVersion))); require(stFactoryAddress == address(0), "Already exists"); set(Encoder.getKey("protocolVersionST", uint256(_packedVersion)), _STFactoryAddress); emit ProtocolFactorySet(_STFactoryAddress, _major, _minor, _patch); } /** * @notice Removes a STFactory * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function removeProtocolFactory(uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(getUintValue(LATEST_VERSION) != _packedVersion, "Cannot remove latestVersion"); emit ProtocolFactoryRemoved(getAddressValue(Encoder.getKey("protocolVersionST", _packedVersion)), _major, _minor, _patch); set(Encoder.getKey("protocolVersionST", uint256(_packedVersion)), address(0)); } /** * @notice Changes the default protocol version * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setLatestVersion(uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { _setLatestVersion(_major, _minor, _patch); } function _setLatestVersion(uint8 _major, uint8 _minor, uint8 _patch) internal { uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(getAddressValue(Encoder.getKey("protocolVersionST", _packedVersion)) != address(0), "No factory"); set(LATEST_VERSION, uint256(_packedVersion)); emit LatestVersionSet(_major, _minor, _patch); } /** * @notice Changes the PolyToken address. Only Polymath. * @param _newAddress is the address of the polytoken. */ function updatePolyTokenAddress(address _newAddress) public onlyOwner { require(_newAddress != address(0), "Bad address"); set(POLYTOKEN, _newAddress); } /** * @notice Check whether the registry is paused or not * @return bool */ function isPaused() public view returns(bool) { return getBoolValue(PAUSED); } /** * @notice Gets the owner of the contract * @return address owner */ function owner() public view returns(address) { return getAddressValue(OWNER); } }
Gets the ticker registration fee return Fee amount/
function getTickerRegistrationFee() public returns(uint256 polyFee) { (, polyFee) = getFees(TICKERREGFEE); }
12,533,471
// Sources flattened with hardhat v2.2.1 https://hardhat.org // File @openzeppelin/contracts/utils/Context.sol@v3.4.1 // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/Ownable.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () 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; } } // File @openzeppelin/contracts/math/SafeMath.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v3.4.1 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); } // File @openzeppelin/contracts/utils/Address.sol@v3.4.1 pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/SafeERC20.sol@v3.4.1 pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/Whitelist.sol pragma solidity ^0.6.0; contract Whitelist { // pool index => whether or not whitelist is enabled mapping(uint => bool) public enableWhiteList; // pool index => account => whether or not in white list mapping(uint => mapping(address => bool)) public whitelist; function _setEnableWhiteList(uint index, bool v) internal { enableWhiteList[index] = v; } function _addWhitelist(uint index, address[] memory whitelist_) internal { for (uint i = 0; i < whitelist_.length; i++) { whitelist[index][whitelist_[i]] = true; } } function _removeWhitelist(uint index, address[] memory whitelist_) internal { for (uint i = 0; i < whitelist_.length; i++) { delete whitelist[index][whitelist_[i]]; } } function _isWhitelistEnabled(uint index) internal view returns (bool) { return enableWhiteList[index]; } function _inWhitelist(uint index, address target) internal view returns (bool) { return whitelist[index][target]; } modifier checkInWhitelist(uint index, address target) { if (_isWhitelistEnabled(index)) { require(_inWhitelist(index, target), "ADDRESS SHOULD IN WHITELIST"); } _; } } // File contracts/PoolToken.sol pragma solidity ^0.6.0; contract PoolToken { struct TokenInfo { address payable creator; // address of token0 address token0; // address of token1 address token1; // total amount of token0 uint amountTotal0; // total amount of token1 uint amountTotal1; // maximum allocation amount of token1 per address uint maxAllocToken1; // swapped amount of token0 uint amountSwap0; // swapped amount of token1 uint amountSwap1; } TokenInfo[] public tokenInfos; function getPoolCount() public view returns (uint) { return tokenInfos.length; } function _setPoolToken( address payable creator, address token0, address token1, uint amountTotal0, uint amountTotal1, uint maxAllocToken1 ) internal returns (TokenInfo memory) { require(token0 != token1, "TOKEN0 AND TOKEN1 SHOULD BE DIFFERENT"); require(amountTotal0 != 0, "INVALID TOTAL AMOUNT OF TOKEN0"); require(amountTotal1 != 0, "INVALID TOTAL AMOUNT OF TOKEN1"); TokenInfo memory tokenInfo; tokenInfo.creator = creator; tokenInfo.token0 = token0; tokenInfo.token1 = token1; tokenInfo.amountTotal0 = amountTotal0; tokenInfo.amountTotal1 = amountTotal1; tokenInfo.maxAllocToken1 = maxAllocToken1; tokenInfo.amountSwap0 = 0; tokenInfo.amountSwap1 = 0; tokenInfos.push(tokenInfo); return tokenInfo; } modifier poolShouldExist(uint index) { require(index < tokenInfos.length, "POOL SHOULD EXIST"); _; } } // File contracts/PoolTime.sol pragma solidity ^0.6.0; contract PoolTime { struct TimeInfo { // timestamp when the pool will open uint openAt; // timestamp when the pool will close uint closeAt; // timestamp when users can claim their tokens uint claimAt; } mapping(uint => TimeInfo) public timeInfos; function _setPoolTime(uint index, uint openAt, uint closeAt, uint claimAt) internal returns (TimeInfo memory) { require(openAt >= block.timestamp, "INVALID OPEN_AT"); require(closeAt >= openAt, "INVALID CLOSE_AT"); require(claimAt == 0 || claimAt >= closeAt, "INVALID CLAIM_AT"); TimeInfo memory timeInfo; timeInfo.openAt = openAt; timeInfo.closeAt = closeAt; timeInfo.claimAt = claimAt; timeInfos[index] = timeInfo; return timeInfo; } function _isInstantClaim(uint index) internal view returns (bool) { return timeInfos[index].claimAt == 0; } modifier poolShouldClose(uint index) { require(timeInfos[index].closeAt <= block.timestamp, "POOL SHOULD BE CLOSED"); _; } modifier canClaim(uint index) { require(timeInfos[index].claimAt == 0 || timeInfos[index].claimAt <= block.timestamp, "CANNOT CLAIM"); _; } modifier poolShouldOpen(uint index) { require( timeInfos[index].openAt <= block.timestamp && block.timestamp < timeInfos[index].closeAt, "POOL SHOULD BE OPENED" ); _; } } // File contracts/TokenFixedSwap.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract TokenFixedSwap is Ownable, Whitelist, PoolToken, PoolTime { using SafeMath for uint; using SafeERC20 for IERC20; struct Pool { // token receiver address payable creator; // address of token0 address token0; // address of token1 address token1; // total amount of token0 uint amountTotal0; // total amount of token1 uint amountTotal1; // maximum allocation amount of token1 per address uint maxAllocToken1; // the timestamp in seconds the pool will open uint openAt; // the timestamp in seconds the pool will be closed uint closeAt; // the delay timestamp in seconds when buyers can claim after pool filled uint claimAt; } // team address => pool index => whether or not pool has been claimed mapping(address => mapping(uint => bool)) public poolClaimed; // user address => pool index => whether or not my pool has been claimed mapping(address => mapping(uint => bool)) public myClaimed; // user address => pool index => swapped amount of token0 mapping(address => mapping(uint => uint)) public myAmountSwapped0; // user address => pool index => swapped amount of token1 mapping(address => mapping(uint => uint)) public myAmountSwapped1; event Created(uint indexed index, address indexed sender, Pool pool); event Swapped(uint indexed index, address indexed sender, uint amount0, uint amount1); event PoolClaimed(uint indexed index, address indexed sender, uint amount0); event UserClaimed(uint indexed index, address indexed sender, uint amount0); function create(Pool memory pool, address[] memory whitelist_) public onlyOwner { // transfer amount of token0 to this contract IERC20 _token0 = IERC20(pool.token0); // uint token0BalanceBefore = _token0.balanceOf(address(this)); // _token0.safeTransferFrom(pool.creator, address(this), pool.amountTotal0); // require( // _token0.balanceOf(address(this)).sub(token0BalanceBefore) == pool.amountTotal0, // "DON'T SUPPORT DEFLATIONARY TOKEN" // ); // reset allowance to 0 _token0.safeApprove(address(this), 0); uint index = getPoolCount(); super._setEnableWhiteList(index, false); super._addWhitelist(index, whitelist_); super._setPoolToken(pool.creator, pool.token0, pool.token1, pool.amountTotal0, pool.amountTotal1, pool.maxAllocToken1); super._setPoolTime(index, pool.openAt, pool.closeAt, pool.claimAt); emit Created(index, msg.sender, pool); } function setEnableWhiteList(uint index, bool v) public onlyOwner { super._setEnableWhiteList(index, v); } function swap(uint index, uint amount1) external payable poolShouldExist(index) poolShouldOpen(index) checkInWhitelist(index, msg.sender) { TokenInfo memory tokenInfo = tokenInfos[index]; require(tokenInfo.amountTotal1 > tokenInfo.amountSwap1, "INSUFFICIENT SWAP AMOUNT"); // check if amount1 is exceeded uint excessAmount1 = 0; uint _amount1 = tokenInfo.amountTotal1.sub(tokenInfo.amountSwap1); if (_amount1 < amount1) { excessAmount1 = amount1.sub(_amount1); } else { _amount1 = amount1; } // check if amount0 is exceeded uint amount0 = _amount1.mul(tokenInfo.amountTotal0).div(tokenInfo.amountTotal1); uint _amount0 = tokenInfo.amountTotal0.sub(tokenInfo.amountSwap0); if (_amount0 > amount0) { _amount0 = amount0; } tokenInfos[index].amountSwap0 = tokenInfo.amountSwap0.add(_amount0); tokenInfos[index].amountSwap1 = tokenInfo.amountSwap1.add(_amount1); myAmountSwapped0[msg.sender][index] = myAmountSwapped0[msg.sender][index].add(_amount0); // check if swapped amount of token1 is exceeded maximum allowance if (tokenInfo.maxAllocToken1 != 0) { require( myAmountSwapped1[msg.sender][index].add(_amount1) <= tokenInfo.maxAllocToken1, "SWAP AMOUNT EXCEEDED" ); myAmountSwapped1[msg.sender][index] = myAmountSwapped1[msg.sender][index].add(_amount1); } // transfer amount of token1 to this contract if (tokenInfo.token1 == address(0)) { require(msg.value == amount1, "INVALID MSG.VALUE"); } else { require(msg.value == 0, "MSG.VALUE SHOULD BE ZERO"); IERC20(tokenInfo.token1).safeTransferFrom(msg.sender, address(this), amount1); } if (super._isInstantClaim(index)) { if (_amount0 > 0) { // send token0 to sender if (tokenInfo.token0 == address(0)) { msg.sender.transfer(_amount0); } else { IERC20(tokenInfo.token0).safeTransfer(msg.sender, _amount0); } } } if (excessAmount1 > 0) { // send excess amount of token1 back to sender if (tokenInfo.token1 == address(0)) { msg.sender.transfer(excessAmount1); } else { IERC20(tokenInfo.token1).safeTransfer(msg.sender, excessAmount1); } } // send token1 to creator if (_amount1 > 0) { if (tokenInfo.token1 == address(0)) { tokenInfo.creator.transfer(_amount1); } else { IERC20(tokenInfo.token1).safeTransfer(tokenInfo.creator, _amount1); } } emit Swapped(index, msg.sender, _amount0, _amount1); } function poolClaim(uint index) external poolShouldExist(index) poolShouldClose(index) canClaim(index) { TokenInfo memory tokenInfo = tokenInfos[index]; require(!poolClaimed[tokenInfo.creator][index], "POOL CLAIMED"); poolClaimed[tokenInfo.creator][index] = true; uint unSwapAmount0 = tokenInfo.amountTotal0.sub(tokenInfo.amountSwap0); if (unSwapAmount0 > 0) { IERC20(tokenInfo.token0).safeTransfer(tokenInfo.creator, unSwapAmount0); } emit PoolClaimed(index, msg.sender, unSwapAmount0); } function userClaim(uint index) external poolShouldExist(index) poolShouldClose(index) canClaim(index) { TokenInfo memory tokenInfo = tokenInfos[index]; require(!super._isInstantClaim(index), "NOT DELAYED CLAIM"); require(!myClaimed[msg.sender][index], "USER CLAIMED"); myClaimed[msg.sender][index] = true; if (myAmountSwapped0[msg.sender][index] > 0) { // send token0 to sender if (tokenInfo.token0 == address(0)) { msg.sender.transfer(myAmountSwapped0[msg.sender][index]); } else { IERC20(tokenInfo.token0).safeTransfer(msg.sender, myAmountSwapped0[msg.sender][index]); } } emit UserClaimed(index, msg.sender, myAmountSwapped0[msg.sender][index]); } function addWhitelist(uint index, address[] memory whitelist_) public onlyOwner { super._addWhitelist(index, whitelist_); } function removeWhitelist(uint index, address[] memory whitelist_) external onlyOwner { super._removeWhitelist(index, whitelist_); } }
check if amount1 is exceeded check if swapped amount of token1 is exceeded maximum allowance transfer amount of token1 to this contract send token0 to sender send excess amount of token1 back to sender send token1 to creator
function swap(uint index, uint amount1) external payable poolShouldExist(index) poolShouldOpen(index) checkInWhitelist(index, msg.sender) { TokenInfo memory tokenInfo = tokenInfos[index]; require(tokenInfo.amountTotal1 > tokenInfo.amountSwap1, "INSUFFICIENT SWAP AMOUNT"); uint excessAmount1 = 0; uint _amount1 = tokenInfo.amountTotal1.sub(tokenInfo.amountSwap1); if (_amount1 < amount1) { excessAmount1 = amount1.sub(_amount1); _amount1 = amount1; } uint _amount0 = tokenInfo.amountTotal0.sub(tokenInfo.amountSwap0); if (_amount0 > amount0) { _amount0 = amount0; } tokenInfos[index].amountSwap0 = tokenInfo.amountSwap0.add(_amount0); tokenInfos[index].amountSwap1 = tokenInfo.amountSwap1.add(_amount1); myAmountSwapped0[msg.sender][index] = myAmountSwapped0[msg.sender][index].add(_amount0); if (tokenInfo.maxAllocToken1 != 0) { require( myAmountSwapped1[msg.sender][index].add(_amount1) <= tokenInfo.maxAllocToken1, "SWAP AMOUNT EXCEEDED" ); myAmountSwapped1[msg.sender][index] = myAmountSwapped1[msg.sender][index].add(_amount1); } if (tokenInfo.token1 == address(0)) { require(msg.value == amount1, "INVALID MSG.VALUE"); require(msg.value == 0, "MSG.VALUE SHOULD BE ZERO"); IERC20(tokenInfo.token1).safeTransferFrom(msg.sender, address(this), amount1); } if (super._isInstantClaim(index)) { if (_amount0 > 0) { if (tokenInfo.token0 == address(0)) { msg.sender.transfer(_amount0); IERC20(tokenInfo.token0).safeTransfer(msg.sender, _amount0); } } } if (excessAmount1 > 0) { if (tokenInfo.token1 == address(0)) { msg.sender.transfer(excessAmount1); IERC20(tokenInfo.token1).safeTransfer(msg.sender, excessAmount1); } } if (_amount1 > 0) { if (tokenInfo.token1 == address(0)) { tokenInfo.creator.transfer(_amount1); IERC20(tokenInfo.token1).safeTransfer(tokenInfo.creator, _amount1); } } emit Swapped(index, msg.sender, _amount0, _amount1); }
280,091
/** *Submitted for verification at Etherscan.io on 2021-06-08 */ //SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @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); } contract TokenVesting { event TrancheCreated(uint8 indexed tranche_id, uint256 cliff_start, uint256 duration); event TrancheBalanceAdded(address indexed user, uint8 indexed tranche_id, uint256 amount); event TrancheBalanceRemoved(address indexed user, uint8 indexed tranche_id, uint256 amount); event StakeDeposited(address indexed user, uint256 amount, bytes32 vega_public_key); event StakeRemoved(address indexed user, uint256 amount); event IssuerPermitted(address indexed issuer, uint256 amount); event IssuerRevoked(address indexed issuer); event ControllerSet(address indexed new_controller); /// @notice controller is similar to "owner" in other contracts address public controller; /// @notice tranche_count starts at 1 to cause tranche 0 (perma-lock) to exist as the default tranche uint8 public tranche_count = 1; /// @notice user => has been migrated mapping(address => bool) public v1_migrated; /// @notice user => user_stat struct mapping(address=> user_stat) public user_stats; /// @notice total_locked is the total amount of tokens "on" this contract that are locked into a tranche uint256 public total_locked; /// @notice v1_address is the address for Vega's v1 ERC20 token that has already been deployed address public v1_address; // mainnet = 0xD249B16f61cB9489Fe0Bb046119A48025545b58a; /// @notice v2_address is the address for Vega's v2 ERC20 token that replaces v1 address public v2_address; /// @notice accuracy_scale is the multiplier to assist in integer division uint256 constant public accuracy_scale = 100000000000; /// @notice default_tranche_id is the tranche_id for the default tranche uint8 constant public default_tranche_id = 0; /****ADDRESS MIGRATION**/ /// @notice new address => old address mapping(address => address) public address_migration; /*****/ /// @param token_v1_address Vega's already deployed v1 ERC20 token address /// @param token_v2_address Vega's v2 ERC20 token and the token being vested here /// @dev emits Controller_Set event constructor(address token_v1_address, address token_v2_address, address[] memory old_addresses, address[] memory new_addresses) { require(old_addresses.length == new_addresses.length, "array length mismatch"); for(uint8 map_idx = 0; map_idx < old_addresses.length; map_idx++) { v1_migrated[old_addresses[map_idx]] = true; address_migration[new_addresses[map_idx]] = old_addresses[map_idx]; } v1_address = token_v1_address; /// @notice this initializes the total_locked with the amount of already issued v1 VEGA ERC20 tokens total_locked = IERC20(token_v1_address).totalSupply() - IERC20(token_v1_address).balanceOf(token_v1_address); v2_address = token_v2_address; controller = msg.sender; emit ControllerSet(controller); } /// @notice tranche_balance has the params necessary to track what a user is owed in a single tranche /// @param total_deposited is the total number of tokens deposited into this single tranche for a single user /// @param total_claimed is the total number of tokens in this tranche that have been withdrawn struct tranche_balance { uint256 total_deposited; uint256 total_claimed; } /// @notice user_stat is a struct that holds all the details needed to handle a single user's vesting /// @param total_in_all_tranches is the total number of tokens currently in all tranches that have been migrated to v2 /// @param lien total amount of locked tokens that have been marked for staking /// @param tranche_balances is a mapping of tranche_id => tranche_balance struct user_stat { uint256 total_in_all_tranches; uint256 lien; mapping (uint8 => tranche_balance) tranche_balances; } /// @notice tranche is a struct that hold the details needed for calculating individual tranche vesting /// @param cliff_start is a timestamp after which vesting starts /// @param duration is the number of seconds after cliff_start until the tranche is 100% vested struct tranche { uint256 cliff_start; uint256 duration; } /// @notice tranche_id => tranche struct mapping(uint8 => tranche) public tranches; /// @notice issuer address => permitted issuance allowance mapping(address => uint256) public permitted_issuance; /// @notice this function allows the contract controller to create a tranche /// @notice tranche zero is perma-locked and already exists prior to running this function, making the first vesting tranche "tranche:1" /// @param cliff_start is a timestamp in seconds of when vesting begins for this tranche /// @param duration is the number of seconds after cliff_start that the tranche will be fully vested function create_tranche(uint256 cliff_start, uint256 duration) public only_controller { tranches[tranche_count] = tranche(cliff_start, duration); emit TrancheCreated(tranche_count, cliff_start, duration); /// @notice sol ^0.8 comes with auto-overflow protection tranche_count++; } /// @notice this function allows the conroller or permitted issuer to issue tokens from this contract itself (no tranches) into the specified tranche /// @notice tranche MUST be created /// @notice once assigned to a tranche, tokens can never be clawed back, but they can be reassigned IFF they are in tranche_id:0 /// @param user The user being issued the tokens /// @param tranche_id the id of the target tranche /// @param amount number of tokens to be issued into tranche /// @dev emits Tranche_Balance_Added event function issue_into_tranche(address user, uint8 tranche_id, uint256 amount) public controller_or_issuer { require(tranche_id < tranche_count, "tranche_id out of bounds"); if(permitted_issuance[msg.sender] > 0){ /// @dev if code gets here, they are an issuer if not they must be the controller require(permitted_issuance[msg.sender] >= amount, "not enough permitted balance"); require(user != msg.sender, "cannot issue to self"); permitted_issuance[msg.sender] -= amount; } require( IERC20(v2_address).balanceOf(address(this)) - (total_locked + amount) >= 0, "contract token balance low" ); /// @dev only runs once if(!v1_migrated[user]){ uint256 bal = v1_bal(user); user_stats[user].tranche_balances[0].total_deposited += bal; user_stats[user].total_in_all_tranches += bal; v1_migrated[user] = true; } user_stats[user].tranche_balances[tranche_id].total_deposited += amount; user_stats[user].total_in_all_tranches += amount; total_locked += amount; emit TrancheBalanceAdded(user, tranche_id, amount); } /// @notice this function allows the controller to move tokens issued into tranche zero to the target tranche /// @notice can only be moved from tranche 0 /// @param user The user being issued the tokens /// @param tranche_id the id of the target tranche /// @param amount number of tokens to be moved from tranche 0 /// @dev emits Tranche_Balance_Removed event /// @dev emits Tranche_Balance_Added event function move_into_tranche(address user, uint8 tranche_id, uint256 amount) public only_controller { require(tranche_id > 0 && tranche_id < tranche_count); /// @dev only runs once if(!v1_migrated[user]){ uint256 bal = v1_bal(user); user_stats[user].tranche_balances[default_tranche_id].total_deposited += bal; user_stats[user].total_in_all_tranches += bal; v1_migrated[user] = true; } require(user_stats[user].tranche_balances[default_tranche_id].total_deposited >= amount); user_stats[user].tranche_balances[default_tranche_id].total_deposited -= amount; user_stats[user].tranche_balances[tranche_id].total_deposited += amount; emit TrancheBalanceRemoved(user, default_tranche_id, amount); emit TrancheBalanceAdded(user, tranche_id, amount); } /// @notice this view returns the balance of the given tranche for the given user /// @notice tranche 0 balance of a non-v1_migrated user will return user's v1 token balance as they are pre-issued to the current hodlers /// @param user Target user address /// @param tranche_id target tranche /// @return balance of target tranche of user function get_tranche_balance(address user, uint8 tranche_id) public view returns(uint256) { if(tranche_id == default_tranche_id && !v1_migrated[user]){ return v1_bal(user); } else { return user_stats[user].tranche_balances[tranche_id].total_deposited - user_stats[user].tranche_balances[tranche_id].total_claimed; } } /// @notice This view returns the amount that is currently vested in a given tranche /// @notice This does NOT take into account any current lien /// @param user Target user address /// @param tranche_id Target tranche /// @return number of tokens vested in the target tranche for the target user function get_vested_for_tranche(address user, uint8 tranche_id) public view returns(uint256) { if(block.timestamp < tranches[tranche_id].cliff_start){ return 0; } else if(block.timestamp > tranches[tranche_id].cliff_start + tranches[tranche_id].duration || tranches[tranche_id].duration == 0){ return user_stats[user].tranche_balances[tranche_id].total_deposited - user_stats[user].tranche_balances[tranche_id].total_claimed; } else { return (((( accuracy_scale * (block.timestamp - tranches[tranche_id].cliff_start) ) / tranches[tranche_id].duration ) * user_stats[user].tranche_balances[tranche_id].total_deposited ) / accuracy_scale ) - user_stats[user].tranche_balances[tranche_id].total_claimed; } } /// @notice This view returns the balance remaining in Vega V1 for a given user /// @notice Once migrated, the balance will always return zero, hence "remaining" /// @param user Target user /// @return remaining v1 balance function v1_bal(address user) internal view returns(uint256) { if(!v1_migrated[user]){ if(address_migration[user] != address(0)){ return IERC20(v1_address).balanceOf(user) + IERC20(v1_address).balanceOf(address_migration[user]); } else { return IERC20(v1_address).balanceOf(user); } } else { return 0; } } /// @notice This view returns the current amount of tokens locked in all tranches /// @notice This includes remaining v1 balance /// @param user Target user /// @return the current amount of tokens for target user in all tranches function user_total_all_tranches(address user) public view returns(uint256){ return user_stats[user].total_in_all_tranches + v1_bal(user); } /// @notice This function withdraws all the currently available vested tokens from the target tranche /// @notice This will not allow a user's total tranch balance to go below the user's lien amount /// @dev Emits Tranche_Balance_Removed event if successful /// @param tranche_id Id of target tranche function withdraw_from_tranche(uint8 tranche_id) public { require(tranche_id != default_tranche_id); uint256 to_withdraw = get_vested_for_tranche(msg.sender, tranche_id); require(user_stats[msg.sender].total_in_all_tranches - to_withdraw >= user_stats[msg.sender].lien); user_stats[msg.sender].tranche_balances[tranche_id].total_claimed += to_withdraw; user_stats[msg.sender].total_in_all_tranches -= to_withdraw; total_locked -= to_withdraw; require(IERC20(v2_address).transfer(msg.sender, to_withdraw)); emit TrancheBalanceRemoved(msg.sender, tranche_id, to_withdraw); } /// @notice This function will put a lien on the user who runs this function /// @dev Emits Stake_Deposited event if successful /// @param amount Amount of tokens to stake /// @param vega_public_key Target Vega public key to be credited with the stake lock function stake_tokens(uint256 amount, bytes32 vega_public_key) public { require(user_stats[msg.sender].lien + amount > user_stats[msg.sender].lien); require(user_total_all_tranches(msg.sender) >= user_stats[msg.sender].lien + amount); //user applies this to themselves which only multisig control can remove user_stats[msg.sender].lien += amount; emit StakeDeposited(msg.sender, amount, vega_public_key); } /// @notice This function will remove the lien from the user who runs this function /// @notice clears "amount" of lien /// @dev emits Stake_Removed event if successful /// @param amount Amount of tokens to remove from Staking function remove_stake(uint256 amount) public { /// @dev TODO add multisigControl IFF needed /// @dev Solidity ^0.8 has overflow protection, if this next line overflows, the transaction will revert user_stats[msg.sender].lien -= amount; emit StakeRemoved(msg.sender, amount); } /// @notice This function allows the controller to permit the given address to issue the given Amount /// @notice Target users MUST have a zero (0) permitted issuance balance (try revoke_issuer) /// @dev emits Issuer_Permitted event /// @param issuer Target address to be allowed to issue given amount /// @param amount Number of tokens issuer is permitted to issue function permit_issuer(address issuer, uint256 amount) public only_controller { /// @notice revoke is required first to stop a simple double allowance attack require(amount > 0, "amount must be > 0"); require(permitted_issuance[issuer] == 0, "issuer already permitted, revoke first"); require(controller != issuer, "controller cannot be permitted issuer"); permitted_issuance[issuer] = amount; emit IssuerPermitted(issuer, amount); } /// @notice This function allows the controller to revoke issuance permission from given target /// @notice permitted_issuance must be greater than zero (0) /// @dev emits Issuer_Revoked event /// @param issuer Target address of issuer to be revoked function revoke_issuer(address issuer) public only_controller { require(permitted_issuance[issuer] != 0, "issuer already revoked"); permitted_issuance[issuer] = 0; emit IssuerRevoked(issuer); } /// @notice This function allows the controller to assign a new controller /// @dev Emits Controller_Set event /// @param new_controller Address of the new controller function set_controller(address new_controller) public only_controller { controller = new_controller; if(permitted_issuance[new_controller] > 0){ permitted_issuance[new_controller] = 0; emit IssuerRevoked(new_controller); } emit ControllerSet(new_controller); } /// @notice this modifier requires that msg.sender is the controller of this contract modifier only_controller { require( msg.sender == controller, "not controller" ); _; } /// @notice this modifier requires that msg.sender is the controller of this contract or has a permitted issuance remaining of more than zero (0) modifier controller_or_issuer { require( msg.sender == controller || permitted_issuance[msg.sender] > 0,"not controller or issuer" ); _; } }
This function will put a lien on the user who runs this function Emits Stake_Deposited event if successful amount Amount of tokens to stake vega_public_key Target Vega public key to be credited with the stake lockuser applies this to themselves which only multisig control can remove
function stake_tokens(uint256 amount, bytes32 vega_public_key) public { require(user_stats[msg.sender].lien + amount > user_stats[msg.sender].lien); require(user_total_all_tranches(msg.sender) >= user_stats[msg.sender].lien + amount); user_stats[msg.sender].lien += amount; emit StakeDeposited(msg.sender, amount, vega_public_key); }
10,633,224
pragma solidity ^0.4.24; // File: contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/rbac/Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address&#39; access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: contracts/rbac/RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * @dev Supports unlimited numbers of roles and addresses. * @dev See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It&#39;s also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: contracts/VeraCrowdsale.sol /** * @title Interface of Price oracle * @dev Implements methods of price oracle used in the crowdsale * @author OnGrid Systems */ contract PriceOracleIface { uint256 public ethPriceInCents; function getUsdCentsFromWei(uint256 _wei) public view returns (uint256) { } } /** * @title Interface of ERC-20 token * @dev Implements transfer methods and event used throughout crowdsale * @author OnGrid Systems */ contract TransferableTokenIface { function transfer(address to, uint256 value) public returns (bool) { } function balanceOf(address who) public view returns (uint256) { } event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title CrowdSale contract for Vera.jobs * @dev Keep the list of investors passed KYC, receive ethers to fallback, * calculate correspinding amount of tokens, add bonus (depending on the deposit size) * then transfers tokens to the investor&#39;s account * @author OnGrid Systems */ contract VeraCrowdsale is RBAC { using SafeMath for uint256; // Price of one token (1.00000...) in USD cents uint256 public tokenPriceInCents = 200; // Minimal amount of USD cents to invest. Transactions of less value will be reverted. uint256 public minDepositInCents = 1000; // Amount of USD cents raised. Continuously increments on each transaction. // Note: may be irrelevant because the actual amount of harvested ethers depends on ETH/USD price at the moment. uint256 public centsRaised; // Amount of tokens distributed by this contract. // Note: doesn&#39;t include previous phases of tokensale. uint256 public tokensSold; // Address of VERA ERC-20 token contract TransferableTokenIface public token; // Address of ETH price feed PriceOracleIface public priceOracle; // Wallet address collecting received ETH address public wallet; // constants defining roles for access control string public constant ROLE_ADMIN = "admin"; string public constant ROLE_BACKEND = "backend"; string public constant ROLE_KYC_VERIFIED_INVESTOR = "kycVerified"; // Value bonus configuration struct AmountBonus { // To understand which bonuses were applied bonus contains binary flag. // If several bonuses applied ids get summarized in resulting event. // Use values with a single 1-bit like 0x01, 0x02, 0x04, 0x08 uint256 id; // amountFrom and amountTo define deposit value range. // Bonus percentage applies if deposit amount in cents is within the boundaries uint256 amountFrom; uint256 amountTo; uint256 bonusPercent; } // The list of available bonuses. Filled by the constructor on contract initialization AmountBonus[] public amountBonuses; /** * Event for token purchase logging * @param investor who received tokens * @param ethPriceInCents ETH price at the moment of purchase * @param valueInCents deposit calculated to USD cents * @param bonusPercent total bonus percent (sum of all bonuses) * @param bonusIds flags of all the bonuses applied to the purchase */ event TokenPurchase( address indexed investor, uint256 ethPriceInCents, uint256 valueInCents, uint256 bonusPercent, uint256 bonusIds ); /** * @dev modifier to scope access to admins * // reverts if called not by admin */ modifier onlyAdmin() { checkRole(msg.sender, ROLE_ADMIN); _; } /** * @dev modifier to scope access of backend keys stored on * investor&#39;s portal * // reverts if called not by backend */ modifier onlyBackend() { checkRole(msg.sender, ROLE_BACKEND); _; } /** * @dev modifier allowing calls from investors successfully passed KYC verification * // reverts if called by investor who didn&#39;t pass KYC via investor&#39;s portal */ modifier onlyKYCVerifiedInvestor() { checkRole(msg.sender, ROLE_KYC_VERIFIED_INVESTOR); _; } /** * @dev Constructor initializing Crowdsale contract * @param _token address of the token ERC-20 contract. * @param _priceOracle ETH price feed * @param _wallet address where received ETH get forwarded */ constructor( TransferableTokenIface _token, PriceOracleIface _priceOracle, address _wallet ) public { require(_token != address(0), "Need token contract address"); require(_priceOracle != address(0), "Need price oracle contract address"); require(_wallet != address(0), "Need wallet address"); addRole(msg.sender, ROLE_ADMIN); token = _token; priceOracle = _priceOracle; wallet = _wallet; // solium-disable-next-line arg-overflow amountBonuses.push(AmountBonus(0x1, 800000, 1999999, 20)); // solium-disable-next-line arg-overflow amountBonuses.push(AmountBonus(0x2, 2000000, 2**256 - 1, 30)); } /** * @dev Fallback function receiving ETH sent to the contract address * sender must be KYC (Know Your Customer) verified investor. */ function () external payable onlyKYCVerifiedInvestor { uint256 valueInCents = priceOracle.getUsdCentsFromWei(msg.value); buyTokens(msg.sender, valueInCents); wallet.transfer(msg.value); } /** * @dev Withdraws all remaining (not sold) tokens from the crowdsale contract * @param _to address of tokens receiver */ function withdrawTokens(address _to) public onlyAdmin { uint256 amount = token.balanceOf(address(this)); require(amount > 0, "no tokens on the contract"); token.transfer(_to, amount); } /** * @dev Called when investor&#39;s portal (backend) receives non-ethereum payment * @param _investor address of investor * @param _cents received deposit amount in cents */ function buyTokensViaBackend(address _investor, uint256 _cents) public onlyBackend { if (! RBAC.hasRole(_investor, ROLE_KYC_VERIFIED_INVESTOR)) { addKycVerifiedInvestor(_investor); } buyTokens(_investor, _cents); } /** * @dev Computes total bonuses amount by value * @param _cents deposit amount in USD cents * @return total bonus percent (sum of applied bonus percents), bonusIds (sum of applied bonus flags) */ function computeBonuses(uint256 _cents) public view returns (uint256, uint256) { uint256 bonusTotal; uint256 bonusIds; for (uint i = 0; i < amountBonuses.length; i++) { if (_cents >= amountBonuses[i].amountFrom && _cents <= amountBonuses[i].amountTo) { bonusTotal += amountBonuses[i].bonusPercent; bonusIds += amountBonuses[i].id; } } return (bonusTotal, bonusIds); } /** * @dev Calculates amount of tokens by cents * @param _cents deposit amount in USD cents * @return amount of tokens investor receive for the deposit */ function computeTokens(uint256 _cents) public view returns (uint256) { uint256 tokens = _cents.mul(10 ** 18).div(tokenPriceInCents); (uint256 bonusPercent, ) = computeBonuses(_cents); uint256 bonusTokens = tokens.mul(bonusPercent).div(100); if (_cents >= minDepositInCents) { return tokens.add(bonusTokens); } } /** * @dev Add admin role to an address * @param addr address */ function addAdmin(address addr) public onlyAdmin { addRole(addr, ROLE_ADMIN); } /** * @dev Revoke admin privileges from an address * @param addr address */ function delAdmin(address addr) public onlyAdmin { removeRole(addr, ROLE_ADMIN); } /** * @dev Add backend privileges to an address * @param addr address */ function addBackend(address addr) public onlyAdmin { addRole(addr, ROLE_BACKEND); } /** * @dev Revoke backend privileges from an address * @param addr address */ function delBackend(address addr) public onlyAdmin { removeRole(addr, ROLE_BACKEND); } /** * @dev Mark investor&#39;s address as KYC-verified person * @param addr address */ function addKycVerifiedInvestor(address addr) public onlyBackend { addRole(addr, ROLE_KYC_VERIFIED_INVESTOR); } /** * @dev Revoke KYC verification from the person * @param addr address */ function delKycVerifiedInvestor(address addr) public onlyBackend { removeRole(addr, ROLE_KYC_VERIFIED_INVESTOR); } /** * @dev Calculates and applies bonuses and implements actual token transfer and events * @param _investor address of the beneficiary receiving tokens * @param _cents amount of deposit in cents */ function buyTokens(address _investor, uint256 _cents) internal { (uint256 bonusPercent, uint256 bonusIds) = computeBonuses(_cents); uint256 tokens = computeTokens(_cents); require(tokens > 0, "value is not enough"); token.transfer(_investor, tokens); centsRaised = centsRaised.add(_cents); tokensSold = tokensSold.add(tokens); emit TokenPurchase( _investor, priceOracle.ethPriceInCents(), _cents, bonusPercent, bonusIds ); } }
Computes total bonuses amount by value _cents deposit amount in USD cents return total bonus percent (sum of applied bonus percents), bonusIds (sum of applied bonus flags)/
function computeBonuses(uint256 _cents) public view returns (uint256, uint256) { uint256 bonusTotal; uint256 bonusIds; for (uint i = 0; i < amountBonuses.length; i++) { if (_cents >= amountBonuses[i].amountFrom && _cents <= amountBonuses[i].amountTo) { bonusTotal += amountBonuses[i].bonusPercent; bonusIds += amountBonuses[i].id; } } return (bonusTotal, bonusIds); }
2,110,680
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./BokkyPooBahsDateTimeLibrary.sol"; contract BlankTokenVesting is Ownable { using SafeMath for uint256; using BokkyPooBahsDateTimeLibrary for uint256; using SafeERC20 for IERC20; event DistributionAdded(address indexed investor, address indexed caller, uint256 allocation); event DistributionRemoved(address indexed investor, address indexed caller, uint256 allocation); event WithdrawnTokens(address indexed investor, uint256 value); event RecoverToken(address indexed token, uint256 indexed amount); enum DistributionType { MARKETING, LIQUIDITY, TEAM, ADVISORS, DEVELOPMENT } uint256 private _initialTimestamp; IERC20 private _blankToken; struct Distribution { address beneficiary; uint256 withdrawnTokens; uint256 tokensAllotment; DistributionType distributionType; } mapping(DistributionType => Distribution) public distributionInfo; /// @dev Boolean variable that indicates whether the contract was initialized. bool public isInitialized = false; /// @dev Boolean variable that indicates whether the investors set was finalized. bool public isFinalized = false; uint256 constant _SCALING_FACTOR = 10**18; // decimals uint256[] marketingVesting = [ 25000000000000000000, 32500000000000000000, 40000000000000000000, 47500000000000000000, 55000000000000000000, 62500000000000000000, 70000000000000000000, 75000000000000000000, 80000000000000000000, 85000000000000000000, 90000000000000000000, 95000000000000000000, 100000000000000000000 ]; uint256[] liqudityVesting = [ 10000000000000000000, 17500000000000000000, 25000000000000000000, 32500000000000000000, 40000000000000000000, 45000000000000000000, 50000000000000000000, 55000000000000000000, 60000000000000000000, 65000000000000000000, 70000000000000000000, 75000000000000000000, 80000000000000000000, 85000000000000000000, 90000000000000000000, 95000000000000000000, 100000000000000000000 ]; uint256[] cliffVesting = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10000000000000000000, 17500000000000000000, 25000000000000000000, 35000000000000000000, 42500000000000000000, 50000000000000000000, 60000000000000000000, 67500000000000000000, 75000000000000000000, 85000000000000000000, 92500000000000000000, 100000000000000000000 ]; /// @dev Checks that the contract is initialized. modifier initialized() { require(isInitialized, "not initialized"); _; } /// @dev Checks that the contract is initialized. modifier notInitialized() { require(!isInitialized, "initialized"); _; } // Marketing: 0x10535712A3cFA961b82615D1FF0252604B4b0455 // Liquidity: 0xAF03Ee6959663A93df252D2423587AA7715c67A0 // Team: 0x67cC023e03051a3901849390e3EEDBd429840858 // Advisors: 0x8e07271e057b4FA4aA127926955Fb6EFe4ab80FC // Development: 0xE6bC3cE3290E3411c4E46fD4747e0f789F89F23c constructor( address _token, address _marketing, address _liquidity, address _team, address _advisors, address _development ) { require(address(_token) != address(0x0), "Blank token address is not valid"); _blankToken = IERC20(_token); _addDistribution(_marketing, DistributionType.MARKETING, 12500000 * _SCALING_FACTOR, 3125000 * _SCALING_FACTOR); _addDistribution(_liquidity, DistributionType.LIQUIDITY, 40000000 * _SCALING_FACTOR, 4000000 * _SCALING_FACTOR); _addDistribution(_team, DistributionType.TEAM, 15000000 * _SCALING_FACTOR, 0); _addDistribution(_advisors, DistributionType.ADVISORS, 5000000 * _SCALING_FACTOR, 0); _addDistribution(_development, DistributionType.DEVELOPMENT, 15625000 * _SCALING_FACTOR, 0); } /// @dev Returns initial timestamp function getInitialTimestamp() public view returns (uint256 timestamp) { return _initialTimestamp; } /// @dev Adds Distribution. This function doesn't limit max gas consumption, /// so adding too many investors can cause it to reach the out-of-gas error. /// @param _beneficiary The address of distribution. /// @param _tokensAllotment The amounts of the tokens that belong to each investor. function _addDistribution( address _beneficiary, DistributionType _distributionType, uint256 _tokensAllotment, uint256 _withdrawnTokens ) internal { require(_beneficiary != address(0), "Invalid address"); require(_tokensAllotment > 0, "the investor allocation must be more than 0"); Distribution storage distribution = distributionInfo[_distributionType]; require(distribution.tokensAllotment == 0, "investor already added"); distribution.beneficiary = _beneficiary; distribution.withdrawnTokens = _withdrawnTokens; distribution.tokensAllotment = _tokensAllotment; distribution.distributionType = _distributionType; emit DistributionAdded(_beneficiary, _msgSender(), _tokensAllotment); } function withdrawTokens(uint256 _distributionType) external onlyOwner() initialized() { Distribution storage distribution = distributionInfo[DistributionType(_distributionType)]; uint256 tokensAvailable = withdrawableTokens(DistributionType(_distributionType)); require(tokensAvailable > 0, "no tokens available for withdrawl"); distribution.withdrawnTokens = distribution.withdrawnTokens.add(tokensAvailable); _blankToken.safeTransfer(distribution.beneficiary, tokensAvailable); emit WithdrawnTokens(_msgSender(), tokensAvailable); } /// @dev The starting time of TGE /// @param _timestamp The initial timestamp, this timestap should be used for vesting function setInitialTimestamp(uint256 _timestamp) external onlyOwner() notInitialized() { // isInitialized = true; _initialTimestamp = _timestamp; } function withdrawableTokens(DistributionType distributionType) public view returns (uint256 tokens) { Distribution storage distribution = distributionInfo[distributionType]; uint256 availablePercentage = _calculateAvailablePercentage(distributionType); // console.log("Available Percentage: %s", availablePercentage); uint256 noOfTokens = _calculatePercentage(distribution.tokensAllotment, availablePercentage); uint256 tokensAvailable = noOfTokens.sub(distribution.withdrawnTokens); // console.log("Withdrawable Tokens: %s", tokensAvailable); return tokensAvailable; } function _calculatePercentage(uint256 _amount, uint256 _percentage) private pure returns (uint256 percentage) { return _amount.mul(_percentage).div(100).div(1e18); } function _calculateAvailablePercentage(DistributionType distributionType) private view returns (uint256 _availablePercentage) { uint256 currentTimeStamp = block.timestamp; uint256 noOfMonths = BokkyPooBahsDateTimeLibrary.diffMonths(_initialTimestamp, currentTimeStamp); if (currentTimeStamp > _initialTimestamp) { if (distributionType == DistributionType.MARKETING) { return marketingVesting[noOfMonths]; } else if (distributionType == DistributionType.LIQUIDITY) { return liqudityVesting[noOfMonths]; } else if ( distributionType == DistributionType.TEAM || distributionType == DistributionType.ADVISORS || distributionType == DistributionType.DEVELOPMENT ) { return cliffVesting[noOfMonths]; } } } function recoverExcessToken(address _token, uint256 amount) external onlyOwner { IERC20(_token).safeTransfer(_msgSender(), amount); emit RecoverToken(_token, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 _days) { require(year >= 1970); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4 + (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101; _days = uint256(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } function timestampFromDate( uint256 year, uint256 month, uint256 day ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns ( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate( uint256 year, uint256 month, uint256 day ) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime( uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second ) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { (uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { (uint256 year, uint256 month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = ((_days + 3) % 7) + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = ((month - 1) % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = (yearMonth % 12) + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY); require(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // 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.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); } } } }
The starting time of TGE _timestamp The initial timestamp, this timestap should be used for vesting isInitialized = true;
function setInitialTimestamp(uint256 _timestamp) external onlyOwner() notInitialized() { _initialTimestamp = _timestamp; }
11,956,341
// SPDX-License-Identifier: UNLICENSED import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; pragma solidity ^0.8.0; /** * @title Loopy Donuts contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract LoopyDonuts is ERC721, ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; string public PROVENANCE; uint256 public MAX_TOKENS; uint256 public REVEAL_TIMESTAMP; uint public constant RESERVE = 50; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public donutPrice = 0.07 ether; uint256 public discountPrice1 = 0.06 ether; uint256 public discountPrice2 = 0.055 ether; uint256 public qtyDiscount1 = 5; uint256 public qtyDiscount2 = 10; uint public constant maxDonutPurchase = 20; bool public saleIsActive = false; // Base URIs - one for IPFS and the other for Arweave string public IpfsBaseURI; string public ArweaveBaseURI; string public mysteryDonutURI; // Contract lock - when set, prevents altering the base URLs saved in the smart contract bool public locked = false; enum StorageType { IPFS, ARWEAVE } StorageType public mainStorage; // Whitelist and Presale mapping(address => bool) Whitelist; bool public presaleIsActive = false; /** @param name - Name of ERC721 as used in openzeppelin @param symbol - Symbol of ERC721 as used in openzeppelin @param maxNftSupply - Maximum number of tokens to allow minting @param revealTs - Timestamp in seconds since epoch of the revealing time @param main - The initial StorageType value for mainStorage @param provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance. @param ipfsBase - Base URI for token metadata on IPFS @param arweaveBase - Base URI for token metadata on Arweave @param mysteryDonut - URI for pre-reveal Mystery Donut metadata */ constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 revealTs, StorageType main, string memory provenance, string memory ipfsBase, string memory arweaveBase, string memory mysteryDonut) ERC721(name, symbol) { MAX_TOKENS = maxNftSupply; REVEAL_TIMESTAMP = revealTs; mainStorage = main; PROVENANCE = provenance; IpfsBaseURI = ipfsBase; ArweaveBaseURI = arweaveBase; mysteryDonutURI = mysteryDonut; } /** * @dev Throws if the contract is already locked */ modifier notLocked() { require(!locked, "Contract already locked."); _; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * Reserve Donuts for future activities and for supporters */ function reserveDonuts() public onlyOwner { uint supply = totalSupply(); uint i; for (i = 0; i < RESERVE; i++) { _safeMint(msg.sender, supply + i); } } /** * Sets the reveal timestamp */ function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner notLocked { REVEAL_TIMESTAMP = revealTimeStamp; } /* * Set provenance hash - just in case there is an error * Provenance hash is set in the contract construction time, * ideally there is no reason to ever call it. */ function setProvenanceHash(string memory provenanceHash) public onlyOwner notLocked { PROVENANCE = provenanceHash; } /** * @dev Pause sale if active, activate if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * @dev Pause presale if active, activate if paused */ function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } /** * @dev Adds addresses to the whitelist */ function addToWhitelist(address[] calldata addrs) external onlyOwner notLocked { for (uint i=0; i<addrs.length; i++) { Whitelist[addrs[i]] = true; } } /** * @dev Removes addresses from the whitelist */ function removeFromWhitelist(address[] calldata addrs) external onlyOwner notLocked { for (uint i=0; i<addrs.length; i++) { Whitelist[addrs[i]] = false; } } function registerForPresale() external { require(!presaleIsActive, "The presale has already begun!"); require(!isSenderInWhitelist(), "Already registered for the presale!"); Whitelist[msg.sender] = true; } /** * @dev Checks if an address is in the whitelist */ function isAddressInWhitelist(address addr) public view returns (bool) { return Whitelist[addr]; } /** * @dev Checks if the sender's address is in the whitelist */ function isSenderInWhitelist() public view returns (bool) { return Whitelist[msg.sender]; } /** * @dev locks the contract (prevents changing the metadata base uris) */ function lock() public onlyOwner notLocked { require(bytes(IpfsBaseURI).length > 0 && bytes(ArweaveBaseURI).length > 0, "Thou shall not lock prematurely!"); require(totalSupply() == MAX_TOKENS, "Not all Donuts are minted yet!"); locked = true; } /** * @dev Set the starting index for the collection */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set."); require(startingIndexBlock != 0, "Starting index block must be set."); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_TOKENS; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_TOKENS; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * @dev Set the starting index block for the collection, essentially unblocking * setting starting index */ function manualSetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set."); startingIndexBlock = block.number; } /** * @dev Sets the prices for minting - in case of cataclysmic ETH price movements */ function setPrices(uint256 single, uint256 discount1, uint256 discount2) external onlyOwner notLocked { require(single >= discount1 && discount1 >= discount2 && discount2 > 0, "Invalid prices."); donutPrice = single; discountPrice1 = discount1; discountPrice2 = discount2; } /** * @dev Sets the quantities that are eligible for discount. */ function setDiscountQunatities(uint256 qty1, uint256 qty2) external onlyOwner notLocked { require( 0 < qty1 && qty1 <= qty2, "Invalid quantities."); qtyDiscount1 = qty1; qtyDiscount2 = qty2; } /** * @dev Sets the IPFS Base URI for computing {tokenURI}. * Ideally we will have already uploaded everything before deploying the contract. * This method - along with {setArweaveBaseURI} - should only be called if we didn't * complete uploading the images and metadata to IPFS and Arweave or if there is an unforseen error. */ function setIpfsBaseURI(string memory newURI) public onlyOwner notLocked { IpfsBaseURI = newURI; } /** * @dev Sets the Arweave Base URI for computing {arweaveTokenURI}. */ function setArweaveBaseURI(string memory newURI) public onlyOwner notLocked { ArweaveBaseURI = newURI; } /** * @dev Sets the Mystrey Donut's URI */ function setMysteryDonutURI(string memory mystery) public onlyOwner notLocked { mysteryDonutURI = mystery; } /** * @dev Sets the main metadata Storage baseUri. */ function setMainStorage(StorageType stype) public onlyOwner notLocked { mainStorage = stype; } /** * @dev Returns the URI to the token's metadata stored on Arweave */ function arweaveTokenURI(uint256 tokenId) public view returns (string memory) { return getTokenURI(tokenId, StorageType.ARWEAVE); } /** * @dev Returns the URI to the token's metadata stored on IPFS */ function ipfsTokenURI(uint256 tokenId) public view returns (string memory) { return getTokenURI(tokenId, StorageType.IPFS); } /** * @dev Returns the tokenURI if exists and using the default - * aka main - metadata storage pointer specified by {mainStorage}. * See {IERC721Metadata-tokenURI} for more details. */ function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { return getTokenURI(tokenId, mainStorage); } /** * @dev Returns the URI to the token's metadata stored on either Arweave or IPFS. * Takes into account the contracts' {startingIndex} which - alone - determines the allocation * of Loopy Donuts - ensuring a fair and completely random distribution. */ function getTokenURI(uint256 tokenId, StorageType origin) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (startingIndex == 0) { return mysteryDonutURI; } string memory base; string memory sequenceId = ( (tokenId + startingIndex) % MAX_TOKENS ).toString(); if (origin == StorageType.IPFS) { base = IpfsBaseURI; } else { base = ArweaveBaseURI; } // Deployer should make sure that the selected base has a trailing '/' return bytes(base).length > 0 ? string( abi.encodePacked(base, sequenceId, ".json") ) : ""; } /** * @dev Returns the base URI. Overrides empty string returned by base class. * Unused because we override {tokenURI}. * Included for completeness-sake. */ function _baseURI() internal view override(ERC721) returns (string memory) { if (mainStorage == StorageType.IPFS) { return IpfsBaseURI; } else { return ArweaveBaseURI; } } /** * @dev Returns the base URI. Public facing method. * Included for completeness-sake and folks that want just the base. */ function baseURI() public view returns (string memory) { return _baseURI(); } /** * @dev Actual function that performs minting */ function _mintDonuts(uint numberOfTokens, address sender) internal { for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * @dev Mints Loopy Donuts * Ether value sent must exactly match. */ function mintDonut(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Donuts."); require(numberOfTokens <= maxDonutPurchase, "Can only mint 20 donuts at a time."); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Donuts."); require(getPricePerUnit(numberOfTokens).mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _mintDonuts(numberOfTokens, msg.sender); } /** * @dev Mints Loopy Donuts during the presale. * Ether value sent must exactly match - * and only addresses in {Whitelist} are allowed to participate in the presale. */ function presaleMintDonut(uint numberOfTokens) public payable { require(presaleIsActive, "Presale is not active."); require(isSenderInWhitelist(), "Your address is not in the whitelist."); require(numberOfTokens <= maxDonutPurchase, "Can only mint 20 donuts at a time."); require(balanceOf(msg.sender).add(numberOfTokens) <= maxDonutPurchase, "Purchase would exceed presale limit of 20 Donuts per address."); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Donuts."); require(getPricePerUnit(numberOfTokens).mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _mintDonuts(numberOfTokens, msg.sender); } /** * @dev Gets the available pricing options [qty, pricePerUnit, ...] */ function getPricingOptions() public view returns (uint256[6] memory) { uint256[6] memory arr = [1, donutPrice, qtyDiscount1, discountPrice1, qtyDiscount2, discountPrice2]; return arr; } /** * @dev Get the price per unit based on number of donuts to mint */ function getPricePerUnit(uint numberOfTokens) public view returns (uint256) { if (numberOfTokens >= qtyDiscount2) { return discountPrice2; } else if (numberOfTokens >= qtyDiscount1) { return discountPrice1; } return donutPrice; } /** * @dev Do not allow renouncing ownership */ function renounceOwnership() public override(Ownable) onlyOwner {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
Returns the tokenURI if exists and using the default - aka main - metadata storage pointer specified by {mainStorage}. See {IERC721Metadata-tokenURI} for more details./
function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) { return getTokenURI(tokenId, mainStorage); }
15,862,393